summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSiep Kroonenberg <siepo@cybercomm.nl>2023-02-26 14:42:54 +0000
committerSiep Kroonenberg <siepo@cybercomm.nl>2023-02-26 14:42:54 +0000
commitc2cbe5554ef9b3243e33d38ed75cfd00542103fd (patch)
treeda3591d9e0b9b690cec136eec56853a130f537e6
parentb09967bfe2ae329f19b19973e14acd2b69754357 (diff)
ConTeXt LMTX: scripts
git-svn-id: svn://tug.org/texlive/trunk@66175 c570f23f-e606-0410-a88d-b1316a301751
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-cache.lua3
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-context.lua146
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-context.xml16
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-ctan.lua319
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-fonts.lua35
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-install.lua64
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-interface.lua138
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-patterns.lua24
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-pdf.lua26
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-spell.lua346
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-synctex.lua179
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-unicode.lua173
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-update.lua69
-rw-r--r--Master/texmf-dist/scripts/context/lua/mtx-vscode.lua417
-rwxr-xr-xMaster/texmf-dist/scripts/context/lua/mtxrun.lua1208
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/ctx.rb462
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/exa.rb407
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/file.rb150
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/kpse.rb399
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/kpse/drb.rb57
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/kpse/soap.rb79
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/kpse/trees.rb84
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/kpsedirect.rb34
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/kpsefast.rb934
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/kpseremote.rb116
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/kpserunner.rb87
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/logger.rb105
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/merge.rb139
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/mp.rb167
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/pdf.rb83
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/state.rb75
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/switch.rb637
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/system.rb121
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/tex.rb2182
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/texutil.rb1097
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/tool.rb291
-rw-r--r--Master/texmf-dist/scripts/context/ruby/base/variables.rb132
-rw-r--r--Master/texmf-dist/scripts/context/ruby/concheck.rb471
-rw-r--r--Master/texmf-dist/scripts/context/ruby/ctxtools.rb2779
-rw-r--r--Master/texmf-dist/scripts/context/ruby/graphics/gs.rb684
-rw-r--r--Master/texmf-dist/scripts/context/ruby/graphics/inkscape.rb113
-rw-r--r--Master/texmf-dist/scripts/context/ruby/graphics/magick.rb161
-rw-r--r--Master/texmf-dist/scripts/context/ruby/imgtopdf.rb86
-rw-r--r--Master/texmf-dist/scripts/context/ruby/pdftools.rb861
-rw-r--r--Master/texmf-dist/scripts/context/ruby/pstopdf.rb533
-rw-r--r--Master/texmf-dist/scripts/context/ruby/rlxtools.rb368
-rw-r--r--Master/texmf-dist/scripts/context/ruby/rscortool.rb63
-rw-r--r--Master/texmf-dist/scripts/context/ruby/rsfiltool.rb341
-rw-r--r--Master/texmf-dist/scripts/context/ruby/rslb/base.rb270
-rw-r--r--Master/texmf-dist/scripts/context/ruby/rslibtool.rb114
-rw-r--r--Master/texmf-dist/scripts/context/ruby/runtools.rb506
-rw-r--r--Master/texmf-dist/scripts/context/ruby/texexec.rb791
-rwxr-xr-xMaster/texmf-dist/scripts/context/ruby/texmfstart.rb1271
-rw-r--r--Master/texmf-dist/scripts/context/ruby/textools.rb1033
-rw-r--r--Master/texmf-dist/scripts/context/ruby/texutil.rb93
-rw-r--r--Master/texmf-dist/scripts/context/ruby/tmftools.rb165
-rw-r--r--Master/texmf-dist/scripts/context/ruby/xmltools.rb656
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/install/first-setup.bat87
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/install/first-setup.sh173
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/mswin/context.exebin4608 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/mswin/contextjit.exebin4608 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/mswin/ctxtools.exebin4608 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/mswin/luatools.exebin4608 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/mswin/mtxrun.dllbin7680 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/mswin/mtxrun.exebin4608 -> 0 bytes
-rw-r--r--Master/texmf-dist/scripts/context/stubs/mswin/mtxrun.lua27376
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/mswin/mtxrunjit.exebin4608 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/mswin/pstopdf.exebin4608 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/mswin/texexec.exebin4608 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/mswin/texmfstart.exebin4608 -> 0 bytes
-rw-r--r--Master/texmf-dist/scripts/context/stubs/setup/setuptex222
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/setup/setuptex.bat70
-rw-r--r--Master/texmf-dist/scripts/context/stubs/setup/setuptex.csh177
-rw-r--r--Master/texmf-dist/scripts/context/stubs/source/mtxrun_dll.c306
-rw-r--r--Master/texmf-dist/scripts/context/stubs/source/mtxrun_exe.c8
-rw-r--r--Master/texmf-dist/scripts/context/stubs/source/readme.txt40
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/unix/context2
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/unix/contextjit5
-rw-r--r--Master/texmf-dist/scripts/context/stubs/unix/ctxtools2
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/unix/luatools2
-rw-r--r--Master/texmf-dist/scripts/context/stubs/unix/mptopdf2
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/unix/mtxrun27376
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/unix/mtxrunjit5
-rw-r--r--Master/texmf-dist/scripts/context/stubs/unix/pstopdf2
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/unix/texexec2
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/unix/texmfstart2
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/context.exebin15360 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/contextjit.exebin15360 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/ctxtools.exebin15360 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/luatools.exebin15360 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/mptopdf.exebin15360 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/mtxrun.dllbin18432 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/mtxrun.exebin15360 -> 0 bytes
-rw-r--r--Master/texmf-dist/scripts/context/stubs/win64/mtxrun.lua27376
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/mtxrunjit.exebin15360 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/pstopdf.exebin15360 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/texexec.exebin15360 -> 0 bytes
-rwxr-xr-xMaster/texmf-dist/scripts/context/stubs/win64/texmfstart.exebin15360 -> 0 bytes
98 files changed, 2427 insertions, 103168 deletions
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-cache.lua b/Master/texmf-dist/scripts/context/lua/mtx-cache.lua
index 4f378ff0a69..79b9a118cf1 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-cache.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-cache.lua
@@ -78,7 +78,8 @@ local function erase(banner,path,list)
local kept = 0
for i=1,#list do
local filename = list[i]
- if find(filename,"luatex%-cache") then
+ -- if find(filename,"luatex%-cache") then
+ if find(filename,LUATEXENGINE .. "%-cache") then
remove(filename)
if isfile(filename) then
kept = kept + 1
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-context.lua b/Master/texmf-dist/scripts/context/lua/mtx-context.lua
index 7ae350111be..014a7d4efe4 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-context.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-context.lua
@@ -22,6 +22,7 @@ local setargument = environment.setargument
local filejoinname = file.join
local filebasename = file.basename
+local filenameonly = file.nameonly
local filepathpart = file.pathpart
local filesuffix = file.suffix
local fileaddsuffix = file.addsuffix
@@ -106,12 +107,14 @@ end
-- -- The way we use stubs will change in a bit in 2019 (mtxrun and context). We also normalize
-- -- the platforms to use a similar approach to this.
-local engine_new = file.nameonly(getargument("engine") or directives.value("system.engine"))
-local engine_old = file.nameonly(environment.ownmain) or file.nameonly(environment.ownbin)
+local engine_new = filenameonly(getargument("engine") or directives.value("system.engine"))
+local engine_old = filenameonly(environment.ownmain) or filenameonly(environment.ownbin)
local function restart(engine_old,engine_new)
- local ownname = file.join(file.dirname(environment.ownname),"mtxrun.lua")
- local command = format("%s --luaonly %q %s --redirected",engine_new,ownname,environment.reconstructcommandline())
+ local generate = environment.arguments.generate and (engine_new == "luatex" or engine_new == "luajittex")
+ local arguments = generate and "--generate" or environment.reconstructcommandline()
+ local ownname = filejoinname(filepathpart(environment.ownname),"mtxrun.lua")
+ local command = format("%s --luaonly %q %s --redirected",engine_new,ownname,arguments)
report(format("redirect %s -> %s: %s",engine_old,engine_new,command))
local result = os.execute(command)
os.exit(result == 0 and 0 or 1)
@@ -361,20 +364,29 @@ local function multipass_changed(oldhash, newhash)
return false
end
-local f_tempfile = formatters["%s-%s-%02d.tmp"]
+local f_tempfile_i = formatters["%s-%s-%02d.tmp"]
+local f_tempfile_s = formatters["%s-%s-keep.%s"]
local function backup(jobname,run,kind,filename)
- if run == 1 then
- for i=1,10 do
- local tmpname = f_tempfile(jobname,kind,i)
- if validfile(tmpname) then
- removefile(tmpname)
- report("removing %a",tmpname)
+ if run then
+ if run == 1 then
+ for i=1,10 do
+ local tmpname = f_tempfile_i(jobname,kind,i)
+ if validfile(tmpname) then
+ removefile(tmpname)
+ report("removing %a",tmpname)
+ end
end
end
- end
- if validfile(filename) then
- local tmpname = f_tempfile(jobname,kind,run or 1)
+ if validfile(filename) then
+ local tmpname = f_tempfile_i(jobname,kind,run or 1)
+ report("copying %a into %a",filename,tmpname)
+ file.copy(filename,tmpname)
+ else
+ report("no file %a, nothing kept",filename)
+ end
+ elseif validfile(filename) then
+ local tmpname = f_tempfile_s(jobname,kind,kind)
report("copying %a into %a",filename,tmpname)
file.copy(filename,tmpname)
else
@@ -395,10 +407,20 @@ local function multipass_copyluafile(jobname,run)
end
end
+local function multipass_copypdffile(jobname,run)
+ if run then
+ local pdfname = jobname..".pdf"
+ if validfile(pdfname) then
+ backup(jobname,false,"pdf",pdfname)
+ report()
+ end
+ end
+end
+
local function multipass_copylogfile(jobname,run)
- local logname = jobname..".log"
- if validfile(logname) then
- if run then
+ if run then
+ local logname = jobname..".log"
+ if validfile(logname) then
backup(jobname,run,"log",logname)
report()
end
@@ -659,6 +681,7 @@ function scripts.context.run(ctxdata,filename)
local a_purgeall = getargument("purgeall")
local a_purgeresult = getargument("purgeresult")
local a_global = getargument("global")
+ local a_runpath = getargument("runpath")
local a_timing = getargument("timing")
local a_profile = getargument("profile")
local a_batchmode = getargument("batchmode")
@@ -673,6 +696,7 @@ function scripts.context.run(ctxdata,filename)
local a_texformat = getargument("texformat")
local a_keeptuc = getargument("keeptuc")
local a_keeplog = getargument("keeplog")
+ local a_keeppdf = getargument("keeppdf")
local a_export = getargument("export")
local a_nodates = getargument("nodates")
local a_trailerid = getargument("trailerid")
@@ -692,9 +716,13 @@ function scripts.context.run(ctxdata,filename)
local basename = filebasename(filename) -- use splitter
local pathname = filepathpart(filename)
--
+ if filesuffix(filename) == "" then
+ filename = fileaddsuffix(filename,"tex")
+ end
+ --
if pathname == "" and not a_global and filename ~= usedfiles.nop then
filename = "./" .. filename
- if not validfile(filename) and not validfile(filename..".tex") then
+ if not validfile(filename) then
report("warning: no (local) file %a, proceeding",filename)
end
end
@@ -715,6 +743,31 @@ function scripts.context.run(ctxdata,filename)
formatfile, scriptfile = resolvers.locateformat(formatname)
end
--
+ local runpath = a_runpath or analysis.runpath
+ if type(runpath) == "string" and runpath ~= "" then
+ runpath = resolvers.resolve(runpath)
+ local currentdir = dir.current()
+ if not lfs.isdir(runpath) then
+ if dir.makedirs(runpath) then
+ report("runpath %a has been created",runpath)
+ else
+ report("error: runpath %a cannot be created",runpath)
+ os.exit()
+ end
+ end
+ if lfs.chdir(runpath) then
+ report("changing to runpath %a",runpath)
+ else
+ report("error: changing to runpath %a is impossible",runpath)
+ os.exit()
+ end
+ environment.arguments.path = currentdir
+ environment.arguments.runpath = runpath
+ if filepathpart(filename) == "." then
+ filename = filebasename(filename)
+ end
+ end
+ --
a_jithash = validstring(a_jithash or analysis.jithash) or nil
a_permitloadlib = a_permitloadlib or analysis.permitloadlib or nil
--
@@ -733,19 +786,23 @@ function scripts.context.run(ctxdata,filename)
return flag or plus -- flag wins
end
end
- local a_trackers = analysis.trackers
- local a_experiments = analysis.experiments
+ ----- a_trackers = analysis.trackers
+ ----- a_experiments = analysis.experiments
local directives = combine("directives")
local trackers = combine("trackers")
local experiments = combine("experiments")
--
+ local ownerpassword = environment.ownerpassword or analysis.ownerpassword
+ local userpassword = environment.userpassword or analysis.userpassword
+ local permissions = environment.permissions or analysis.permissions
+ --
if formatfile and scriptfile then
local suffix = validstring(getargument("suffix"))
local resultname = validstring(getargument("result"))
if not resultname or resultname == "" then
resultname = validstring(analysis.result)
end
- local resultpath = file.pathpart(resultname)
+ local resultpath = filepathpart(resultname)
if resultpath ~= "" then
resultname = nil
elseif suffix then
@@ -805,6 +862,10 @@ function scripts.context.run(ctxdata,filename)
export = a_export and true or nil,
nocompression = a_nocompression and true or nil,
texmfbinpath = os.selfdir,
+ --
+ ownerpassword = ownerpassword,
+ userpassword = userpassword,
+ permissions = permissions,
}
--
for k, v in next, environment.arguments do
@@ -816,6 +877,14 @@ function scripts.context.run(ctxdata,filename)
--
-- todo: --output-file=... in luatex
--
+ local usedname = jobname
+ local engine = analysis.engine or "luametatex"
+ if engine == "luametatex" and (mainfile == usedfiles.yes or mainfile == usedfiles.nop) and not getargument("redirected") then
+ mainfile = "" -- we don't need that
+ usedname = fulljobname
+ end
+ --
+ --
local l_flags = {
["interaction"] = a_batchmode,
-- ["synctex"] = false, -- context has its own way
@@ -825,7 +894,8 @@ function scripts.context.run(ctxdata,filename)
-- ["file-line-error-style"] = true,
-- ["fmt"] = formatfile,
-- ["lua"] = scriptfile,
- ["jobname"] = jobname,
+-- ["jobname"] = jobname,
+ ["jobname"] = usedname,
["jithash"] = a_jithash,
["permitloadlib"] = a_permitloadlib,
}
@@ -854,10 +924,9 @@ function scripts.context.run(ctxdata,filename)
--
-- kindofrun: 1:first run, 2:successive run, 3:once, 4:last of maxruns
--
- local engine = analysis.engine or "luametatex"
- if engine == "luametatex" and (mainfile == usedfiles.yes or mainfile == usedfiles.nop) then
- mainfile = "" -- we don't need that
- end
+ -- can be used to include pages from a previous run, --keeppdf or "% keeppdf" on first-line
+ --
+ multipass_copypdffile(jobname,a_keeppdf or analysis.keeppdf)
--
for currentrun=1,maxnofruns do
--
@@ -913,7 +982,7 @@ function scripts.context.run(ctxdata,filename)
end
--
if environment.arguments["ansilog"] then
- local logfile = file.replacesuffix(jobname,"log")
+ local logfile = filenewsuffix(jobname,"log")
local logdata = io.loaddata(logfile) or ""
if logdata ~= "" then
io.savedata(logfile,(gsub(logdata,"%[.-m","")))
@@ -1438,7 +1507,7 @@ end
function scripts.context.pages()
local filename = environment.files[1]
if filename then
- local u = table.load(file.addsuffix(filename,"tuc"))
+ local u = table.load(fileaddsuffix(filename,"tuc"))
if u then
local p = u.structures.pages.collected
local l = u.structures.lists.collected
@@ -1637,19 +1706,16 @@ end
-- todo: we need to do a dummy run
-function scripts.context.trackers()
- environment.files = { resolvers.findfile("m-trackers.mkiv") }
+local function showsetter()
+ environment.files = { resolvers.findfile("mtx-context-setters.tex") }
multipass_nofruns = 1
setargument("purgeall",true)
scripts.context.run()
end
-function scripts.context.directives()
- environment.files = { resolvers.findfile("m-directives.mkiv") }
- multipass_nofruns = 1
- setargument("purgeall",true)
- scripts.context.run()
-end
+scripts.context.trackers = showsetter
+scripts.context.directives = showsetter
+scripts.context.experiments = showsetter
function scripts.context.logcategories()
environment.files = { resolvers.findfile("m-logcategories.mkiv") }
@@ -1664,6 +1730,12 @@ end
-- getting it done
+if getargument("pdftex") then
+ setargument("engine","pdftex")
+elseif getargument("xetex") then
+ setargument("engine","xetex")
+end
+
if getargument("timedlog") then
logs.settimedlog()
end
@@ -1781,7 +1853,7 @@ end
do
if getargument("wipebusy") then
- os.remove("context-is-busy.tmp")
+ removefile("context-is-busy.tmp")
end
end
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-context.xml b/Master/texmf-dist/scripts/context/lua/mtx-context.xml
index 98a75244b12..bf341c21a9f 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-context.xml
+++ b/Master/texmf-dist/scripts/context/lua/mtx-context.xml
@@ -148,7 +148,7 @@
<short>never initializes synctex (for production runs)</short>
</flag>
<flag name="synctex">
- <short>run with synctex enabled (better use \setupsynctex[state=start]</short>
+ <short>run with synctex enabled (better use \setupsynctex[state=start])</short>
</flag>
</subcategory>
<subcategory>
@@ -202,6 +202,9 @@
<flag name="keeptuc">
<short>keep previous tuc files (jobname-tuc-[run].tmp)</short>
</flag>
+ <flag name="keeppdf">
+ <short>keep previous pdf files (jobname-pdf-keep.tmp)</short>
+ </flag>
<flag name="keeplog">
<short>keep previous log files (jobname-log-[run].tmp)</short>
</flag>
@@ -220,6 +223,17 @@
<short>show extras</short>
</flag>
</subcategory>
+ <subcategory>
+ <flag name="ownerpassword">
+ <short>encrypt the (pdf) file using this master password</short>
+ </flag>
+ <flag name="userpassword">
+ <short>use an additional password for opening the document</short>
+ </flag>
+ <flag name="permissions">
+ <short>list of: print, modify, extract, add, fillin, assemble, quality</short>
+ </flag>
+ </subcategory>
</category>
<category name="special">
<subcategory>
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-ctan.lua b/Master/texmf-dist/scripts/context/lua/mtx-ctan.lua
new file mode 100644
index 00000000000..798a2da02f4
--- /dev/null
+++ b/Master/texmf-dist/scripts/context/lua/mtx-ctan.lua
@@ -0,0 +1,319 @@
+if not modules then modules = { } end modules ['mtx-ctan'] = {
+ version = 1.00,
+ comment = "companion to mtxrun.lua",
+ author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
+ copyright = "PRAGMA ADE / ConTeXt Development Team",
+ license = "see context related readme files"
+}
+
+-- This is just an experiment. Some day I want to be able to install fonts this way
+-- but maybe fetching tex live packages is also an option (I need to check if there
+-- is an api for that ... in wintertime). Normally fonts come from the web but I had
+-- to fetch newcm from ctan, so ...
+--
+-- mtxrun --script ctan --packages --pattern=computermodern
+
+-- http://www.ctan.org/json/2.0/packages
+-- http://www.ctan.org/json/2.0/pkg/name
+-- http://www.ctan.org/json/2.0/topics : key details
+-- http://www.ctan.org/json/2.0/topic/name : key details
+-- http://www.ctan.org/json/2.0/topic/name?ref=true : key details packages
+
+local lower, find, gsub = string.lower, string.find, string.gsub
+local write_nl = (logs and logs.writer) or (texio and texio.write_nl) or print
+local xmlconvert, xmltext, xmlattr, xmlcollected = xml.convert, xml.text, xml.attribute, xml.collected
+
+local helpinfo = [[
+<?xml version="1.0"?>
+<application>
+ <metadata>
+ <entry name="name">mtx-ctan</entry>
+ <entry name="detail">Dealing with CTAN</entry>
+ <entry name="version">1.00</entry>
+ </metadata>
+ <flags>
+ <category name="basic">
+ <subcategory>
+ <flag name="packages"><short>list available packages</short></flag>
+ <flag name="topics"><short>list available topics</short></flag>
+ <flag name="detail"><short>show details about package</short></flag>
+ <flag name="pattern" value="string"><short>use this pattern, otherwise first argument</short></flag>
+ </subcategory>
+ </category>
+ </flags>
+</application>
+]]
+
+local application = logs.application {
+ name = "mtx-ctan",
+ banner = "Dealing with CTAN",
+ helpinfo = helpinfo,
+}
+
+local report = application.report
+
+scripts = scripts or { }
+scripts.ctan = scripts.ctan or { }
+
+local okay, json = pcall(require,"util-jsn")
+local okay, curl = pcall(require,"libs-imp-curl")
+ pcall(require,"char-ini")
+
+local jsontolua = json and json.tolua
+local shaped = characters and characters.shaped or lower
+
+-- local ignore = {
+-- "latex",
+-- "plain",
+-- "xetex",
+-- }
+
+-- what is the url to fetch a zip
+
+-- We cannot use the socket library because we don't compile that massive amount of
+-- ssl code into lua(meta)tex. aybe some day one fo these small embedded libraries
+-- makes sense but there are so many changes in all that security stuff that it
+-- defeats long term stability of the ecosystem anyway ... just like some of my old
+-- devices suddenly are no longer accessible with modern browsers I expect it to
+-- happen everywhere. I'm not sure why ctan can't support http because I see no
+-- added value in the 's' here.
+
+local ctanurl = "https://www.ctan.org/" .. (json and "json" or "xml") .. "/2.0/"
+
+local fetched = curl and
+
+ function(str)
+ local data, message = curl.fetch {
+ url = ctanurl .. str,
+ sslverifyhost = false,
+ sslverifypeer = false,
+ }
+ if not data then
+ report("some error: %s",message)
+ end
+ return data
+ end
+
+or
+
+ function(str)
+ -- So, no redirect to http, which means that we cannot use the built in socket
+ -- library. What if the client is happy with http?
+ local data = os.resultof("curl -sS " .. ctanurl .. str)
+ -- print(data)
+ return data
+ end
+
+-- for j=1,#ignore do
+-- if find(str,ignore[j]) then
+-- return false
+-- end
+-- end
+
+local function strfound(pattern,str)
+ if not pattern then
+ return true
+ else
+ local str = lower(shaped(str))
+ if find(str,pattern) then
+ return true
+ else
+ str = gsub(str,"[^a-zA-Z0-9]","")
+ if find(str,pattern) then
+ return true
+ else
+ return false
+ end
+ end
+ end
+end
+
+local function showresult(found)
+ if #found > 2 then
+ utilities.formatters.formatcolumns(found)
+ report("")
+ for k=1,#found do
+ report(found[k])
+ end
+ report("")
+ end
+end
+
+local function checkedpattern(pattern)
+ if pattern then
+ return lower(shaped(pattern))
+ end
+end
+
+local validdata = json and
+
+ function(data)
+ if data then
+ data = jsontolua(data)
+ if type(data) == "table" then
+ return data
+ else
+ report("unable to handle this json data")
+ end
+ else
+ report("unable to fetch packages")
+ end
+ end
+
+or
+
+ function(data)
+ if data then
+ data = xmlconvert(data)
+ if data.error then
+ report("unable to handle this json data")
+ else
+ return data
+ end
+ else
+ report("unable to fetch packages")
+ end
+ end
+
+scripts.ctan.details = json and
+
+ function(name)
+ if name then
+ local data = validdata(fetched("pkg/" .. name))
+ if data then
+ report("")
+ -- report("key : %s",data.key or "-")
+ report("name : %s",data.name or "-")
+ report("caption : %s",data.caption or "-")
+ report("path : %s",data.ctan.path or "-")
+ report("")
+ end
+ end
+ end
+
+or
+
+ function (name)
+ if name then
+ local data = validdata(fetched("pkg/" .. name))
+ report("")
+ -- report("key : %s",data.key or "-")
+ report("name : %s",xmltext(data,"/entry/name"))
+ report("caption : %s",xmltext(data,"/entry/caption"))
+ report("path : %s",xmlattr(data,"/entry/ctan","path"))
+ report("")
+ end
+ end
+
+scripts.ctan.packages = json and
+
+ function(pattern)
+ local data = validdata(fetched("packages"))
+ if data then
+ local found = {
+ { "key", "name", "caption" },
+ { "", "", "" },
+ }
+ pattern = checkedpattern(pattern)
+ for i=1,#data do
+ local entry = data[i]
+ if strfound(pattern,entry.caption) then
+ found[#found+1] = { entry.key, entry.name, entry.caption }
+ end
+ end
+ showresult(found)
+ end
+ end
+
+or
+
+ function(pattern)
+ local data = validdata(fetched("packages"))
+ if data then
+ local found = {
+ { "key", "name", "caption" },
+ { "", "", "" },
+ }
+ pattern = checkedpattern(pattern)
+ for c in xmlcollected(data,"/packages/package") do
+ local at = c.at
+ if strfound(pattern,at.caption) then
+ found[#found+1] = { at.key, at.name, at.caption }
+ end
+ end
+ showresult(found)
+ end
+ end
+
+scripts.ctan.topics = json and
+
+ function (pattern)
+ local data = validdata(fetched("topics"))
+ if data then
+ local found = {
+ { "key", "details" },
+ { "", "" },
+ }
+ pattern = checkedpattern(pattern)
+ for i=1,#data do
+ local entry = data[i]
+ if strfound(pattern,entry.details) then
+ found[#found+1] = { entry.key or entry.name, entry.details } -- inconsistency between json and xml
+ end
+ end
+ showresult(found)
+ end
+ end
+
+or
+
+ function(pattern)
+ local data = validdata(fetched("topics"))
+ if data then
+ local found = {
+ { "name", "details" },
+ { "", "" },
+ }
+ pattern = checkedpattern(pattern)
+ for c in xmlcollected(data,"/topics/topic") do
+ local at = c.at
+ if strfound(pattern,at.caption) then
+ found[#found+1] = { at.key or at.name, at.details } -- inconsistency between json and xml
+ end
+ end
+ showresult(found)
+ end
+ end
+
+local function whatever()
+ report("")
+ report("using %s interface", json and "json" or "xml")
+ report("using curl %s", curl and "library" or "binary")
+ report("")
+end
+
+if environment.argument("packages") then
+ whatever()
+ scripts.ctan.packages(environment.argument("pattern") or environment.files[1])
+elseif environment.argument("topics") then
+ whatever()
+ scripts.ctan.topics(environment.argument("pattern") or environment.files[1])
+elseif environment.argument("details") then
+ whatever()
+ scripts.ctan.details(environment.files[1])
+elseif environment.argument("exporthelp") then
+ application.export(environment.argument("exporthelp"),environment.files[1])
+else
+ application.help()
+end
+
+-- scripts.ctan.packages(environment.argument("pattern") or environment.files[1])
+-- scripts.ctan.packages("font")
+-- scripts.ctan.details("tex")
+-- scripts.ctan.details("ipaex")
+
+-- scripts.ctan.packages("Półtawskiego")
+-- scripts.ctan.packages("Poltawskiego")
+
+-- scripts.ctan.topics("font")
+-- scripts.ctan.topics()
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-fonts.lua b/Master/texmf-dist/scripts/context/lua/mtx-fonts.lua
index 65a661ac40b..37107ea1e3f 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-fonts.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-fonts.lua
@@ -12,11 +12,11 @@ local givenfiles = environment.files
local suffix, addsuffix, removesuffix, replacesuffix = file.suffix, file.addsuffix, file.removesuffix, file.replacesuffix
local nameonly, basename, joinpath, collapsepath = file.nameonly, file.basename, file.join, file.collapsepath
-local lower = string.lower
+local lower, gsub = string.lower, string.gsub
local concat = table.concat
local write_nl = (logs and logs.writer) or (texio and texio.write_nl) or print
-local otlversion = 3.113
+local otlversion = 3.133
local helpinfo = [[
<?xml version="1.0"?>
@@ -60,6 +60,10 @@ local helpinfo = [[
<example><command>mtxrun --script font --list somename (== --pattern=*somename*)</command></example>
</subcategory>
<subcategory>
+ <example><command>mtxrun --script font --list --file filename</command></example>
+ <example><command>mtxrun --script font --list --name --pattern=*somefile*</command></example>
+ </subcategory>
+ <subcategory>
<example><command>mtxrun --script font --list --name somename</command></example>
<example><command>mtxrun --script font --list --name --pattern=*somename*</command></example>
</subcategory>
@@ -123,7 +127,7 @@ loadmodule("font-otr.lua")
loadmodule("font-cff.lua")
loadmodule("font-ttf.lua")
loadmodule("font-tmp.lua")
-loadmodule("font-dsp.lua")
+loadmodule("font-dsp.lua") -- autosuffix
loadmodule("font-oup.lua")
loadmodule("font-otl.lua")
@@ -183,6 +187,9 @@ function fonts.names.simple(alsotypeone)
local simplelist = { "ttf", "otf", "ttc", alsotypeone and "afm" or nil }
local name = "luatex-fonts-names.lua"
local path = collapsepath(caches.getwritablepath("..","..","generic","fonts","data"))
+
+ path = gsub(path, "luametatex%-cache", "luatex-cache") -- maybe have an option to force it
+
fonts.names.filters.list = simplelist
fonts.names.version = simpleversion -- this number is the same as in font-dum.lua
report("generating font database for 'luatex-fonts' version %s",fonts.names.version)
@@ -288,7 +295,7 @@ local function showfeatures(tag,specification)
else
done = true
end
- report(" % -8s % -8s % -8s",f,s,concat(table.sortedkeys(ss), " ")) -- todo: padd 4
+ report(" %-8s %-8s %-8s",f,s,concat(table.sortedkeys(ss), " ")) -- todo: padd 4
end
end
end
@@ -310,7 +317,7 @@ local function showfeatures(tag,specification)
report(" method feature formats")
report()
for k, v in table.sortedhash(methods) do
- report(" % -8s % -14s %s",k,v.feature,v.format)
+ report(" %-8s %-14s %s",k,v.feature,v.format)
end
end
end
@@ -406,46 +413,46 @@ function scripts.fonts.list()
if getargument("name") then
if pattern then
- --~ mtxrun --script font --list --name --pattern=*somename*
+ -- mtxrun --script font --list --name --pattern=*somename*
list_matches(fonts.names.list(string.topattern(pattern,true),reload,all),info)
elseif filter then
report("not supported: --list --name --filter",name)
elseif given then
- --~ mtxrun --script font --list --name somename
+ -- mtxrun --script font --list --name somename
list_matches(fonts.names.list(given,reload,all),info)
else
report("not supported: --list --name <no specification>",name)
end
elseif getargument("spec") then
if pattern then
- --~ mtxrun --script font --list --spec --pattern=*somename*
+ -- mtxrun --script font --list --spec --pattern=*somename*
report("not supported: --list --spec --pattern",name)
elseif filter then
- --~ mtxrun --script font --list --spec --filter="fontname=somename"
+ -- mtxrun --script font --list --spec --filter="fontname=somename"
list_specifications(fonts.names.getlookups(filter),info)
elseif given then
- --~ mtxrun --script font --list --spec somename
+ -- mtxrun --script font --list --spec somename
list_specifications(fonts.names.collectspec(given,reload,all),info)
else
report("not supported: --list --spec <no specification>",name)
end
elseif getargument("file") then
if pattern then
- --~ mtxrun --script font --list --file --pattern=*somename*
+ -- mtxrun --script font --list --file --pattern=*somename*
list_specifications(fonts.names.collectfiles(string.topattern(pattern,true),reload,all),info)
elseif filter then
report("not supported: --list --spec",name)
elseif given then
- --~ mtxrun --script font --list --file somename
+ -- mtxrun --script font --list --file somename
list_specifications(fonts.names.collectfiles(given,reload,all),info)
else
report("not supported: --list --file <no specification>",name)
end
elseif pattern then
- --~ mtxrun --script font --list --pattern=*somename*
+ -- mtxrun --script font --list --pattern=*somename*
list_matches(fonts.names.list(string.topattern(pattern,true),reload,all),info)
elseif given then
- --~ mtxrun --script font --list somename
+ -- mtxrun --script font --list somename
list_matches(fonts.names.list(given,reload,all),info)
elseif all then
pattern = "*"
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-install.lua b/Master/texmf-dist/scripts/context/lua/mtx-install.lua
index 614d20e9294..7efd8f5edee 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-install.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-install.lua
@@ -14,7 +14,7 @@ local helpinfo = [[
<metadata>
<entry name="name">mtx-install</entry>
<entry name="detail">ConTeXt Installer</entry>
- <entry name="version">2.00</entry>
+ <entry name="version">2.01</entry>
</metadata>
<flags>
<category name="basic">
@@ -28,27 +28,55 @@ local helpinfo = [[
<flag name="update"><short>update context</short></flag>
<flag name="erase"><short>wipe the cache</short></flag>
<flag name="identify"><short>create list of files</short></flag>
+ <flag name="secure"><short>use curl for https</short></flag>
</subcategory>
</category>
</flags>
</application>
]]
+local type, tonumber = type, tonumber
local gsub, find, escapedpattern = string.gsub, string.find, string.escapedpattern
local round = math.round
local savetable, loadtable, sortedhash = table.save, table.load, table.sortedhash
local copyfile, joinfile, filesize, dirname, addsuffix, basename = file.copy, file.join, file.size, file.dirname, file.addsuffix, file.basename
local isdir, isfile, walkdir, pushdir, popdir, currentdir = lfs.isdir, lfs.isfile, lfs.dir, lfs.chdir, dir.push, dir.pop, currentdir
local mkdirs, globdir = dir.mkdirs, dir.glob
-local osremove, osexecute, ostype = os.remove, os.execute, os.type
+local osremove, osexecute, ostype, resultof = os.remove, os.execute, os.type, os.resultof
local savedata = io.savedata
local formatters = string.formatters
+local httprequest = socket.http.request
-local fetch = socket.http.request
+local usecurl = false
+
+local function checkcurl()
+ local s = resultof("curl --version")
+ return type(s) == "string" and find(s,"libcurl") and find(s,"rotocols")
+end
+
+local function fetch(url)
+ local data = nil
+ local detail = nil
+ if usecurl and find(url,"^https") then
+ data = resultof("curl " .. url)
+ else
+ data, detail = httprequest(url)
+ end
+ if type(data) ~= "string" then
+ data = false
+ elseif #data < 2048 then
+ local n, t = find(data,"<head>%s*<title>%s*(%d+)%s(.-)</title>")
+ if tonumber(n) then
+ data = false
+ detail = n .. " " .. t
+ end
+ end
+ return data, detail
+end
local application = logs.application {
name = "mtx-install",
- banner = "ConTeXt Installer 2.00",
+ banner = "ConTeXt Installer 2.01",
helpinfo = helpinfo,
}
@@ -75,11 +103,14 @@ local platforms = {
["windows"] = "mswin",
["win32"] = "mswin",
["win"] = "mswin",
+ ["arm32"] = "windows-arm32",
+ ["windows-arm32"] = "windows-arm32",
--
["mswin-64"] = "win64",
["windows-64"] = "win64",
["win64"] = "win64",
["arm64"] = "windows-arm64",
+ ["windows-arm64"] = "windows-arm64",
--
["linux"] = "linux",
["linux-32"] = "linux",
@@ -93,9 +124,9 @@ local platforms = {
--
["linux-armhf"] = "linux-armhf",
--
- ["openbsd"] = "openbsd6.8",
- ["openbsd-i386"] = "openbsd6.8",
- ["openbsd-amd64"] = "openbsd6.8-amd64",
+ ["openbsd"] = "openbsd7.2",
+ ["openbsd-i386"] = "openbsd7.2",
+ ["openbsd-amd64"] = "openbsd7.2-amd64",
--
["freebsd"] = "freebsd",
["freebsd-i386"] = "freebsd",
@@ -121,10 +152,8 @@ local platforms = {
["macosx"] = "osx-64",
["osx"] = "osx-64",
["osx-64"] = "osx-64",
--- ["osx-arm"] = "osx-arm64",
--- ["osx-arm64"] = "osx-arm64",
- ["osx-arm"] = "osx-64",
- ["osx-arm64"] = "osx-64",
+ ["osx-arm"] = "osx-arm64",
+ ["osx-arm64"] = "osx-arm64",
--
-- ["solaris-intel"] = "solaris-intel",
--
@@ -589,6 +618,11 @@ function install.update()
end
run("%s --make en", contextbin)
+ -- in case we also install luatex:
+
+ run("%s --luatex --generate",contextbin)
+ run("%s --luatex --make en", contextbin)
+
-- in calling script: update mtxrun.exe and mtxrun.lua
report("")
@@ -602,6 +636,14 @@ function install.update()
report("update, done")
end
+if environment.argument("secure") then
+ usecurl = checkcurl()
+ if not usecurl then
+ report("no curl installed, quitting")
+ os.exit()
+ end
+end
+
if environment.argument("identify") then
install.identify()
elseif environment.argument("install") then
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-interface.lua b/Master/texmf-dist/scripts/context/lua/mtx-interface.lua
index a335560fa56..ec2da63cce0 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-interface.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-interface.lua
@@ -7,9 +7,9 @@ if not modules then modules = { } end modules ['mtx-cache'] = {
}
local concat, sort, insert = table.concat, table.sort, table.insert
-local gsub, format, gmatch, find = string.gsub, string.format, string.gmatch, string.find
+local gsub, format, gmatch, find, upper = string.gsub, string.format, string.gmatch, string.find, string.upper
local utfchar, utfgsub = utf.char, utf.gsub
-local sortedkeys = table.sortedkeys
+local sortedkeys, sortedhash, serialize = table.sortedkeys, table.sortedhash, table.serialize
local helpinfo = [[
<?xml version="1.0"?>
@@ -32,6 +32,7 @@ local helpinfo = [[
<flag name="bbedit"><short>generate bbedit interface files</short></flag>
<flag name="jedit"><short>generate jedit interface files</short></flag>
<flag name="textpad"><short>generate textpad interface files</short></flag>
+ <flag name="vim"><short>generate vim interface files</short></flag>
<flag name="text"><short>create text files for commands and environments</short></flag>
<flag name="raw"><short>report commands to the console</short></flag>
<flag name="check"><short>generate check file</short></flag>
@@ -71,19 +72,19 @@ local messageinterfaces = { 'en','cs','de','it','nl','ro','fr','pe','no' }
local function collect(filename,class,data)
if data then
- local result = { }
- for name, list in table.sortedhash(data) do
- result[#result+1] = format("keywordclass.%s.%s=\\\n",class,name)
+ local result, r = { }, 0
+ for name, list in sortedhash(data) do
+ r = r + 1 ; result[r] = format("keywordclass.%s.%s=\\\n",class,name)
for i=1,#list do
if i%5 == 0 then
- result[#result+1] = "\\\n"
+ r = r + 1 ; result[r] = "\\\n"
end
- result[#result+1] = format("%s ",list[i])
+ r = r + 1 ; result[r] = format("%s ",list[i])
end
- result[#result+1] = "\n\n"
+ r = r + 1 ; result[r] = "\n\n"
end
io.savedata(file.addsuffix(filename,"properties"),concat(result))
- io.savedata(file.addsuffix(filename,"lua"), table.serialize(data,true))
+ io.savedata(file.addsuffix(filename,"lua"),serialize(data,true))
else
os.remove(filename)
end
@@ -127,18 +128,18 @@ function flushers.jedit(collected)
for interface, whatever in next, collected do
local commands = whatever.commands
local environments = whatever.environments
- local result = { }
- result[#result+1] = "<?xml version='1.0'?>"
- result[#result+1] = "<!DOCTYPE MODE SYSTEM 'xmode.dtd'>\n"
- result[#result+1] = "<MODE>"
- result[#result+1] = "\t<RULES>"
- result[#result+1] = "\t\t<KEYWORDS>"
+ local result, r = { }, 0
+ r = r + 1 ; result[r] = "<?xml version='1.0'?>"
+ r = r + 1 ; result[r] = "<!DOCTYPE MODE SYSTEM 'xmode.dtd'>\n"
+ r = r + 1 ; result[r] = "<MODE>"
+ r = r + 1 ; result[r] = "\t<RULES>"
+ r = r + 1 ; result[r] = "\t\t<KEYWORDS>"
for i=1,#commands do
- result[#result+1] = format("\t\t\t<KEYWORD2>%s</KEYWORD2>",commands[i])
+ r = r + 1 ; result[r] = format("\t\t\t<KEYWORD2>%s</KEYWORD2>",commands[i])
end
- result[#result+1] = "\t\t</KEYWORDS>"
- result[#result+1] = "\t</RULES>"
- result[#result+1] = "</MODE>"
+ r = r + 1 ; result[r] = "\t\t</KEYWORDS>"
+ r = r + 1 ; result[r] = "\t</RULES>"
+ r = r + 1 ; result[r] = "</MODE>"
io.savedata(format("context-jedit-%s.xml",interface), concat(result),"\n")
end
end
@@ -147,18 +148,100 @@ function flushers.bbedit(collected)
for interface, whatever in next, collected do
local commands = whatever.commands
local environments = whatever.environments
- local result = {}
- result[#result+1] = "<?xml version='1.0'?>"
- result[#result+1] = "<key>BBLMKeywordList</key>"
- result[#result+1] = "<array>"
+ local result, r = { }, 0
+ r = r + 1 ; result[r] = "<?xml version='1.0'?>"
+ r = r + 1 ; result[r] = "<key>BBLMKeywordList</key>"
+ r = r + 1 ; result[r] = "<array>"
for i=1,#commands do
- result[#result+1] = format("\t<string>\\%s</string>",commands[i])
+ r = r + 1 ; result[r] = format("\t<string>\\%s</string>",commands[i])
end
- result[#result+1] = "</array>"
+ r = r + 1 ; result[r] = "</array>"
io.savedata(format("context-bbedit-%s.xml",interface), concat(result),"\n")
end
end
+-- The Vim export is maintained by Nicola Vitacolonna:
+
+local function vimcollect(filename,class,data)
+ if data then
+ local result, r = { }, 0
+ local endline = " contained\n"
+ if find(class,"^meta") then
+ endline = "\n"
+ end
+ r = r + 1 ; result[r] = "vim9script\n\n"
+ r = r + 1 ; result[r] = "# Vim syntax file\n"
+ r = r + 1 ; result[r] = "# Language: ConTeXt\n"
+ r = r + 1 ; result[r] = format("# Automatically generated by mtx-interface (%s)\n\n", os.date())
+ local n = 5 -- number of keywords per row
+ for name, list in sortedhash(data) do
+ local i = 1
+ while i <= #list do
+ r = r + 1 ; result[r] = format("syn keyword %s%s", class, (gsub(name,"^%l",upper))) -- upper is fragile
+ local j = 0
+-- while i+j <= #list and j < n do
+-- if list[i+j] == "transparent" then -- this is a Vim keyword
+-- r = r + 1 ; result[r] = format(" %s[]",list[i+j])
+-- else
+-- r = r + 1 ; result[r] = format(" %s",list[i+j])
+-- end
+-- j = j + 1
+-- end
+ while j < n do
+ local lij = list[i + j]
+ if not lij then
+ break
+ elseif lij == "transparent" then -- this is a Vim keyword
+ r = r + 1 ; result[r] = format(" %s[]",lij)
+ else
+ r = r + 1 ; result[r] = format(" %s",lij)
+ end
+ j = j + 1
+ end
+ r = r + 1 ; result[r] = endline
+ i = i + n
+ end
+ end
+ io.savedata(file.addsuffix(filename,"vim"),concat(result))
+ else
+ os.remove(filename)
+ end
+end
+
+function flushers.vim(collected)
+ local data = { }
+ -- for interface, whatever in next, collected do
+ -- data[interface] = whatever.commands
+ -- end
+ local function add(target,origin,field)
+ if origin then
+ local list = origin[field]
+ if list then
+ for i=1,#list do
+ target[list[i]] = true
+ end
+ end
+ end
+ end
+ --
+ for interface, whatever in next, collected do
+ local combined = { }
+ add(combined,whatever,"commands")
+ add(combined,whatever,"environments")
+ if interface == "common" then
+ add(combined,whatever,"textnames")
+ add(combined,whatever,"mathnames")
+ end
+ data[interface] = sortedkeys(combined)
+ end
+ --
+ vimcollect("context-data-interfaces", "context", data)
+ -- vimcollect("context-data-metapost", "metapost", dofile(resolvers.findfile("mult-mps.lua")))
+ vimcollect("context-data-metafun", "metafun", dofile(resolvers.findfile("mult-fun.lua")))
+ vimcollect("context-data-context", "context", dofile(resolvers.findfile("mult-low.lua")))
+ vimcollect("context-data-tex", "tex", dofile(resolvers.findfile("mult-prm.lua")))
+end
+
function flushers.raw(collected)
for interface, whatever in next, collected do
local commands = whatever.commands
@@ -749,7 +832,7 @@ elseif ea("bidi") then
scripts.interface.bidi()
elseif ea("check") then
scripts.interface.check()
-elseif ea("scite") or ea("bbedit") or ea("jedit") or ea("textpad") or ea("text") or ea("raw") then
+elseif ea("scite") or ea("bbedit") or ea("jedit") or ea("textpad") or ea("vim") or ea("text") or ea("raw") then
if ea("scite") then
scripts.interface.editor("scite")
end
@@ -762,6 +845,9 @@ elseif ea("scite") or ea("bbedit") or ea("jedit") or ea("textpad") or ea("text")
if ea("textpad") then
scripts.interface.editor("textpad",true, { "en" })
end
+ if ea("vim") then
+ scripts.interface.editor("vim",true, { "en" })
+ end
if ea("text") then
scripts.interface.editor("text")
end
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-patterns.lua b/Master/texmf-dist/scripts/context/lua/mtx-patterns.lua
index 36b60192d28..7f5c1c55629 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-patterns.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-patterns.lua
@@ -93,7 +93,7 @@ scripts.patterns.list = {
-- { "ar", "hyph-ar", "arabic" },
-- { "as", "hyph-as", "assamese" },
{ "bg", "hyph-bg", "bulgarian" },
- -- { "bn", "hyph-bn", "bengali" },
+ { "bn", "hyph-bn", "bengali" },
{ "ca", "hyph-ca", "catalan" },
-- { "??", "hyph-cop", "coptic" },
{ "cs", "hyph-cs", "czech" },
@@ -102,8 +102,8 @@ scripts.patterns.list = {
{ "deo", "hyph-de-1901", "german, old spelling" },
{ "de", "hyph-de-1996", "german, new spelling" },
-- { "??", "hyph-de-ch-1901", "swiss german" },
- -- { "??", "hyph-el-monoton", "greek" },
- -- { "gr", "hyph-el-polyton", "greek" },
+ -- { "??", "hyph-el-polyton", "greek" },
+ { "gr", "hyph-el-monoton", "greek" },
{ "agr", "hyph-grc", "ancient greek", ignored_ancient_greek },
{ "gb", "hyph-en-gb", "british english" },
{ "us", "hyph-en-us", "american english" },
@@ -116,8 +116,8 @@ scripts.patterns.list = {
{ "fr", "hyph-fr", "french", ignored_french },
-- { "??", "hyph-ga", "irish" },
-- { "??", "hyph-gl", "galician" },
- -- { "gu", "hyph-gu", "gujarati" },
- -- { "hi", "hyph-hi", "hindi" },
+ { "gu", "hyph-gu", "gujarati" },
+ { "hi", "hyph-hi", "hindi" },
{ "hr", "hyph-hr", "croatian" },
-- { "??", "hyph-hsb", "upper sorbian" },
{ "hu", "hyph-hu", "hungarian" },
@@ -127,7 +127,7 @@ scripts.patterns.list = {
{ "is", "hyph-is", "icelandic" },
{ "it", "hyph-it", "italian" },
-- { "??", "hyph-kmr", "kurmanji" },
- -- { "kn", "hyph-kn", "kannada" },
+ { "kn", "hyph-kn", "kannada" },
{ "la", "hyph-la", "latin" },
{ "ala", "hyph-la-x-classic", "ancient latin" },
-- { "lo", "hyph-lo", "lao" },
@@ -147,15 +147,16 @@ scripts.patterns.list = {
{ "pt", "hyph-pt", "portuguese" },
{ "ro", "hyph-ro", "romanian" },
{ "ru", "hyph-ru", "russian" },
- -- { "sa", "hyph-sa", "sanskrit" },
+ { "sa", "hyph-sa", "sanskrit" },
{ "sk", "hyph-sk", "slovak" },
{ "sl", "hyph-sl", "slovenian" },
- { "sr", "hyph-sr", "serbian", false, { "hyph-sr-cyrl", "hyph-sr-latn" }, },
+ { "sq", "hyph-sq", "albanian" },
+ { "sr", "hyph-sr", "serbian", false, { "hyph-sh-cyrl", "hyph-sh-latn" }, },
-- { "sr", "hyph-sr-cyrl", "serbian", false },
-- { "sr", "hyph-sr-latn", "serbian" },
{ "sv", "hyph-sv", "swedish" },
- -- { "ta", "hyph-ta", "tamil" },
- -- { "te", "hyph-te", "telugu" },
+ { "ta", "hyph-ta", "tamil" },
+ { "te", "hyph-te", "telugu" },
{ "th", "hyph-th", "thai" },
{ "tk", "hyph-tk", "turkmen" },
{ "tr", "hyph-tr", "turkish" },
@@ -186,6 +187,7 @@ function scripts.patterns.load(path,name,mnemonic,ignored, merged)
local splitpatternsold, splithyphenationsold = { }, { }
local usedpatterncharactersnew, usedhyphenationcharactersnew = { }, { }
if merged then
+ -- no version info
report("using merged txt files %s.[hyp|pat|lic].txt",name)
for i=1,#merged do
local fullname = file.join(path,merged[i])
@@ -194,11 +196,13 @@ function scripts.patterns.load(path,name,mnemonic,ignored, merged)
hyphenations = hyphenations .. (io.loaddata(addsuffix(fullname,"hyp.txt")) or "") .. "\n\n"
end
elseif lfs.isfile(patfile) then
+ -- no version info
report("using txt files %s.[hyp|pat|lic].txt",name)
comment = io.loaddata(licfile) or ""
patterns = io.loaddata(patfile) or ""
hyphenations = io.loaddata(hypfile) or ""
elseif lfs.isfile(texfile) then
+ -- version info in comment blob
report("using tex file %s.txt",name)
local data = io.loaddata(texfile) or ""
if data ~= "" then
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-pdf.lua b/Master/texmf-dist/scripts/context/lua/mtx-pdf.lua
index fbb1a3995e5..0ce17ec5b56 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-pdf.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-pdf.lua
@@ -7,7 +7,7 @@ if not modules then modules = { } end modules ['mtx-pdf'] = {
}
local tonumber = tonumber
-local format, gmatch, gsub = string.format, string.gmatch, string.gsub
+local format, gmatch, gsub, match, find = string.format, string.gmatch, string.gsub, string.match, string.find
local utfchar = utf.char
local concat = table.concat
local setmetatableindex, sortedhash, sortedkeys = table.setmetatableindex, table.sortedhash, table.sortedkeys
@@ -27,11 +27,13 @@ local helpinfo = [[
<flag name="metadata"><short>show metadata xml blob</short></flag>
<flag name="pretty"><short>replace newlines in metadata</short></flag>
<flag name="fonts"><short>show used fonts (<ref name="detail)"/></short></flag>
+ <flag name="object"><short>show object"/></short></flag>
</subcategory>
<subcategory>
<example><command>mtxrun --script pdf --info foo.pdf</command></example>
<example><command>mtxrun --script pdf --metadata foo.pdf</command></example>
<example><command>mtxrun --script pdf --metadata --pretty foo.pdf</command></example>
+ <example><command>mtxrun --script pdf --stream=4 foo.pdf</command></example>
</subcategory>
</category>
</flags>
@@ -46,10 +48,14 @@ local application = logs.application {
local report = application.report
-if pdfe then
- dofile(resolvers.findfile("lpdf-pde.lua","tex"))
-else
+if not pdfe then
dofile(resolvers.findfile("lpdf-epd.lua","tex"))
+elseif CONTEXTLMTXMODE then
+ dofile(resolvers.findfile("util-dim.lua","tex"))
+ dofile(resolvers.findfile("lpdf-ini.lmt","tex"))
+ dofile(resolvers.findfile("lpdf-pde.lmt","tex"))
+else
+ dofile(resolvers.findfile("lpdf-pde.lua","tex"))
end
scripts = scripts or { }
@@ -271,6 +277,7 @@ function scripts.pdf.fonts(filename)
chars[i] = c
freqs[i] = format("U+%05X %s %s",k,counts[k] > 1 and "+" or " ", c)
else
+ chars[i] = k == 32 and "SPACE" or format("U+%03X",k)
freqs[i] = format("U+%05X %s --",k,counts[k] > 1 and "+" or " ")
end
end
@@ -349,6 +356,15 @@ function scripts.pdf.fonts(filename)
end
end
+function scripts.pdf.object(filename,n)
+ if n then
+ local pdffile = loadpdffile(filename)
+ if pdffile then
+ print(lpdf.epdf.verboseobject(pdffile,n) or "no object with number " .. n)
+ end
+ end
+end
+
-- scripts.pdf.info("e:/tmp/oeps.pdf")
-- scripts.pdf.metadata("e:/tmp/oeps.pdf")
-- scripts.pdf.fonts("e:/tmp/oeps.pdf")
@@ -364,6 +380,8 @@ elseif environment.argument("metadata") then
scripts.pdf.metadata(filename,environment.argument("pretty"))
elseif environment.argument("fonts") then
scripts.pdf.fonts(filename)
+elseif environment.argument("object") then
+ scripts.pdf.object(filename,tonumber(environment.argument("object")))
elseif environment.argument("exporthelp") then
application.export(environment.argument("exporthelp"),filename)
else
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-spell.lua b/Master/texmf-dist/scripts/context/lua/mtx-spell.lua
new file mode 100644
index 00000000000..dcfc9feb100
--- /dev/null
+++ b/Master/texmf-dist/scripts/context/lua/mtx-spell.lua
@@ -0,0 +1,346 @@
+if not modules then modules = { } end modules ['mtx-patterns'] = {
+ version = 1.001,
+ comment = "companion to mtxrun.lua",
+ author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
+ copyright = "PRAGMA ADE / ConTeXt Development Team",
+ license = "see context related readme files"
+}
+
+local find, gsub, match = string.find, string.gsub, string.match
+local concat = table.concat
+local P, R, S, C, Ct, Cmt, Cc, Cs = lpeg.P, lpeg.R, lpeg.S, lpeg.C, lpeg.Ct, lpeg.Cmt, lpeg.Cc, lpeg.Cs
+local patterns = lpeg.patterns
+local lpegmatch = lpeg.match
+
+local helpinfo = [[
+<?xml version="1.0"?>
+<application>
+ <metadata>
+ <entry name="name">mtx-spell</entry>
+ <entry name="detail">ConTeXt Word Filtering</entry>
+ <entry name="version">0.10</entry>
+ </metadata>
+ <flags>
+ <category name="basic">
+ <subcategory>
+ <flag name="expand"><short>expand hunspell dics and aff files</short></flag>
+ <flag name="dictionary"><short>word file (.dics)</short></flag>
+ <flag name="specification"><short>affix specification file (.aff)</short></flag>
+ <flag name="result"><short>destination file</short></flag>
+ </subcategory>
+ </category>
+ </flags>
+ <examples>
+ <category>
+ <title>Examples</title>
+ <subcategory>
+ <example><command>mtxrun --script spell --expand --dictionary="en_US.dic" --specification="en_US.txt" --result="data-us.txt"</command></example>
+ </subcategory>
+ </category>
+ </examples>
+</application>
+]]
+
+
+local application = logs.application {
+ name = "mtx-spell",
+ banner = "ConTeXt Word Filtering 0.10",
+ helpinfo = helpinfo,
+}
+
+local report = application.report
+local trace = false
+
+scripts = scripts or { }
+scripts.spell = scripts.spell or { }
+
+---------------
+
+require("char-def")
+require("char-utf")
+
+-- nl: ij => ij
+
+do
+
+ local prefixes, suffixes, affixes, continue, collected
+
+ local function resetall()
+ prefixes = table.setmetatableindex("table")
+ suffixes = table.setmetatableindex("table")
+ affixes = table.setmetatableindex("table")
+ continue = { }
+ collected = { }
+ end
+
+ local uppers = { }
+ local chardata = characters.data
+ for k, v in next, chardata do
+ if v.category == "lu" then
+ uppers[utf.char(k)] = true
+ end
+ end
+
+ local newline = patterns.newline
+ local digit = patterns.digit
+ local skipped = digit + lpeg.utfchartabletopattern(uppers)
+ local ignored = 1 - newline
+ local garbage = S("'-")
+
+ local function fixeddata(data)
+ data = gsub(data,"ij","ij")
+ return data
+ end
+
+ local function registersuffix(tag,f)
+ table.insert(suffixes[tag],f)
+ table.insert(affixes [tag],f)
+ end
+
+ local function registerprefix(tag,f)
+ table.insert(prefixes[tag],f)
+ table.insert(affixes [tag],f)
+ end
+
+ local function getfixes(specification)
+
+ local data = fixeddata(io.loaddata(specification) or "")
+ local lines = string.splitlines(data)
+
+ -- /* in two
+ -- Y/N continuation
+
+ -- [^...] [...] ...
+
+ local p0 = nil
+
+ local p1 = P("[^") * Cs((1-P("]"))^1) * P("]") / function(s)
+ local t = utf.split(s)
+ local p = 1 - lpeg.utfchartabletopattern(t)
+ p0 = p0 and (p0 * p) or p
+ end
+ local p2 = P("[") * Cs((1-P("]"))^1) * P("]") / function(s)
+ local t = utf.split(s)
+ local p = lpeg.utfchartabletopattern(t)
+ p0 = p0 and (p0 * p) or p
+ end
+ local p3 = (patterns.utf8char - S("[]"))^1 / function(s)
+ local p = P(s)
+ p0 = p0 and (p0 * p) or p
+ end
+
+ local p = (p1 + p2 + p3)^1
+
+ local function makepattern(s)
+ p0 = nil
+ lpegmatch(p,s)
+ return p0
+ end
+
+ local i = 1
+ while i <= #lines do
+ local line = lines[i]
+ local tag, continuation, n = match(line,"PFX%s+(%S+)%s+(%S+)%s+(%d+)")
+ if tag then
+ n = tonumber(n) or 0
+ continue[tag] = continuation == "Y"
+ for j=1,n do
+ i = i + 1
+ line = lines[i]
+ if not find(line,"[-']") then
+ local tag, one, two, three = match(line,"PFX%s+(%S+)%s+(%S+)%s+([^%s/]+)%S*%s+(%S+)")
+ if tag then
+ if one == "0" and two and three == "." then
+ -- simple case: PFX A 0 re .
+ registerprefix(tag,function(str)
+ local new = two .. str
+ if trace then
+ print("p 1",str,new)
+ end
+ return new
+ end)
+ elseif one == "0" and two and three then
+ -- strip begin
+ if trace then
+ print('2',line)
+ end
+ elseif one and two and three then
+ if trace then
+ print('3',line)
+ end
+ else
+ if trace then
+ print('4',line)
+ end
+ end
+ end
+ end
+ end
+ end
+ local tag, continuation, n = match(line,"SFX%s+(%S+)%s+(%S+)%s+(%S+)")
+ if tag then
+ n = tonumber(n) or 0
+ continue[tag] = continuation == "Y"
+ for j=1,n do
+ i = i + 1
+ line = lines[i]
+ if not find(line,"[-']") then
+ local tag, one, two, three = match(line,"SFX%s+(%S+)%s+(%S+)%s+([^%s/]+)%S*%s+(%S+)")
+ if tag then
+ if one == "0" and two and three == "." then
+ -- SFX Y 0 ly .
+ registersuffix(tag,function(str)
+ local new = str .. two
+ if trace then
+ print("s 1",str,new)
+ end
+ return new
+ end)
+ elseif one == "0" and two and three then
+ -- SFX G 0 ing [^e]
+ local final = makepattern(three) * P(-1)
+ local check = (1 - final)^0 * final
+ registersuffix(tag,function(str)
+ if lpegmatch(check,str) then
+ local new = str .. two
+ if trace then
+ print("s 2",str,new)
+ end
+ return new
+ end
+ end)
+ elseif one and two and three then
+ -- SFX G match$ suffix old$ (dutch has sloppy matches, use english as reference)
+ local final = makepattern(three) * P(-1)
+ local check = (1 - final)^1 * final
+ local final = makepattern(one) * P(-1)
+ local replace = Cs((1 - final)^1 * (final/two))
+ registersuffix(tag,function(str)
+ if lpegmatch(check,str) then
+ local new = lpegmatch(replace,str)
+ if new then
+ if trace then
+ print("s 3",str,new)
+ end
+ return new
+ end
+ end
+ end)
+ else
+ if trace then
+ print('4',line)
+ end
+ end
+ end
+ end
+ end
+ end
+ i = i + 1
+ end
+ end
+
+ local function expand(_,_,word,spec)
+ if spec then
+ local w = { word }
+ local n = 1
+ for i=1,#spec do
+ local s = spec[i]
+ local affix = affixes[s]
+ if affix then
+ for i=1,#affix do
+ local ai = affix[i]
+ local wi = ai(word)
+ if wi then
+ n = n + 1
+ w[n] = wi
+ if not continue[s] then
+ break
+ end
+ end
+ end
+ end
+ end
+ for i=1,n do
+ collected[w[i]] = true
+ end
+ elseif not find(word,"/") then
+ collected[word] = true
+ end
+ return true
+ end
+
+ local function getwords(dictionary)
+ local data = fixeddata(io.loaddata(dictionary) or "")
+ local keys = { }
+ for k, v in next, prefixes do
+ keys[k] = true
+ end
+ for k, v in next, suffixes do
+ keys[k] = true
+ end
+ local validkeys = lpeg.utfchartabletopattern(keys)
+ local specifier = P("/") * Ct(C(validkeys)^1)^0 * newline
+ local pattern = (
+ newline^1
+ + skipped * (1-newline)^0
+ + Cmt(C((1-specifier-newline-garbage)^1) * specifier^0, expand)
+ + ignored^1 * newline^1
+ )^0
+ lpegmatch(pattern,data)
+ collected = table.keys(collected)
+ table.sort(collected)
+ return collected
+ end
+
+ local function saveall(result)
+ if result then
+ io.savedata(result,concat(collected,"\n"))
+ end
+ end
+
+ function scripts.spell.expand(arguments)
+ if arguments then
+ local dictionary = environment.arguments.dictionary
+ local specification = environment.arguments.specification
+ local result = environment.arguments.result
+ if type(dictionary) ~= "string" or dictionary == "" then
+ report("missing --dictionary=name")
+ elseif type(specification) ~= "string" or specification == "" then
+ report("missing --specification=name")
+ elseif type(result) ~= "string" or result == "" then
+ resetall()
+ getfixes(specification)
+ getwords(dictionary)
+ saveall(result)
+ return collected
+ end
+ end
+ end
+
+end
+
+-- spell.dicaff {
+-- dictionary = "e:/context/spell/lo/en_US.dic.txt",
+-- specification = "e:/context/spell/lo/en_US.aff.txt",
+-- result = "e:/context/spell/lo/data-en.txt",
+-- }
+
+-- spell.dicaff {
+-- dictionary = "e:/context/spell/lo/en_GB.dic.txt",
+-- specification = "e:/context/spell/lo/en_GB.aff.txt",
+-- result = "e:/context/spell/lo/data-uk.txt",
+-- }
+
+-- spell.dicaff {
+-- dictionary = "e:/context/spell/lo/nl_NL.dic.txt",
+-- specification = "e:/context/spell/lo/nl_NL.aff.txt",
+-- result = "e:/context/spell/lo/data-nl.txt",
+-- }
+
+if environment.argument("expand") then
+ scripts.spell.expand(environment.arguments)
+elseif environment.argument("exporthelp") then
+ application.export(environment.argument("exporthelp"),environment.files[1])
+else
+ application.help()
+end
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-synctex.lua b/Master/texmf-dist/scripts/context/lua/mtx-synctex.lua
index 3c4f6ee7184..f94a9605f3b 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-synctex.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-synctex.lua
@@ -10,8 +10,9 @@ if not modules then modules = { } end modules ['mtx-synctex'] = {
-- InverseSearchCmdLine = mtxrun.exe --script synctex --edit --name="%f" --line="%l" $
local tonumber = tonumber
-local find, match, gsub = string.find, string.match, string.gsub
+local find, match, gsub, formatters = string.find, string.match, string.gsub, string.formatters
local isfile = lfs.isfile
+local max = math.max
local longtostring = string.longtostring
local helpinfo = [[
@@ -20,15 +21,16 @@ local helpinfo = [[
<metadata>
<entry name="name">mtx-synctex</entry>
<entry name="detail">SyncTeX Checker</entry>
- <entry name="version">1.00</entry>
+ <entry name="version">1.01</entry>
</metadata>
<flags>
<category name="basic">
<subcategory>
<flag name="edit"><short>open file at line: --line=.. --editor=.. sourcefile</short></flag>
- <flag name="list"><short>show blob: synctexfile</short></flag>
- <flag name="goto"><short>open file at position: --page=.. --x=.. --y=.. --editor=.. synctexfile</short></flag>
- <flag name="report"><short>show file and line: --page=.. --x=.. --y=.. --console synctexfile</short></flag>
+ <flag name="list"><short>show all areas: synctexfile</short></flag>
+ <flag name="goto"><short>open file at position: --page=.. --x=.. --y=.. [--tolerance=] --editor=.. synctexfile</short></flag>
+ <flag name="report"><short>show (tex) file and line: [--direct] --page=.. --x=.. --y=.. [--tolerance=] --console synctexfile</short></flag>
+ <flag name="find"><short>find (pdf) page and box: [--direct] --file=.. --line=.. synctexfile</short></flag>
</subcategory>
</category>
</flags>
@@ -37,15 +39,22 @@ local helpinfo = [[
local application = logs.application {
name = "mtx-synctex",
- banner = "ConTeXt SyncTeX Checker 1.00",
+ banner = "ConTeXt SyncTeX Checker 1.01",
helpinfo = helpinfo,
}
local report = application.report
+local template_show = "page=%i llx=%r lly=%r urx=%r ury=%r"
+local template_goto = "filename=%a linenumber=%a tolerance=%a"
+
+local function reportdirect(template,...)
+ print(formatters[template](...))
+end
+
local editors = {
console = function(specification)
- print(string.formatters["%q %i"](specification.filename,specification.linenumber or 1))
+ print(string.formatters["%q %i %i"](specification.filename,specification.linenumber or 1,specification.tolerance))
end,
scite = sandbox.registerrunner {
name = "scite",
@@ -69,7 +78,7 @@ local function validfile(filename)
end
end
-local function editfile(filename,line,editor)
+local function editfile(filename,line,tolerance,editor)
if not validfile(filename) then
return
end
@@ -77,6 +86,7 @@ local function editfile(filename,line,editor)
runner {
filename = filename,
linenumber = tonumber(line) or 1,
+ tolerance = tolerance,
}
end
@@ -184,18 +194,142 @@ local function findlocation(filename,page,xpos,ypos)
end
end
-local function showlocation(filename)
+local function findlocation(filename,page,xpos,ypos,tolerance)
+ if not validfile(filename) then
+ return
+ elseif not page then
+ page = 1
+ elseif not xpos or not ypos then
+ report("provide x and y coordinates (unit: basepoints)")
+ return
+ end
+ local files = { }
+ local found = false
+ local skip = false
+ local fi = 0
+ local ln = 0
+ local tl = 0
+ local lines = { }
+ for line in io.lines(filename) do
+ if found then
+ if find(line,"^}") then
+ local function locate(x,y)
+ local dx = false
+ local dy = false
+ local px = (xpos + x) / factor
+ local py = (ypos + y) / factor
+ for i=1,#lines do
+ local line = lines[i]
+ -- we only look at positive cases
+ local f, l, x, y, w, h, d = match(line,"^h(.-),(.-):(.-),(.-):(.-),(.-),(.-)$")
+ if f and f ~= 0 then
+-- print(x,y,f)
+ x = tonumber(x)
+ if px >= x then
+ w = tonumber(w)
+ if px <= x + w then
+ y = tonumber(y)
+ d = tonumber(d)
+ if py >= y - d then
+ h = tonumber(h)
+ if py <= y + h then
+ if quit then
+ -- we have no overlapping boxes
+ fi = f
+ ln = l
+ return
+ else
+ local lx = px - x
+ local rx = x + w - px
+ local by = py - y + d
+ local ty = y + h - py
+ mx = lx < rx and lx or rx
+ my = by < ty and by or ty
+ if not dx then
+ dx = mx
+ dy = my
+ fi = f
+ ln = l
+ else
+ if mx < dx then
+ dx = mx
+ di = f
+ ln = l
+ end
+ if my < dy then
+ dy = my
+ fi = f
+ ln = l
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ locate(0,0)
+ if fi ~= 0 then
+ return files[fi], ln, 0
+ end
+ if not tolerance then
+ tolerance = 10
+ end
+ for s=1,tolerance,max(tolerance//10,1) do
+ locate( s, 0) if fi ~= 0 then tl = s ; goto done end
+ locate(-s, 0) if fi ~= 0 then tl = s ; goto done end
+ locate( s, s) if fi ~= 0 then tl = s ; goto done end
+ locate( s,-s) if fi ~= 0 then tl = s ; goto done end
+ locate(-s, s) if fi ~= 0 then tl = s ; goto done end
+ locate(-s,-s) if fi ~= 0 then tl = s ; goto done end
+ end
+ break
+ else
+ lines[#lines+1] = line
+ end
+ elseif skip then
+ if find(line,"^}") then
+ skip = false
+ end
+ elseif find(line,"^{(%d+)") then
+ local p = tonumber(match(line,"^{(%d+)"))
+ if p == page then
+ found = true
+ else
+ skip = true
+ end
+ elseif find(line,"^Input:") then
+ local id, name = match(line,"^Input:(.-):(.-)$")
+ if id then
+ files[id] = name
+ end
+ end
+ end
+ ::done::
+ if fi ~= 0 then
+ return files[fi], ln, tl
+ end
+end
+
+local function showlocation(filename,sourcename,linenumber,direct)
if not validfile(filename) then
return
end
local files = { }
local found = false
local page = 0
+ if sourcename then
+ sourcename = file.collapsepath(sourcename)
+ end
for line in io.lines(filename) do
if found then
if find(line,"^}") then
found = false
- report("end page: %i",page)
+ if not sourcename then
+ report("end page: %i",page)
+ end
else
local f, l, x, y, w, h, d = match(line,"^h(.-),(.-):(.-),(.-):(.-),(.-),(.-)$")
if f then
@@ -206,15 +340,22 @@ local function showlocation(filename)
local urx = factor * ( x + tonumber(w) )
local ury = factor * ( y + tonumber(h) )
f = files[f]
- if f then
+ if not f then
+ --
+ elseif not sourcename then
report(" [% 4r % 4r % 4r % 4r] : % 5i : %s",llx,lly,urx,ury,l,f)
+ elseif f == sourcename and l == linenumber then
+ (direct and reportdirect or report)(template_show,page,llx,lly,urx,ury)
+ return
end
end
end
elseif find(line,"^{(%d+)") then
page = tonumber(match(line,"^{(%d+)"))
found = true
- report("begin page: %i",page)
+ if not sourcename then
+ report("begin page: %i",page)
+ end
elseif find(line,"^Input:") then
local id, name = match(line,"^Input:(.-):(.-)$")
if id then
@@ -224,14 +365,14 @@ local function showlocation(filename)
end
end
-local function gotolocation(filename,page,xpos,ypos,editor)
+local function gotolocation(filename,page,xpos,ypos,editor,direct,tolerance)
if filename then
- local target, line = findlocation(filename,tonumber(page),tonumber(xpos),tonumber(ypos))
+ local target, line, t = findlocation(filename,tonumber(page),tonumber(xpos),tonumber(ypos),tonumber(tolerance))
if target and line then
if editor then
- editfile(target,line,editor)
+ editfile(target,line,t,editor)
else
- report("filename=%a linenumber=%a",target,line)
+ (direct and reportdirect or report)(template_goto,target,line,t)
end
end
end
@@ -248,11 +389,13 @@ local filename = environment.files[1]
if argument("edit") then
editfile(filename,argument("line"),argument("editor"))
elseif argument("goto") then
- gotolocation(filename,argument("page"),argument("x"),argument("y"),argument("editor"))
+ gotolocation(filename,argument("page"),argument("x"),argument("y"),argument("editor"),argument("direct"),argument("tolerance"))
elseif argument("report") then
- gotolocation(filename,argument("page"),argument("x"),argument("y"),"console")
+ gotolocation(filename,argument("page"),argument("x"),argument("y"),"console",argument("direct"),argument("tolerance"))
elseif argument("list") then
showlocation(filename)
+elseif argument("find") then
+ showlocation(filename,argument("file"),argument("line"),argument("direct"))
elseif argument("exporthelp") then
application.export(argument("exporthelp"),filename)
else
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-unicode.lua b/Master/texmf-dist/scripts/context/lua/mtx-unicode.lua
index 060e563c642..ad42797b70d 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-unicode.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-unicode.lua
@@ -143,6 +143,7 @@ function scripts.unicode.update()
local eastasianwidth = texttables.eastasianwidth
local standardizedvariants = texttables.standardizedvariants
local arabicshaping = texttables.arabicshaping
+ local casefolding = texttables.casefolding
local index = texttables.index
local characterdata = characters.data
--
@@ -164,6 +165,8 @@ function scripts.unicode.update()
local cjkwd = ed and lower(ed[2] or "n")
local mirror = bd and tonumber(bd[2],16)
local arabic = nil
+ local lccode = false
+ local uccode = false
descriptions[description] = unicode
if sparse and direction == "l" then
direction = nil
@@ -203,6 +206,40 @@ function scripts.unicode.update()
if not combining or combining == 0 then
combining = nil
end
+ --
+ local cf = casefolding[unicode]
+ if cf and tonumber(cf[1],16) == unicode then
+ local how = cf[2]
+ if how == "C" or how == "S" then
+ local fold = tonumber(cf[3],16)
+ if fold == unicode then
+ -- print("SKIPPING",description)
+ elseif category == "ll" then
+ uccode = fold
+ elseif category == "lu" then
+ lccode = fold
+ end
+ elseif how == "F" then
+ -- we can use the first
+ local folding = { }
+ for s in gmatch(cf[3],"%S+") do
+ folding[#folding+1] = tonumber(s,16)
+ end
+ if category == "ll" then
+ uccode = folding
+ elseif category == "ul" then
+ lccode = folding
+ end
+ else
+ -- we skip these
+ -- print(description)
+ -- inspect(cf)
+ end
+ end
+ --
+-- if specials and specials[1] == "font" then
+-- specials = nil
+-- end
if not char then
report("%U : adding entry %a",unicode,description)
char = {
@@ -218,9 +255,34 @@ function scripts.unicode.update()
specials = specials,
arabic = arabic,
combining = combining,
+ uccode = uccode and uccode or nil,
+ lccode = lccode and lccode or nil,
}
characterdata[unicode] = char
else
+ -- we have more case mapping (e.g. cherokee)
+ if lccode then
+ if type(lccode) == "table" then
+ if type(char.lccode) ~= "table" or not are_equal(lccode,char.lccode) then
+ report("%U : setting lccode to % t, %a",unicode,lccode,description)
+ char.lccode = lccode
+ end
+ elseif char.lccode ~= lccode then
+ report("%U : setting lccode to %a, %a, %a",unicode,lccode,description)
+ char.lccode = lccode
+ end
+ end
+ if uccode then
+ if type(uccode) == "table" then
+ if type(char.uccode) ~= "table" or not are_equal(uccode,char.uccode) then
+ report("%U : setting uccode to % t, %a",unicode,uccode,description)
+ char.uccode = uccode
+ end
+ elseif char.uccode ~= uccode then
+ report("%U : setting uccode to %a, %a",unicode,uccode,description)
+ char.uccode = uccode
+ end
+ end
if direction then
if char.direction ~= direction then
report("%U : setting direction to %a, %a",unicode,direction,description)
@@ -295,6 +357,7 @@ function scripts.unicode.update()
else
local specials = char.specials
if specials then
+-- if specials and specials[1] ~= "font" then
local t = { } for i=2,#specials do t[i] = formatters["%U"](specials[i]) end
if false then
char.comment = nil
@@ -306,7 +369,7 @@ function scripts.unicode.update()
elseif not find(comment,"check special") then
char.comment = comment .. ", check special"
end
- report("%U : check specials % + t, %a",unicode,t,description)
+ -- report("%U : check specials % + t, %a",unicode,t,description)
end
end
end
@@ -397,7 +460,7 @@ function scripts.unicode.update()
mark = descriptions["SOLIDUS"] -- SLASH
end
if base and mark then
- report("adding extra char special for %a",description)
+ -- report("adding extra char special for %a",description)
data.specials = { "with", base, mark }
data.comment = nil
end
@@ -414,7 +477,7 @@ function scripts.unicode.update()
if first then
local d = characterdata[first]
if d then
- local v = d.variants
+ -- local v = d.variants
local v = rawget(d,"variants")
if not v then
v = { }
@@ -429,7 +492,7 @@ function scripts.unicode.update()
end
for unicode, ud in table.sortedpairs(characterdata) do
if not rawget(ud,"category") and rawget(ud,"variants") then
- report("stripping %U (variant, takes from metacharacter)",unicode)
+ -- report("stripping %U (variant, takes from metacharacter)",unicode)
characterdata[unicode] = nil
end
end
@@ -437,7 +500,7 @@ end
local preamble
-local function splitdefinition(str,index)
+local function splitdefinition(filename,str,index)
local l = splitlines(str)
local t = { }
if index then
@@ -459,7 +522,7 @@ local function splitdefinition(str,index)
t[k] = d
end
else
- report("problem: %s",s)
+ report("problem: %i %s => %s",i,filename,s)
end
end
end
@@ -521,6 +584,7 @@ function scripts.unicode.load()
eastasianwidth = resolvers.findfile("eastasianwidth.txt") or "",
standardizedvariants = resolvers.findfile("standardizedvariants.txt") or "",
arabicshaping = resolvers.findfile("arabicshaping.txt") or "",
+ casefolding = resolvers.findfile("casefolding.txt") or "",
index = resolvers.findfile("index.txt") or "",
}
--
@@ -531,15 +595,17 @@ function scripts.unicode.load()
eastasianwidth = textfiles.eastasianwidth ~= "" and io.loaddata(textfiles.eastasianwidth) or "",
standardizedvariants = textfiles.standardizedvariants ~= "" and io.loaddata(textfiles.standardizedvariants) or "",
arabicshaping = textfiles.arabicshaping ~= "" and io.loaddata(textfiles.arabicshaping) or "",
+ casefolding = textfiles.casefolding ~= "" and io.loaddata(textfiles.casefolding) or "",
index = textfiles.index ~= "" and io.loaddata(textfiles.index) or "",
}
texttables = {
- unicodedata = splitdefinition(textdata.unicodedata,true),
- bidimirroring = splitdefinition(textdata.bidimirroring,true),
- linebreak = splitdefinition(textdata.linebreak,true),
- eastasianwidth = splitdefinition(textdata.eastasianwidth,true),
- standardizedvariants = splitdefinition(textdata.standardizedvariants,false),
- arabicshaping = splitdefinition(textdata.arabicshaping,true),
+ unicodedata = splitdefinition(textfiles.unicodedata,textdata.unicodedata,true),
+ bidimirroring = splitdefinition(textfiles.bidimirroring,textdata.bidimirroring,true),
+ linebreak = splitdefinition(textfiles.linebreak,textdata.linebreak,true),
+ eastasianwidth = splitdefinition(textfiles.eastasianwidth,textdata.eastasianwidth,true),
+ standardizedvariants = splitdefinition(textfiles.standardizedvariants,textdata.standardizedvariants,false),
+ arabicshaping = splitdefinition(textfiles.arabicshaping,textdata.arabicshaping,true),
+ casefolding = splitdefinition(textfiles.casefolding,textdata.casefolding,true),
index = splitindex(textdata.index),
}
--
@@ -563,11 +629,88 @@ end
-- [0xFE01]="centered form",
-- }
+-- local variants_style={
+-- [0xFE00]="chancery style",
+-- [0xFE01]="roundhand style",
+-- }
+
+-- local variants_90={
+-- [0xFE00]="rotated 90 degrees",
+-- }
+--
+-- local variants_180={
+-- [0xFE01]="rotated 180 degrees",
+-- }
+--
+-- local variants_270={
+-- [0xFE02]="rotated 270 degrees",
+-- }
+--
+-- local variants_expanded={
+-- [0xFE00]="expanded",
+-- }
+--
+-- local variants_90_180={
+-- [0xFE00]="rotated 90 degrees",
+-- [0xFE01]="rotated 180 degrees",
+-- }
+--
+-- local variants_90_180_270={
+-- [0xFE00]="rotated 90 degrees",
+-- [0xFE01]="rotated 180 degrees",
+-- [0xFE02]="rotated 270 degrees",
+-- }
+--
+-- local variants_180_270={
+-- [0xFE01]="rotated 180 degrees",
+-- [0xFE02]="rotated 270 degrees",
+-- }
+--
+-- local variants_90_270={
+-- [0xFE00]="rotated 90 degrees",
+-- [0xFE02]="rotated 270 degrees",
+-- }
+
function scripts.unicode.save(filename)
if preamble then
local data = table.serialize(characters.data,"characters.data", { hexify = true, noquotes = true })
- data = gsub(data,"%{%s+%[0xFE0E%]=\"text style\",%s+%[0xFE0F%]=\"emoji style\",%s+%}","variants_emoji")
- data = gsub(data,"%{%s+%[0xFE00%]=\"corner%-justified form\",%s+%[0xFE01%]=\"centered form\",%s+%}","variants_forms")
+ data = gsub(data,
+ "%{%s+%[0xFE0E%]=\"text style\",%s+%[0xFE0F%]=\"emoji style\",%s+%}",
+ "variants_emoji"
+ )
+ data = gsub(data,
+ "%{%s+%[0xFE00%]=\"corner%-justified form\",%s+%[0xFE01%]=\"centered form\",%s+%}",
+ "variants_forms"
+ )
+ data = gsub(data,
+ "%{%s+%[0xFE00%]=\"chancery style\",%s+%[0xFE01%]=\"roundhand style\",%s+%}",
+ "variants_style"
+ )
+ data = gsub(data,
+ "%{%s+%[0xFE00%]=\"dotted form\",%s+%}",
+ "variants_dotted"
+ )
+ data = gsub(data,
+ "%{%s+%[0xFE00%]=\"expanded\",%s+%}",
+ "variants_expanded"
+ )
+ data = gsub(data,
+ "%{%s+%[0xFE0%d%]=\"rotated (%d+) degrees\",%s+%}",
+ "variants_%1"
+ )
+ data = gsub(data,
+ "%{%s+%[0xFE0%d%]=\"rotated (%d+) degrees\"," ..
+ "%s*%[0xFE0%d%]=\"rotated (%d+) degrees\"," ..
+ "%s+%}",
+ "variants_%1_%2"
+ )
+ data = gsub(data,
+ "%{%s+%[0xFE0%d%]=\"rotated (%d+) degrees\"," ..
+ "%s*%[0xFE0%d%]=\"rotated (%d+) degrees\"," ..
+ "%s*%[0xFE0%d%]=\"rotated (%d+) degrees\"," ..
+ "%s+%}",
+ "variants_%1_%2_%3"
+ )
io.savedata(filename,preamble .. data)
end
end
@@ -764,7 +907,7 @@ else
scripts.unicode.save("char-def-new.lua")
scripts.unicode.emoji("char-emj-new.lua")
report("saved file %a","char-def-new.lua")
- report("saved file %a (current 12.0, check for updates, see above!)","char-emj-new.lua")
+ report("saved file %a (current 14.0, check for updates, see above!)","char-emj-new.lua")
else
report("nothing to do")
end
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-update.lua b/Master/texmf-dist/scripts/context/lua/mtx-update.lua
index b0ed9aac7e2..daf23eb0911 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-update.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-update.lua
@@ -157,66 +157,6 @@ update.goodies = {
},
}
--- update.platforms = {
--- ["mswin"] = "mswin",
--- ["windows"] = "mswin",
--- ["win32"] = "mswin",
--- ["win"] = "mswin",
--- -- ["mswin"] = "win32",
--- -- ["windows"] = "win32",
--- -- ["win32"] = "win32",
--- -- ["win"] = "win32",
--- --
--- -- ["mswin-64"] = "mswin-64",
--- -- ["windows-64"] = "mswin-64",
--- -- ["win64"] = "mswin-64",
--- ["mswin-64"] = "win64",
--- ["windows-64"] = "win64",
--- ["win64"] = "win64",
--- --
--- ["linux"] = "linux",
--- ["linux-32"] = "linux",
--- ["linux32"] = "linux",
--- --
--- ["linux-64"] = "linux-64",
--- ["linux64"] = "linux-64",
--- --
--- ["linuxmusl-64"] = "linuxmusl-64",
--- --
--- ["linux-armhf"] = "linux-armhf",
--- --
--- ["freebsd"] = "freebsd",
--- --
--- ["freebsd-amd64"] = "freebsd-amd64",
--- --
--- ["kfreebsd"] = "kfreebsd-i386",
--- ["kfreebsd-i386"] = "kfreebsd-i386",
--- --
--- ["kfreebsd-amd64"] = "kfreebsd-amd64",
--- --
--- ["linux-ppc"] = "linux-ppc",
--- ["ppc"] = "linux-ppc",
--- --
--- ["osx"] = "osx-intel",
--- ["macosx"] = "osx-intel",
--- ["osx-intel"] = "osx-intel",
--- ["osxintel"] = "osx-intel",
--- --
--- ["osx-ppc"] = "osx-ppc",
--- ["osx-powerpc"] = "osx-ppc",
--- ["osxppc"] = "osx-ppc",
--- ["osxpowerpc"] = "osx-ppc",
--- --
--- ["osx-64"] = "osx-64",
--- --
--- ["solaris-intel"] = "solaris-intel",
--- --
--- ["solaris-sparc"] = "solaris-sparc",
--- ["solaris"] = "solaris-sparc",
--- --
--- ["unknown"] = "unknown",
--- }
-
update.platforms = {
["mswin"] = "mswin",
["windows"] = "mswin",
@@ -238,9 +178,9 @@ update.platforms = {
--
["linux-armhf"] = "linux-armhf",
--
- ["openbsd"] = "openbsd6.8",
- ["openbsd-i386"] = "openbsd6.8",
- ["openbsd-amd64"] = "openbsd6.8-amd64",
+ ["openbsd"] = "openbsd7.2",
+ ["openbsd-i386"] = "openbsd7.2",
+ ["openbsd-amd64"] = "openbsd7.2-amd64",
--
["freebsd"] = "freebsd",
["freebsd-i386"] = "freebsd",
@@ -266,7 +206,8 @@ update.platforms = {
["macosx"] = "osx-64",
["osx"] = "osx-64",
["osx-64"] = "osx-64",
- ["osx-arm64"] = "osx-64",
+ ["osx-arm"] = "osx-arm64",
+ ["osx-arm64"] = "osx-arm64",
--
-- ["solaris-intel"] = "solaris-intel",
--
diff --git a/Master/texmf-dist/scripts/context/lua/mtx-vscode.lua b/Master/texmf-dist/scripts/context/lua/mtx-vscode.lua
index 96cc5f9009b..0fd5fd428e4 100644
--- a/Master/texmf-dist/scripts/context/lua/mtx-vscode.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtx-vscode.lua
@@ -62,7 +62,9 @@ if not modules then modules = { } end modules ['mtx-vscode'] = {
-- me (too many different folders with source code, documentation etc). It's kind of
-- strange because simple runners are provided by many editors. I don't want to program
-- a lot to get such simple things done so, awaiting global tasks I stick to using the
--- terminal. But we're prepared.
+-- terminal. Also, having .vscode folderd in every place where a file sits makes no
+-- sense and clutters my disk too much. There is not much progress in this area but we
+-- are prepared.
-- Another showstopper is the fact that we cannot disable utf8 for languages (like pdf,
-- which is just bytes). I couldn't figure out how to set it in the extension.
@@ -138,7 +140,9 @@ local helpinfo = [[
<category name="basic">
<subcategory>
<flag name="generate"><short>generate extension in sync with current version</short></flag>
+ <flag name="program"><short>use the given binary (e.g. codium, default: code)</short></flag>
<flag name="start"><short>start vscode with extension context</short></flag>
+ <flag name="lsfile"><short>generate language server file (work in progress)</short></flag>
</subcategory>
</category>
</flags>
@@ -149,6 +153,7 @@ local helpinfo = [[
<example><command>mtxrun --script vscode --generate e:/vscode/extensions</command></example>
<example><command>mtxrun --script vscode --generate</command></example>
<example><command>mtxrun --script vscode --start</command></example>
+ <example><command>mtxrun --script vscode --program=codium --start</command></example>
</subcategory>
</category>
</examples>
@@ -161,6 +166,8 @@ local application = logs.application {
helpinfo = helpinfo,
}
+local concat = table.concat
+
local report = application.report
require("util-jsn")
@@ -278,6 +285,20 @@ function scripts.vscode.generate(targetpath)
end
+ -- local function registersettings()
+ --
+ -- local filename = "./settings.json"
+ --
+ -- local data = {
+ -- ["editor.bracketPairColorization.enabled"] = false,
+ -- ["editor.bracketPairColorization.independentColorPoolPerBracketType"] = false,
+ -- }
+ --
+ -- report("saving settings %a",filename)
+ --
+ -- io.savedata(filename,data)
+ -- end
+
local function registertheme(theme)
local category = theme.category
@@ -294,6 +315,7 @@ function scripts.vscode.generate(targetpath)
["name"] = category,
["colors"] = theme.colors,
["tokenColors"] = theme.styles,
+ ["settings"] = theme.settings,
}
report("saving theme %a in %a",category,filename)
@@ -353,11 +375,13 @@ function scripts.vscode.generate(targetpath)
displayName = "ConTeXt",
description = "ConTeXt Syntax Highlighting",
publisher = "ConTeXt Development Team",
+ publisher = "cdt",
version = "1.0.0",
engines = {
vscode = "*"
},
categories = {
+ "Programming Languages",
"Lexers",
"Syntaxes"
},
@@ -414,42 +438,69 @@ function scripts.vscode.generate(targetpath)
tippanel = "#444444",
right = "#0000FF",
wrong = "#FF0000",
+ default = "#000000",
+ reverse = "#FFFFFF",
+
+ -- some day a dark:
+
+-- red = "#CC4444",
+-- green = "#44CC44",
+-- blue = "#4444FF",
+-- cyan = "#55BBBB",
+-- magenta = "#BB55BB",
+-- yellow = "#BBBB55",
+-- orange = "#B07F00",
+-- white = "#FFFFFF",
+-- light = "#CFCFCF",
+-- grey = "#808080",
+-- dark = "#4F4F4F",
+-- black = "#000000",
+-- selection = "#F7F7F7",
+-- logpanel = "#E7E7E7",
+-- textpanel = "#1E1E1E", -- VS "#101010",
+-- linepanel = "#A7A7A7",
+-- tippanel = "#444444",
+-- right = "#0000FF",
+-- wrong = "#FF0000",
+-- default = "#D4D4D4",
+-- reverse = "#000000",
+
}
local colors = {
["editor.background"] = mycolors.textpanel,
- ["editor.foreground"] = mycolors.black,
- ["editorLineNumber.foreground"] = mycolors.black,
+ ["editor.foreground"] = mycolors.default,
+ ["editorLineNumber.foreground"] = mycolors.default,
["editorIndentGuide.background"] = mycolors.textpanel,
["editorBracketMatch.background"] = mycolors.textpanel,
["editorBracketMatch.border"] = mycolors.orange,
["editor.lineHighlightBackground"] = mycolors.textpanel,
- ["focusBorder"] = mycolors.black,
+ ["focusBorder"] = mycolors.default,
- ["activityBar.background"] = mycolors.black,
+ ["activityBar.background"] = mycolors.default,
- ["sideBar.background"] = mycolors.linepanel,
- ["sideBar.foreground"] = mycolors.black,
- ["sideBar.border"] = mycolors.white,
- ["sideBarTitle.foreground"] = mycolors.black,
+ ["editorGutter.background"] = mycolors.linepanel,
+ ["editorGutter.foreground"] = mycolors.default,
+ ["editorGutter.border"] = mycolors.reverse,
+ ["sideBarTitle.foreground"] = mycolors.default,
["sideBarSectionHeader.background"] = mycolors.linepanel,
- ["sideBarSectionHeader.foreground"] = mycolors.black,
+ ["sideBarSectionHeader.foreground"] = mycolors.default,
- ["statusBar.foreground"] = mycolors.black,
+ ["statusBar.foreground"] = mycolors.default,
["statusBar.background"] = mycolors.linepanel,
- ["statusBar.border"] = mycolors.white,
- ["statusBar.noFolderForeground"] = mycolors.black,
+ ["statusBar.border"] = mycolors.reverse,
+ ["statusBar.noFolderForeground"] = mycolors.default,
["statusBar.noFolderBackground"] = mycolors.linepanel,
- ["statusBar.debuggingForeground"] = mycolors.black,
+ ["statusBar.debuggingForeground"] = mycolors.default,
["statusBar.debuggingBackground"] = mycolors.linepanel,
- ["notification.background"] = mycolors.black,
+ ["notification.background"] = mycolors.default,
}
local styles = {
{ scope = "context.whitespace", settings = { } },
- { scope = "context.default", settings = { foreground = mycolors.black } },
+ { scope = "context.default", settings = { foreground = mycolors.default } },
{ scope = "context.number", settings = { foreground = mycolors.cyan } },
{ scope = "context.comment", settings = { foreground = mycolors.yellow } },
{ scope = "context.keyword", settings = { foreground = mycolors.blue, fontStyle = "bold" } },
@@ -457,30 +508,30 @@ function scripts.vscode.generate(targetpath)
{ scope = "context.error", settings = { foreground = mycolors.red } },
{ scope = "context.label", settings = { foreground = mycolors.red, fontStyle = "bold" } },
{ scope = "context.nothing", settings = { } },
- { scope = "context.class", settings = { foreground = mycolors.black, fontStyle = "bold" } },
- { scope = "context.function", settings = { foreground = mycolors.black, fontStyle = "bold" } },
+ { scope = "context.class", settings = { foreground = mycolors.default, fontStyle = "bold" } },
+ { scope = "context.function", settings = { foreground = mycolors.default, fontStyle = "bold" } },
{ scope = "context.constant", settings = { foreground = mycolors.cyan, fontStyle = "bold" } },
{ scope = "context.operator", settings = { foreground = mycolors.blue } },
{ scope = "context.regex", settings = { foreground = mycolors.magenta } },
{ scope = "context.preprocessor", settings = { foreground = mycolors.yellow, fontStyle = "bold" } },
{ scope = "context.tag", settings = { foreground = mycolors.cyan } },
{ scope = "context.type", settings = { foreground = mycolors.blue } },
- { scope = "context.variable", settings = { foreground = mycolors.black } },
+ { scope = "context.variable", settings = { foreground = mycolors.default } },
{ scope = "context.identifier", settings = { } },
{ scope = "context.linenumber", settings = { background = mycolors.linepanel } },
{ scope = "context.bracelight", settings = { foreground = mycolors.orange, fontStyle = "bold" } },
{ scope = "context.bracebad", settings = { foreground = mycolors.orange, fontStyle = "bold" } },
{ scope = "context.controlchar", settings = { } },
- { scope = "context.indentguide", settings = { foreground = mycolors.linepanel, back = colors.white } },
- { scope = "context.calltip", settings = { foreground = mycolors.white, back = colors.tippanel } },
+ { scope = "context.indentguide", settings = { foreground = mycolors.linepanel, back = colors.reverse } },
+ { scope = "context.calltip", settings = { foreground = mycolors.reverse, back = colors.tippanel } },
{ scope = "context.invisible", settings = { background = mycolors.orange } },
{ scope = "context.quote", settings = { foreground = mycolors.blue, fontStyle = "bold" } },
{ scope = "context.special", settings = { foreground = mycolors.blue } },
{ scope = "context.extra", settings = { foreground = mycolors.yellow } },
- { scope = "context.embedded", settings = { foreground = mycolors.black, fontStyle = "bold" } },
+ { scope = "context.embedded", settings = { foreground = mycolors.default, fontStyle = "bold" } },
{ scope = "context.char", settings = { foreground = mycolors.magenta } },
{ scope = "context.reserved", settings = { foreground = mycolors.magenta, fontStyle = "bold" } },
- { scope = "context.definition", settings = { foreground = mycolors.black, fontStyle = "bold" } },
+ { scope = "context.definition", settings = { foreground = mycolors.default, fontStyle = "bold" } },
{ scope = "context.okay", settings = { foreground = mycolors.dark } },
{ scope = "context.warning", settings = { foreground = mycolors.orange } },
{ scope = "context.standout", settings = { foreground = mycolors.orange, fontStyle = "bold" } },
@@ -492,12 +543,12 @@ function scripts.vscode.generate(targetpath)
{ scope = "context.plain", settings = { foreground = mycolors.dark, fontStyle = "bold" } },
{ scope = "context.user", settings = { foreground = mycolors.green } },
{ scope = "context.data", settings = { foreground = mycolors.cyan, fontStyle = "bold" } },
- { scope = "context.text", settings = { foreground = mycolors.black } },
+ { scope = "context.text", settings = { foreground = mycolors.default } },
{ scope = { "emphasis" }, settings = { fontStyle = "italic" } },
{ scope = { "strong" }, settings = { fontStyle = "bold" } },
- { scope = { "comment" }, settings = { foreground = mycolors.black } },
+ { scope = { "comment" }, settings = { foreground = mycolors.default } },
{ scope = { "string" }, settings = { foreground = mycolors.magenta } },
{
@@ -541,7 +592,7 @@ function scripts.vscode.generate(targetpath)
"entity.name.function.shell"
},
settings = {
- foreground = mycolors.black,
+ foreground = mycolors.default,
}
},
@@ -550,7 +601,7 @@ function scripts.vscode.generate(targetpath)
"entity.name.tag",
},
settings = {
- foreground = mycolors.black,
+ foreground = mycolors.default,
}
},
@@ -563,6 +614,8 @@ function scripts.vscode.generate(targetpath)
styles = styles,
}
+ -- registersettings()
+
end
do
@@ -576,41 +629,43 @@ function scripts.vscode.generate(targetpath)
clear = true,
}
+ -- chcp 65001 ; ...
+
local tasks = {
{
group = "build",
label = "process tex file",
type = "shell",
- command = "context --autogenerate --autopdf ${file}",
- windows = { command = "chcp 65001 ; context.exe --autogenerate --autopdf ${file}" },
+ command = "context --autogenerate --autopdf ${file}",
+ windows = { command = "context.exe --autogenerate --autopdf ${file}" },
},
{
group = "build",
label = "check tex file",
type = "shell",
- command = "mtxrun --autogenerate --script check ${file}",
- windows = { command = "chcp 65001 ; mtxrun.exe --autogenerate --script check ${file}" },
+ command = "mtxrun --autogenerate --script check ${file}",
+ windows = { command = "mtxrun.exe --autogenerate --script check ${file}" },
},
{
group = "build",
label = "identify fonts",
type = "shell",
- command = "mtxrun --script fonts --reload --force",
- windows = { command = "chcp 65001 ; mtxrun.exe --script fonts --reload --force" },
+ command = "mtxrun --script fonts --reload --force",
+ windows = { command = "mtxrun.exe --script fonts --reload --force" },
},
{
group = "build",
label = "process lua file",
type = "shell",
- command = "mtxrun --script ${file}",
- windows = { command = "chcp 65001 ; mtxrun.exe --script ${file}" },
+ command = "mtxrun --script ${file}",
+ windows = { command = "mtxrun.exe --script ${file}" },
},
}
for i=1,#tasks do
local task = tasks[i]
if not task.windows then
- task.windows = { command = "chcp 65001 ; " .. task.command }
+ task.windows = { command = task.command }
end
if not task.presentation then
task.presentation = presentation
@@ -697,7 +752,7 @@ function scripts.vscode.generate(targetpath)
for i=1,#t do
result[i] = string.gsub(t[i],".",escapes)
end
- return table.concat(result,"|")
+ return concat(result,"|")
end
local function capture(str)
@@ -869,12 +924,12 @@ function scripts.vscode.generate(targetpath)
-- mp argument {...text}
local function words(list)
table.sort(list,sorter)
- return "\\\\(" .. table.concat(list,"|") .. ")" .. "(?=[^a-zA-Z])"
+ return "\\\\(" .. concat(list,"|") .. ")" .. "(?=[^a-zA-Z])"
end
local function bwords(list)
table.sort(list,sorter)
- return "(\\\\(" .. table.concat(list,"|") .. "))\\s*(\\{)"
+ return "(\\\\(" .. concat(list,"|") .. "))\\s*(\\{)"
end
local function ewords()
@@ -883,7 +938,7 @@ function scripts.vscode.generate(targetpath)
local function environments(list)
table.sort(list,sorter)
- last = table.concat(list,"|")
+ last = concat(list,"|")
if #list > 1 then
last = "(?:" .. last .. ")"
end
@@ -975,7 +1030,7 @@ function scripts.vscode.generate(targetpath)
comment = {
name = style("context.comment", "comment"),
- match = texcomment,
+ match = comment,
},
constant = {
@@ -1188,7 +1243,7 @@ function scripts.vscode.generate(targetpath)
local function words(list)
table.sort(list,sorter)
- return "(" .. table.concat(list,"|") .. ")" .. "(?=[^a-zA-Z\\_@!?\127-\255])"
+ return "(" .. concat(list,"|") .. ")" .. "(?=[^a-zA-Z\\_@!?\127-\255])"
end
local capturedshortcuts = oneof(mergedshortcuts)
@@ -1401,7 +1456,7 @@ function scripts.vscode.generate(targetpath)
local function words(list)
table.sort(list,sorter)
- return "(" .. table.concat(list,"|") .. ")" .. "(?=[^a-zA-Z])"
+ return "(" .. concat(list,"|") .. ")" .. "(?=[^a-zA-Z])"
end
local capturedkeywords = words {
@@ -1642,7 +1697,7 @@ function scripts.vscode.generate(targetpath)
category = "cld",
description = "ConTeXt CLD",
- suffixes = { "lua", "luc", "cld", "tuc", "luj", "lum", "tma", "lfg", "luv", "lui" },
+ suffixes = { "lmt", "lua", "luc", "cld", "tuc", "luj", "lum", "tma", "lfg", "luv", "lui" },
version = lualexer.version,
setup = lualexer.setup,
@@ -2118,7 +2173,7 @@ function scripts.vscode.generate(targetpath)
local function words(list)
table.sort(list,sorter)
- local str = table.concat(list,"|")
+ local str = concat(list,"|")
return "(" .. str .. "|" .. string.upper(str) .. ")" .. "(?=[^a-zA-Z])"
end
@@ -2501,7 +2556,7 @@ function scripts.vscode.generate(targetpath)
local function words(list)
table.sort(list,sorter)
- return "\\b(" .. table.concat(list,"|") .. ")\\b"
+ return "\\b(" .. concat(list,"|") .. ")\\b"
end
local capturedkeywords = words { -- copied from cpp.lua
@@ -3157,10 +3212,272 @@ function scripts.vscode.generate(targetpath)
end
+-- {name: 'inherits: \\setupframed'}
+
+function scripts.vscode.ls(forcedinterface)
+
+ local interfaces = forcedinterfaces or environment.files or userinterfaces
+ if not interfaces.en then
+ -- loaded as script so we have "cont-yes.*" as name
+ interfaces = { "en" }
+ end
+ --
+ local filename = "context-en.xml"
+ local xmlfile = resolvers.findfile(filename) or ""
+ if xmlfile == "" then
+ report("unable to locate %a",filename)
+ return
+ end
+ --
+ local filename = "mult-def.lua"
+ local deffile = resolvers.findfile(filename) or ""
+ if deffile == "" then
+ report("unable to locate %a",filename)
+ return
+ end
+ local interface = dofile(deffile)
+ if not interface or not next(interface) then
+ report("invalid file %a",filename)
+ return
+ end
+ local variables = interface.variables
+ local constants = interface.constants
+ local commands = interface.commands
+ local elements = interface.elements
+ --
+ local collected = { }
+ --
+ report("loading %a",xmlfile)
+ local xmlroot = xml.load(xmlfile)
+
+ local interfaces = { "en" }
+
+-- <cd:keywords list="yes">
+-- <cd:inherit name="setupalign"/>
+-- </cd:keywords>
+
+ local function arguments(e)
+ local p = { }
+ for e in xml.collected(e,"/cd:arguments/*") do
+ local tg = e.tg
+ if tg == "keywords" then
+ local a = { }
+ for e in xml.collected(e,"/*") do
+ a[#a+1] = {
+ name = e.at.type
+ }
+ end
+ p[#p+1] = {
+ type = tg,
+ attributes = #a > 0 and a or nil,
+ optional = e.at.optional == "yes" or nil
+ }
+ elseif tg == "assignments" then
+ local a = { }
+ for e in xml.collected(e,"/parameter") do
+ -- local c = { e.at.name, "=" }
+ local c = { }
+ for e in xml.collected(e,"/constant") do
+ c[#c+1] = e.at.type
+ end
+ -- if #c > 0 then
+ -- a[#a+1] = {
+ -- name = concat(c, " ") -- maybe "|"
+ -- }
+ -- end
+ a[#a+1] = {
+ name = e.at.name .. "=" .. concat(c, " ") -- maybe "|"
+ }
+ end
+ p[#p+1] = {
+ type = tg,
+ attributes = #a > 0 and a or nil,
+ optional = e.at.optional == "yes" or nil
+ }
+ else -- e.g. "content"
+ p[#p+1] = {
+ type = tg,
+ optional = e.at.optional == "yes" or nil
+ }
+ end
+ end
+ return p
+ end
+
+ local function details(e, f)
+ local d = { "\\" .. f }
+ local n = 0
+ for e in xml.collected(e,"/cd:arguments/*") do
+ local tg = e.tg
+ if tg == "keywords" then
+ n = n + 1
+ if e.at.optional == "yes" then
+ d[#d+1] = "[optional " .. n .. ":..,..]"
+ else
+ d[#d+1] = "[mandate " .. n .. ":..,..]"
+ end
+ elseif tg == "assignments" then
+ n = n + 1
+ if e.at.optional == "yes" then
+ d[#d+1] = "[optional " .. n .. ":key=val,key=val,..]"
+ else
+ d[#d+1] = "[mandate " .. n .. ":key=val,key=val,..]"
+ end
+ else
+ d[#d+1] = "{ content }"
+ end
+ end
+ return concat(d, " ")
+ end
+
+ -- this one is a bit weird as it could be assembled in the languages server on the fly and
+ -- it bloats the file
+
+ local function documentation(c)
+ local d = { c.detail }
+ local p = c.params
+ if p then
+ local n = 0
+ for i=1,#p do
+ local pi = p[i]
+ local ti = pi.type
+ local ai = pi.attributes
+ if ti == "keywords" then
+ n = n + 1
+ if pi.optional then
+ d[#d+1] = "[optional keywords " .. n .. "]"
+ else
+ d[#d+1] = "[mandate keywords " .. n .. "]"
+ end
+ if ai then
+ local t = { }
+ for j=1,#ai do
+ t[#t+1] = ai[j].name
+ end
+ if #t > 0 then
+ d[#d+1] = concat(t," ")
+ end
+ end
+ elseif ti == "assignments" then
+ n = n + 1
+ if pi.optional then
+ d[#d+1] = "[optional assignments " .. n .. "]"
+ else
+ d[#d+1] = "[mandate assignments " .. n .. "]"
+ end
+ if ai then
+ local t = { }
+ for j=1,#ai do
+ t[#t+1] = ai[j].name
+ end
+ if #t > 0 then
+ d[#d+1] = concat(t,"\n")
+ end
+ end
+ else
+ if pi.optional then
+ d[#d+1] = "{ optional content }"
+ else
+ d[#d+1] = "{ mandate content }"
+ end
+ end
+ end
+ end
+ c.documentation = concat(d,"\n")
+-- inspect(c.documentation)
+ end
+
+ if not xml.expand then
+ -- will be in next version
+ function xml.expand(root,pattern,whatever)
+ local collected = xml.applylpath(root,pattern)
+ if collected then
+ for c=1,#collected do
+ local e = collected[c]
+ local p = e.__p__
+ if p then
+ local d = p.dt
+ local n = e.ni
+ local t = whatever(e,p)
+ if type(t) == "table" then
+ d[n] = t[1]
+ for i=2,#t do
+ n = n + 1
+ table.insert(d,n,t[i])
+ end
+ elseif t then
+ d[n] = t
+ end
+ end
+ end
+ end
+ end
+ end
+
+ do
+ local c = { }
+ xml.expand(xmlroot,"/cd:interface/cd:interface/cd:command/**/inherit",function(e)
+ local f = c[e.at.name]
+ if not f then
+ f = xml.first(xmlroot,"/cd:interface/cd:interface/cd:command[@name='" .. e.at.name .. "']/cd:arguments")
+ c[e.at.name] = f
+ end
+ return f and f.dt
+ end)
+ end
+
+ for i=1,#interfaces do
+ local interface = interfaces[i]
+ local start = elements.start[interface] or elements.start.en
+ local stop = elements.stop [interface] or elements.stop .en
+ for e in xml.collected(xmlroot,"cd:interface/cd:command") do
+ local at = e.at
+ local name = at["name"] or ""
+ local type = at["type"]
+ if name ~= "" then
+ local c = commands[name]
+ local n = (c and (c[interface] or c.en)) or c or name
+ local sequence = xml.all(e,"/cd:sequence/*")
+ if at.generated == "yes" then
+ -- skip (for now)
+ elseif type ~= "environment" then
+ collected[#collected+1] = {
+ name = n,
+ detail = details(e, n),
+ params = arguments(e), -- why not "parameters"
+ }
+ else
+ local f = start .. n
+ collected[#collected+1] = {
+ name = f,
+ start = f,
+ stop = stop .. n,
+ detail = details(e, f),
+ params = arguments(e), -- why not "parameters"
+ }
+ end
+ end
+ end
+ end
+ for i=1,#collected do
+ documentation(collected[i])
+ end
+ local jsonname = "vscode-context-ls.json"
+ -- local exmlname = "vscode-context-ls.xml"
+ report("")
+ report("vscode ls file saved: %s",jsonname)
+ report("")
+ io.savedata(jsonname,utilities.json.tojson(collected))
+ -- io.savedata(exmlname,tostring(xmlroot))
+end
+
function scripts.vscode.start()
local path = locate()
if path then
- local command = 'start "vs code context" code --reuse-window --ignore-gpu-blacklist --extensions-dir "' .. path .. '" --install-extension context'
+ local codecmd = environment.arguments.program or "code" -- can be codium
+ -- local command = 'start "vs code context" ' .. codecmd .. ' --reuse-window --ignore-gpu-blacklist --extensions-dir "' .. path .. '" --install-extension context'
+ -- local command = 'start "vs code context" ' .. codecmd .. ' --reuse-window --extensions-dir "' .. path .. '" --install-extension context'
+ local command = 'start "vs code context" ' .. codecmd .. ' --reuse-window --extensions-dir "' .. path .. '" --verbose --force --install-extension cdt.context'
report("running command: %s",command)
os.execute(command)
end
@@ -3168,6 +3485,8 @@ end
if environment.arguments.generate then
scripts.vscode.generate()
+elseif environment.arguments.lsfile then
+ scripts.vscode.ls()
elseif environment.arguments.start then
scripts.vscode.start()
elseif environment.arguments.exporthelp then
@@ -3176,4 +3495,6 @@ else
application.help()
end
-scripts.vscode.generate([[t:/vscode/data/context/extensions]])
+-- scripts.vscode.ls()
+
+-- scripts.vscode.generate([[t:/vscode/data/context/extensions]])
diff --git a/Master/texmf-dist/scripts/context/lua/mtxrun.lua b/Master/texmf-dist/scripts/context/lua/mtxrun.lua
index 6fc17adb022..a00dc59288c 100755
--- a/Master/texmf-dist/scripts/context/lua/mtxrun.lua
+++ b/Master/texmf-dist/scripts/context/lua/mtxrun.lua
@@ -1201,7 +1201,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["l-lpeg"] = package.loaded["l-lpeg"] or true
--- original size: 38703, stripped down to: 19489
+-- original size: 38742, stripped down to: 19489
if not modules then modules={} end modules ['l-lpeg']={
version=1.001,
@@ -2004,7 +2004,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["l-string"] = package.loaded["l-string"] or true
--- original size: 6644, stripped down to: 3410
+-- original size: 6955, stripped down to: 3504
if not modules then modules={} end modules ['l-string']={
version=1.001,
@@ -2014,7 +2014,7 @@ if not modules then modules={} end modules ['l-string']={
license="see context related readme files"
}
local string=string
-local sub,gmatch,format,char,byte,rep,lower=string.sub,string.gmatch,string.format,string.char,string.byte,string.rep,string.lower
+local sub,gmatch,format,char,byte,rep,lower,find=string.sub,string.gmatch,string.format,string.char,string.byte,string.rep,string.lower,string.find
local lpegmatch,patterns=lpeg.match,lpeg.patterns
local P,S,C,Ct,Cc,Cs=lpeg.P,lpeg.S,lpeg.C,lpeg.Ct,lpeg.Cc,lpeg.Cs
local unquoted=patterns.squote*C(patterns.nosquote)*patterns.squote+patterns.dquote*C(patterns.nodquote)*patterns.dquote
@@ -2024,10 +2024,18 @@ end
function string.quoted(str)
return format("%q",str)
end
-function string.count(str,pattern)
+function string.count(str,pattern)
local n=0
- for _ in gmatch(str,pattern) do
- n=n+1
+ local i=1
+ local l=#pattern
+ while true do
+ i=find(str,pattern,i)
+ if i then
+ n=n+1
+ i=i+l
+ else
+ break
+ end
end
return n
end
@@ -3285,7 +3293,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["l-io"] = package.loaded["l-io"] or true
--- original size: 11829, stripped down to: 6331
+-- original size: 11988, stripped down to: 6430
if not modules then modules={} end modules ['l-io']={
version=1.001,
@@ -3352,9 +3360,12 @@ function io.copydata(source,target,action)
flush()
end
end
-function io.savedata(filename,data,joiner)
- local f=open(filename,"wb")
+function io.savedata(filename,data,joiner,append)
+ local f=open(filename,append and "ab" or "wb")
if f then
+ if append and joiner and f:seek("end")>0 then
+ f:write(joiner)
+ end
if type(data)=="table" then
f:write(concat(data,joiner or ""))
elseif type(data)=="function" then
@@ -3637,17 +3648,17 @@ do -- create closure to overcome 200 locals limit
package.loaded["l-number"] = package.loaded["l-number"] or true
--- original size: 5720, stripped down to: 2176
+-- original size: 4588, stripped down to: 2159
if not modules then modules={} end modules ['l-number']={
version=1.001,
- comment="companion to luat-lib.mkiv",
+ comment="companion to luat-lib.mkxl",
author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
local tostring,tonumber=tostring,tonumber
-local format,floor,match,rep=string.format,math.floor,string.match,string.rep
+local format,match,rep=string.format,string.match,string.rep
local concat,insert=table.concat,table.insert
local lpegmatch=lpeg.match
local floor=math.floor
@@ -3837,7 +3848,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["l-os"] = package.loaded["l-os"] or true
--- original size: 19409, stripped down to: 10419
+-- original size: 20585, stripped down to: 10701
if not modules then modules={} end modules ['l-os']={
version=1.001,
@@ -3847,10 +3858,10 @@ if not modules then modules={} end modules ['l-os']={
license="see context related readme files"
}
local os=os
-local date,time=os.date,os.time
+local date,time,difftime=os.date,os.time,os.difftime
local find,format,gsub,upper,gmatch=string.find,string.format,string.gsub,string.upper,string.gmatch
local concat=table.concat
-local random,ceil,randomseed=math.random,math.ceil,math.randomseed
+local random,ceil,randomseed,modf=math.random,math.ceil,math.randomseed,math.modf
local type,setmetatable,tonumber,tostring=type,setmetatable,tonumber,tostring
do
local selfdir=os.selfdir
@@ -3948,7 +3959,7 @@ if not os.__getenv__ then
osenv[K]=v
end
function os.getenv(k)
- local K=upper(k)
+ local K=upper(k)
local v=osenv[K] or osgetenv(K) or osgetenv(k)
if v=="" then
return nil
@@ -3966,22 +3977,6 @@ if not os.__getenv__ then
setmetatable(os.env,{ __index=__index,__newindex=__newindex } )
end
end
-local execute=os.execute
-local iopopen=io.popen
-local function resultof(command)
- local handle=iopopen(command,"r")
- if handle then
- local result=handle:read("*all") or ""
- handle:close()
- return result
- else
- return ""
- end
-end
-os.resultof=resultof
-function os.pipeto(command)
- return iopopen(command,"w")
-end
if not io.fileseparator then
if find(os.getenv("PATH"),";",1,true) then
io.fileseparator,io.pathseparator,os.type="\\",";",os.type or "windows"
@@ -3996,228 +3991,231 @@ if os.type=="windows" then
else
os.libsuffix,os.binsuffix,os.binsuffixes='so','',{ '' }
end
-local launchers={
- windows="start %s",
- macosx="open %s",
- unix="xdg-open %s &> /dev/null &",
-}
-function os.launch(str)
- local command=format(launchers[os.name] or launchers.unix,str)
- execute(command)
-end
-local gettimeofday=os.gettimeofday or os.clock
-os.gettimeofday=gettimeofday
-local startuptime=gettimeofday()
-function os.runtime()
- return gettimeofday()-startuptime
-end
-local resolvers=os.resolvers or {}
-os.resolvers=resolvers
-setmetatable(os,{ __index=function(t,k)
- local r=resolvers[k]
- return r and r(t,k) or nil
-end })
-local name,platform=os.name or "linux",os.getenv("MTX_PLATFORM") or ""
-if platform~="" then
- os.platform=platform
-elseif os.type=="windows" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("PROCESSOR_ARCHITECTURE") or ""
- local platform=""
- if find(architecture,"AMD64",1,true) then
- platform="win64"
+do
+ local execute=os.execute
+ local iopopen=io.popen
+ local ostype=os.type
+ local function resultof(command)
+ local handle=iopopen(command,ostype=="windows" and "rb" or "r")
+ if handle then
+ local result=handle:read("*all") or ""
+ handle:close()
+ return result
else
- platform="mswin"
+ return ""
end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
end
-elseif name=="linux" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("HOSTTYPE") or resultof("uname -m") or ""
- local platform=os.getenv("MTX_PLATFORM") or ""
+ os.resultof=resultof
+ function os.pipeto(command)
+ return iopopen(command,"w")
+ end
+ local launchers={
+ windows="start %s",
+ macosx="open %s",
+ unix="xdg-open %s &> /dev/null &",
+ }
+ function os.launch(str)
+ local command=format(launchers[os.name] or launchers.unix,str)
+ execute(command)
+ end
+end
+do
+ local gettimeofday=os.gettimeofday or os.clock
+ os.gettimeofday=gettimeofday
+ local startuptime=gettimeofday()
+ function os.runtime()
+ return gettimeofday()-startuptime
+ end
+end
+do
+ local name=os.name or "linux"
+ local platform=os.getenv("MTX_PLATFORM") or ""
+ local architecture=os.uname and os.uname().machine
+ local bits=os.getenv("MTX_BITS") or find(platform,"64") and 64 or 32
+ if platform~="" then
+ elseif os.type=="windows" then
+ architecture=string.lower(architecture or os.getenv("PROCESSOR_ARCHITECTURE") or "")
+ if architecture=="x86_64" then
+ bits,platform=64,"win64"
+ elseif find(architecture,"amd64") then
+ bits,platform=64,"win64"
+ elseif find(architecture,"arm64") then
+ bits,platform=64,"windows-arm64"
+ elseif find(architecture,"arm32") then
+ bits,platform=32,"windows-arm32"
+ else
+ bits,platform=32,"mswin"
+ end
+ elseif name=="linux" then
+ architecture=architecture or os.getenv("HOSTTYPE") or resultof("uname -m") or ""
local musl=find(os.selfdir or "","linuxmusl")
- if platform~="" then
- elseif find(architecture,"x86_64",1,true) then
- platform=musl and "linuxmusl" or "linux-64"
- elseif find(architecture,"ppc",1,true) then
- platform="linux-ppc"
+ if find(architecture,"x86_64") then
+ bits,platform=64,musl and "linuxmusl" or "linux-64"
+ elseif find(architecture,"ppc") then
+ bits,platform=32,"linux-ppc"
else
- platform=musl and "linuxmusl" or "linux"
+ bits,platform=32,musl and "linuxmusl" or "linux"
end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="macosx" then
- function resolvers.platform(t,k)
- local architecture=resultof("echo $HOSTTYPE") or ""
- local platform=""
+ elseif name=="macosx" then
+ architecture=architecture or resultof("echo $HOSTTYPE") or ""
if architecture=="" then
- platform="osx-intel"
- elseif find(architecture,"i386",1,true) then
- platform="osx-intel"
- elseif find(architecture,"x86_64",1,true) then
- platform="osx-64"
- elseif find(architecture,"arm64",1,true) then
- platform="osx-64"
+ bits,platform=64,"osx-intel"
+ elseif find(architecture,"i386") then
+ bits,platform=64,"osx-intel"
+ elseif find(architecture,"x86_64") then
+ bits,platform=64,"osx-64"
+ elseif find(architecture,"arm64") then
+ bits,platform=64,"osx-arm"
else
- platform="osx-ppc"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="sunos" then
- function resolvers.platform(t,k)
- local architecture=resultof("uname -m") or ""
- local platform=""
- if find(architecture,"sparc",1,true) then
- platform="solaris-sparc"
+ bits,platform=32,"osx-ppc"
+ end
+ elseif name=="sunos" then
+ architecture=architecture or resultof("uname -m") or ""
+ if find(architecture,"sparc") then
+ bits,platform=32,"solaris-sparc"
else
- platform="solaris-intel"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="freebsd" then
- function resolvers.platform(t,k)
- local architecture=resultof("uname -m") or ""
- local platform=""
- if find(architecture,"amd64",1,true) then
- platform="freebsd-amd64"
+ bits,platform=32,"solaris-intel"
+ end
+ elseif name=="freebsd" then
+ architecture=architecture or os.getenv("MACHTYPE") or resultof("uname -m") or ""
+ if find(architecture,"amd64") or find(architecture,"AMD64") then
+ bits,platform=64,"freebsd-amd64"
else
- platform="freebsd"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="kfreebsd" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("HOSTTYPE") or resultof("uname -m") or ""
- local platform=""
- if find(architecture,"x86_64",1,true) then
- platform="kfreebsd-amd64"
+ bits,platform=32,"freebsd"
+ end
+ elseif name=="kfreebsd" then
+ architecture=architecture or os.getenv("HOSTTYPE") or resultof("uname -m") or ""
+ if architecture=="x86_64" then
+ bits,platform=64,"kfreebsd-amd64"
+ else
+ bits,platform=32,"kfreebsd-i386"
+ end
+ else
+ architecture=architecture or resultof("uname -m") or ""
+ if find(architecture,"aarch64") then
+ bits,platform="linux-aarch64"
+ elseif find(architecture,"armv7l") then
+ bits,platform=32,"linux-armhf"
+ elseif find(architecture,"mips64") or find(architecture,"mips64el") then
+ bits,platform=64,"linux-mipsel"
+ elseif find(architecture,"mipsel") or find(architecture,"mips") then
+ bits,platform=32,"linux-mipsel"
else
- platform="kfreebsd-i386"
+ bits,platform=64,"linux-64"
end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
end
-else
- function resolvers.platform(t,k)
- local platform="linux"
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-end
-os.newline=name=="windows" and "\013\010" or "\010"
-function resolvers.bits(t,k)
- local bits=find(os.platform,"64",1,true) and 64 or 32
+ os.setenv("MTX_PLATFORM",platform)
+ os.setenv("MTX_BITS",bits)
+ os.platform=platform
os.bits=bits
- return bits
-end
-local t={ 8,9,"a","b" }
-function os.uuid()
- return format("%04x%04x-4%03x-%s%03x-%04x-%04x%04x%04x",
- random(0xFFFF),random(0xFFFF),
- random(0x0FFF),
- t[ceil(random(4))] or 8,random(0x0FFF),
- random(0xFFFF),
- random(0xFFFF),random(0xFFFF),random(0xFFFF)
- )
+ os.newline=name=="windows" and "\013\010" or "\010"
+end
+do
+ local t={ 8,9,"a","b" }
+ function os.uuid()
+ return format("%04x%04x-4%03x-%s%03x-%04x-%04x%04x%04x",
+ random(0xFFFF),random(0xFFFF),
+ random(0x0FFF),
+ t[ceil(random(4))] or 8,random(0x0FFF),
+ random(0xFFFF),
+ random(0xFFFF),random(0xFFFF),random(0xFFFF)
+ )
+ end
end
-local d
-function os.timezone(delta)
- d=d or ((tonumber(date("%H")) or 0)-(tonumber(date("!%H")) or 0))
- if delta then
- if d>0 then
- return format("+%02i:00",d)
+do
+ local hour,min
+ function os.timezone(difference)
+ if not hour then
+ local current=time()
+ local utcdate=date("!*t",current)
+ local localdate=date("*t",current)
+ localdate.isdst=false
+ local timediff=difftime(time(localdate),time(utcdate))
+ hour,min=modf(timediff/3600)
+ min=min*60
+ end
+ if difference then
+ return hour,min
else
- return format("-%02i:00",-d)
+ return format("%+03d:%02d",hour,min)
end
- else
- return 1
end
-end
-local timeformat=format("%%s%s",os.timezone(true))
-local dateformat="!%Y-%m-%d %H:%M:%S"
-local lasttime=nil
-local lastdate=nil
-function os.fulltime(t,default)
- t=t and tonumber(t) or 0
- if t>0 then
- elseif default then
- return default
- else
- t=time()
+ local timeformat=format("%%s%s",os.timezone())
+ local dateformat="%Y-%m-%d %H:%M:%S"
+ local lasttime=nil
+ local lastdate=nil
+ function os.fulltime(t,default)
+ t=t and tonumber(t) or 0
+ if t>0 then
+ elseif default then
+ return default
+ else
+ t=time()
+ end
+ if t~=lasttime then
+ lasttime=t
+ lastdate=format(timeformat,date(dateformat))
+ end
+ return lastdate
end
- if t~=lasttime then
- lasttime=t
- lastdate=format(timeformat,date(dateformat))
+ local dateformat="%Y-%m-%d %H:%M:%S"
+ local lasttime=nil
+ local lastdate=nil
+ function os.localtime(t,default)
+ t=t and tonumber(t) or 0
+ if t>0 then
+ elseif default then
+ return default
+ else
+ t=time()
+ end
+ if t~=lasttime then
+ lasttime=t
+ lastdate=date(dateformat,t)
+ end
+ return lastdate
end
- return lastdate
-end
-local dateformat="%Y-%m-%d %H:%M:%S"
-local lasttime=nil
-local lastdate=nil
-function os.localtime(t,default)
- t=t and tonumber(t) or 0
- if t>0 then
- elseif default then
- return default
- else
- t=time()
+ function os.converttime(t,default)
+ local t=tonumber(t)
+ if t and t>0 then
+ return date(dateformat,t)
+ else
+ return default or "-"
+ end
end
- if t~=lasttime then
- lasttime=t
- lastdate=date(dateformat,t)
+ function os.today()
+ return date("!*t")
end
- return lastdate
-end
-function os.converttime(t,default)
- local t=tonumber(t)
- if t and t>0 then
- return date(dateformat,t)
- else
- return default or "-"
+ function os.now()
+ return date("!%Y-%m-%d %H:%M:%S")
end
end
-local memory={}
-local function which(filename)
- local fullname=memory[filename]
- if fullname==nil then
- local suffix=file.suffix(filename)
- local suffixes=suffix=="" and os.binsuffixes or { suffix }
- for directory in gmatch(os.getenv("PATH"),"[^"..io.pathseparator.."]+") do
- local df=file.join(directory,filename)
- for i=1,#suffixes do
- local dfs=file.addsuffix(df,suffixes[i])
- if io.exists(dfs) then
- fullname=dfs
- break
+do
+ local cache={}
+ local function which(filename)
+ local fullname=cache[filename]
+ if fullname==nil then
+ local suffix=file.suffix(filename)
+ local suffixes=suffix=="" and os.binsuffixes or { suffix }
+ for directory in gmatch(os.getenv("PATH"),"[^"..io.pathseparator.."]+") do
+ local df=file.join(directory,filename)
+ for i=1,#suffixes do
+ local dfs=file.addsuffix(df,suffixes[i])
+ if io.exists(dfs) then
+ fullname=dfs
+ break
+ end
end
end
+ if not fullname then
+ fullname=false
+ end
+ cache[filename]=fullname
end
- if not fullname then
- fullname=false
- end
- memory[filename]=fullname
+ return fullname
end
- return fullname
-end
-os.which=which
-os.where=which
-function os.today()
- return date("!*t")
-end
-function os.now()
- return date("!%Y-%m-%d %H:%M:%S")
+ os.which=which
+ os.where=which
end
if not os.sleep then
local socket=socket
@@ -4228,65 +4226,69 @@ if not os.sleep then
socket.sleep(n)
end
end
-local function isleapyear(year)
- return (year%4==0) and (year%100~=0 or year%400==0)
-end
-os.isleapyear=isleapyear
-local days={ 31,28,31,30,31,30,31,31,30,31,30,31 }
-local function nofdays(year,month,day)
- if not month then
- return isleapyear(year) and 365 or 364
- elseif not day then
- return month==2 and isleapyear(year) and 29 or days[month]
- else
- for i=1,month-1 do
- day=day+days[i]
- end
- if month>2 and isleapyear(year) then
- day=day+1
+do
+ local function isleapyear(year)
+ return (year%4==0) and (year%100~=0 or year%400==0)
+ end
+ os.isleapyear=isleapyear
+ local days={ 31,28,31,30,31,30,31,31,30,31,30,31 }
+ local function nofdays(year,month,day)
+ if not month then
+ return isleapyear(year) and 365 or 364
+ elseif not day then
+ return month==2 and isleapyear(year) and 29 or days[month]
+ else
+ for i=1,month-1 do
+ day=day+days[i]
+ end
+ if month>2 and isleapyear(year) then
+ day=day+1
+ end
+ return day
end
- return day
end
-end
-os.nofdays=nofdays
-function os.weekday(day,month,year)
- return date("%w",time { year=year,month=month,day=day })+1
-end
-function os.validdate(year,month,day)
- if month<1 then
- month=1
- elseif month>12 then
- month=12
+ os.nofdays=nofdays
+ function os.weekday(day,month,year)
+ return date("%w",time { year=year,month=month,day=day })+1
end
- if day<1 then
- day=1
- else
- local max=nofdays(year,month)
- if day>max then
- day=max
+ function os.validdate(year,month,day)
+ if month<1 then
+ month=1
+ elseif month>12 then
+ month=12
+ end
+ if day<1 then
+ day=1
+ else
+ local max=nofdays(year,month)
+ if day>max then
+ day=max
+ end
end
+ return year,month,day
end
- return year,month,day
-end
-function os.date(fmt,...)
- if not fmt then
- fmt="%Y-%m-%d %H:%M"
+ function os.date(fmt,...)
+ if not fmt then
+ fmt="%Y-%m-%d %H:%M"
+ end
+ return date(fmt,...)
end
- return date(fmt,...)
-end
-local osexit=os.exit
-local exitcode=nil
-function os.setexitcode(code)
- exitcode=code
end
-function os.exit(c)
- if exitcode~=nil then
- return osexit(exitcode)
+do
+ local osexit=os.exit
+ local exitcode=nil
+ function os.setexitcode(code)
+ exitcode=code
end
- if c~=nil then
- return osexit(c)
+ function os.exit(c)
+ if exitcode~=nil then
+ return osexit(exitcode)
+ end
+ if c~=nil then
+ return osexit(c)
+ end
+ return osexit()
end
- return osexit()
end
@@ -4296,7 +4298,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["l-file"] = package.loaded["l-file"] or true
--- original size: 22175, stripped down to: 10302
+-- original size: 22186, stripped down to: 10313
if not modules then modules={} end modules ['l-file']={
version=1.001,
@@ -4552,7 +4554,7 @@ function file.join(one,two,three,...)
if not two then
return one=="" and one or lpegmatch(reslasher,one)
end
- if one=="" then
+ if not one or one=="" then
return lpegmatch(stripper,three and concat({ two,three,... },"/") or two)
end
if lpegmatch(isnetwork,one) then
@@ -4714,7 +4716,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["l-gzip"] = package.loaded["l-gzip"] or true
--- original size: 5115, stripped down to: 1699
+-- original size: 268, stripped down to: 216
if not modules then modules={} end modules ['l-gzip']={
version=1.001,
@@ -4722,76 +4724,6 @@ if not modules then modules={} end modules ['l-gzip']={
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
-gzip=gzip or {}
-if not zlib then
- zlib=xzip
-elseif not xzip then
- xzip=zlib
-end
-if zlib then
- local suffix=file.suffix
- local suffixes=file.suffixes
- local find=string.find
- local openfile=io.open
- local gzipwindow=15+16
- local gziplevel=3
- local identifier="^\x1F\x8B\x08"
- local compress=zlib.compress
- local decompress=zlib.decompress
- function gzip.load(filename)
- local f=openfile(filename,"rb")
- if not f then
- else
- local data=f:read("*all")
- f:close()
- if data and data~="" then
- if suffix(filename)=="gz" then
- data=decompress(data,gzipwindow)
- end
- return data
- end
- end
- end
- function gzip.save(filename,data,level)
- if suffix(filename)~="gz" then
- filename=filename..".gz"
- end
- local f=openfile(filename,"wb")
- if f then
- data=compress(data or "",level or gziplevel,nil,gzipwindow)
- f:write(data)
- f:close()
- return #data
- end
- end
- function gzip.suffix(filename)
- local suffix,extra=suffixes(filename)
- local gzipped=extra=="gz"
- return suffix,gzipped
- end
- function gzip.compressed(s)
- return s and find(s,identifier)
- end
- function gzip.compress(s,level)
- if s and not find(s,identifier) then
- if not level then
- level=gziplevel
- elseif level<=0 then
- return s
- elseif level>9 then
- level=9
- end
- return compress(s,level or gziplevel,nil,gzipwindow) or s
- end
- end
- function gzip.decompress(s)
- if s and find(s,identifier) then
- return decompress(s,gzipwindow)
- else
- return s
- end
- end
-end
end -- of closure
@@ -4926,7 +4858,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["l-url"] = package.loaded["l-url"] or true
--- original size: 14755, stripped down to: 6981
+-- original size: 14713, stripped down to: 6981
if not modules then modules={} end modules ['l-url']={
version=1.001,
@@ -5190,7 +5122,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["l-dir"] = package.loaded["l-dir"] or true
--- original size: 18253, stripped down to: 10816
+-- original size: 18217, stripped down to: 10792
if not modules then modules={} end modules ['l-dir']={
version=1.001,
@@ -5380,15 +5312,15 @@ local separator,pattern
if onwindows then
local slash=S("/\\")/"/"
pattern={
- [1]=(Cs(P(".")+slash^1)+Cs(R("az","AZ")*P(":")*slash^0)+Cc("./"))*V(2)*V(3),
- [2]=Cs(((1-S("*?/\\"))^0*slash)^0),
- [3]=Cs(P(1)^0)
+ (Cs(P(".")+slash^1)+Cs(R("az","AZ")*P(":")*slash^0)+Cc("./"))*V(2)*V(3),
+ Cs(((1-S("*?/\\"))^0*slash)^0),
+ Cs(P(1)^0)
}
else
pattern={
- [1]=(C(P(".")+P("/")^1)+Cc("./"))*V(2)*V(3),
- [2]=C(((1-S("*?/"))^0*P("/"))^0),
- [3]=C(P(1)^0)
+ (C(P(".")+P("/")^1)+Cc("./"))*V(2)*V(3),
+ C(((1-S("*?/"))^0*P("/"))^0),
+ C(P(1)^0)
}
end
local filter=Cs ((
@@ -6509,7 +6441,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["l-math"] = package.loaded["l-math"] or true
--- original size: 2555, stripped down to: 1831
+-- original size: 2679, stripped down to: 1909
if not modules then modules={} end modules ['l-math']={
version=1.001,
@@ -6522,8 +6454,14 @@ if not math.ceiling then
math.ceiling=math.ceil
end
if not math.round then
- local floor=math.floor
- function math.round(x) return floor(x+0.5) end
+ if xmath then
+ math.round=xmath.round
+ else
+ local floor=math.floor
+ function math.round(x)
+ return x<0 and -floor(-x+0.5) or floor(x+0.5)
+ end
+ end
end
if not math.div then
local floor=math.floor
@@ -6593,7 +6531,7 @@ if not math.tointeger then
end
if not math.ult then
local floor=math.floor
- function math.tointeger(m,n)
+ function math.ult(m,n)
return floor(m)<floor(n)
end
end
@@ -6605,7 +6543,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["util-str"] = package.loaded["util-str"] or true
--- original size: 45129, stripped down to: 23525
+-- original size: 46322, stripped down to: 24128
if not modules then modules={} end modules ['util-str']={
version=1.001,
@@ -6617,12 +6555,13 @@ if not modules then modules={} end modules ['util-str']={
utilities=utilities or {}
utilities.strings=utilities.strings or {}
local strings=utilities.strings
-local format,gsub,rep,sub,find=string.format,string.gsub,string.rep,string.sub,string.find
+local format,gsub,rep,sub,find,char=string.format,string.gsub,string.rep,string.sub,string.find,string.char
local load,dump=load,string.dump
local tonumber,type,tostring,next,setmetatable=tonumber,type,tostring,next,setmetatable
local unpack,concat=table.unpack,table.concat
local P,V,C,S,R,Ct,Cs,Cp,Carg,Cc=lpeg.P,lpeg.V,lpeg.C,lpeg.S,lpeg.R,lpeg.Ct,lpeg.Cs,lpeg.Cp,lpeg.Carg,lpeg.Cc
local patterns,lpegmatch=lpeg.patterns,lpeg.match
+local tsplitat=lpeg.tsplitat
local utfchar,utfbyte,utflen=utf.char,utf.byte,utf.len
local loadstripped=function(str,shortcuts)
if shortcuts then
@@ -6976,6 +6915,14 @@ patterns.escapedquotes=pattern
function string.escapedquotes(s)
return lpegmatch(pattern,s)
end
+local pattern=(1-P("\\"))^1;pattern=Cs (
+ pattern*((P("\\")/""*(digit^-3/function(s) return char(tonumber(s)) end))+pattern )^1
+)
+patterns.unescapedquotes=pattern
+function string.unescapedquotes(s)
+ return lpegmatch(pattern,s) or s
+end
+string.texnewlines=lpeg.replacer(patterns.newline,"\r",true)
local preamble=""
local environment={
global=global or _G,
@@ -7511,7 +7458,6 @@ function number.to16dot16(n)
return f_16_16(n/65536.0)
end
if not string.explode then
- local tsplitat=lpeg.tsplitat
local p_utf=patterns.utf8character
local p_check=C(p_utf)*(P("+")*Cc(true))^0
local p_split=Ct(C(p_utf)^0)
@@ -7531,6 +7477,20 @@ if not string.explode then
end
end
end
+do
+ local p_whitespace=patterns.whitespace^1
+ local cache=setmetatable({},{ __index=function(t,k)
+ local p=tsplitat(p_whitespace*P(k)*p_whitespace)
+ local v=function(s)
+ return lpegmatch(p,s)
+ end
+ t[k]=v
+ return v
+ end })
+ function string.wordsplitter(s)
+ return cache[s]
+ end
+end
end -- of closure
@@ -7539,7 +7499,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["util-tab"] = package.loaded["util-tab"] or true
--- original size: 32815, stripped down to: 18257
+-- original size: 34148, stripped down to: 18419
if not modules then modules={} end modules ['util-tab']={
version=1.001,
@@ -7866,9 +7826,6 @@ if JITSUPPORTED then
return concat(fastserialize(t,true))
end
else
- local f_v=formatters["[%q]=%q,"]
- local f_t=formatters["[%q]="]
- local f_q=formatters["%q,"]
function table.fastserialize(t,prefix)
local r={ type(prefix)=="string" and prefix or "return" }
local m=1
@@ -7880,7 +7837,7 @@ else
local v=t[0]
if v then
m=m+1
- r[m]="[0]='"
+ r[m]="[0]="
if type(v)=="table" then
fastserialize(v)
else
@@ -8277,6 +8234,21 @@ function table.ordered(t)
return function() end
end
end
+function combine(target,source)
+ if target then
+ for k,v in next,source do
+ if type(v)=="table" then
+ target[k]=combine(target[k],source[k])
+ else
+ target[k]=v
+ end
+ end
+ return target
+ else
+ return source
+ end
+end
+table.combine=combine
end -- of closure
@@ -8285,7 +8257,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["util-fil"] = package.loaded["util-fil"] or true
--- original size: 11552, stripped down to: 9023
+-- original size: 11474, stripped down to: 8973
if not modules then modules={} end modules ['util-fil']={
version=1.001,
@@ -8452,20 +8424,20 @@ function files.readinteger4le(f)
end
end
function files.readfixed2(f)
- local a,b=byte(f:read(2),1,2)
- if a>=0x80 then
- tonumber((a-0x100).."."..b)
- else
- tonumber((a ).."."..b)
+ local n1,n2=byte(f:read(2),1,2)
+ if n1>=0x80 then
+ n1=n1-0x100
end
+ return n1+n2/0xFF
end
function files.readfixed4(f)
local a,b,c,d=byte(f:read(4),1,4)
- if a>=0x80 then
- tonumber((0x100*a+b-0x10000).."."..(0x100*c+d))
- else
- tonumber((0x100*a+b ).."."..(0x100*c+d))
+ local n1=0x100*a+b
+ local n2=0x100*c+d
+ if n1>=0x8000 then
+ n1=n1-0x10000
end
+ return n1+n2/0xFFFF
end
if bit32 then
local extract=bit32.extract
@@ -8654,7 +8626,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["util-sac"] = package.loaded["util-sac"] or true
--- original size: 12968, stripped down to: 9523
+-- original size: 14071, stripped down to: 10417
if not modules then modules={} end modules ['util-sac']={
version=1.001,
@@ -8881,23 +8853,23 @@ function streams.readfixed2(f)
local i=f[2]
local j=i+1
f[2]=j+1
- local a,b=byte(f[1],i,j)
- if a>=0x80 then
- return tonumber((a-0x100).."."..b) or 0
- else
- return tonumber((a ).."."..b) or 0
+ local n1,n2=byte(f[1],i,j)
+ if n1>=0x80 then
+ n1=n1-0x100
end
+ return n1+n2/0xFF
end
function streams.readfixed4(f)
local i=f[2]
local j=i+3
f[2]=j+1
local a,b,c,d=byte(f[1],i,j)
- if a>=0x80 then
- return tonumber((0x100*a+b-0x10000).."."..(0x100*c+d)) or 0
- else
- return tonumber((0x100*a+b ).."."..(0x100*c+d)) or 0
+ local n1=0x100*a+b
+ local n2=0x100*c+d
+ if n1>=0x8000 then
+ n1=n1-0x10000
end
+ return n1+n2/0xFFFF
end
if bit32 then
local extract=bit32.extract
@@ -8986,10 +8958,10 @@ if sio and sio.readcardinal2 then
f[2]=i+4
return readfixed4(f[1],i)
end
- function streams.read2dot4(f)
+ function streams.read2dot14(f)
local i=f[2]
f[2]=i+2
- return read2dot4(f[1],i)
+ return read2dot14(f[1],i)
end
function streams.readbytes(f,n)
local i=f[2]
@@ -9095,10 +9067,10 @@ do
function io.newreader(str,method)
local f,m
if method=="string" then
- f=openstring(str)
+ f=openstring(str,true)
m=streams
elseif method=="stream" then
- f=openstream(str)
+ f=openstream(str,true)
m=streams
else
f=openfile(str,"rb")
@@ -9129,6 +9101,33 @@ do
end
end
end
+if bit32 and not streams.tocardinal1 then
+ local extract=bit32.extract
+ local char=string.char
+ streams.tocardinal1=char
+ function streams.tocardinal2(n) return char(extract(8,8),extract(0,8)) end
+ function streams.tocardinal3(n) return char(extract(16,8),extract(8,8),extract(0,8)) end
+ function streams.tocardinal4(n) return char(extract(24,8),extract(16,8),extract(8,8),extract(0,8)) end
+ streams.tocardinal1le=char
+ function streams.tocardinal2le(n) return char(extract(0,8),extract(8,8)) end
+ function streams.tocardinal3le(n) return char(extract(0,8),extract(8,8),extract(16,8)) end
+ function streams.tocardinal4le(n) return char(extract(0,8),extract(8,8),extract(16,8),extract(24,8)) end
+end
+if not streams.readcstring then
+ local readchar=streams.readchar
+ local concat=table.concat
+ function streams.readcstring(f)
+ local t={}
+ while true do
+ local c=readchar(f)
+ if c and c~="\0" then
+ t[#t+1]=c
+ else
+ return concat(t)
+ end
+ end
+ end
+end
end -- of closure
@@ -9308,7 +9307,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["util-prs"] = package.loaded["util-prs"] or true
--- original size: 24683, stripped down to: 16431
+-- original size: 25542, stripped down to: 16783
if not modules then modules={} end modules ['util-prs']={
version=1.001,
@@ -9357,8 +9356,8 @@ local noparent=1-(lparent+rparent)
local nobracket=1-(lbracket+rbracket)
local escape,left,right=P("\\"),P('{'),P('}')
lpegpatterns.balanced=P {
- [1]=((escape*(left+right))+(1-(left+right))+V(2))^0,
- [2]=left*V(1)*right
+ ((escape*(left+right))+(1-(left+right))+V(2))^0,
+ left*V(1)*right
}
local nestedbraces=P { lbrace*(nobrace+V(1))^0*rbrace }
local nestedparents=P { lparent*(noparent+V(1))^0*rparent }
@@ -9366,11 +9365,12 @@ local nestedbrackets=P { lbracket*(nobracket+V(1))^0*rbracket }
local spaces=space^0
local argument=Cs((lbrace/"")*((nobrace+nestedbraces)^0)*(rbrace/""))
local content=(1-endofstring)^0
-lpegpatterns.nestedbraces=nestedbraces
-lpegpatterns.nestedparents=nestedparents
-lpegpatterns.nested=nestedbraces
-lpegpatterns.argument=argument
-lpegpatterns.content=content
+lpegpatterns.nestedbraces=nestedbraces
+lpegpatterns.nestedparents=nestedparents
+lpegpatterns.nestedbrackets=nestedbrackets
+lpegpatterns.nested=nestedbraces
+lpegpatterns.argument=argument
+lpegpatterns.content=content
local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+(1-comma))^0)
local key=C((1-equal-comma)^1)
local pattern_a=(space+comma)^0*(key*equal*value+key*C(""))
@@ -9776,15 +9776,24 @@ local function ranger(first,last,n,action)
action(first)
end
end
-local cardinal=lpegpatterns.cardinal/tonumber
+local cardinal=(lpegpatterns.hexadecimal+lpegpatterns.cardinal)/tonumber
local spacers=lpegpatterns.spacer^0
local endofstring=lpegpatterns.endofstring
local stepper=spacers*(cardinal*(spacers*S(":-")*spacers*(cardinal+Cc(true) )+Cc(false) )*Carg(1)*Carg(2)/ranger*S(", ")^0 )^1
local stepper=spacers*(cardinal*(spacers*S(":-")*spacers*(cardinal+(P("*")+endofstring)*Cc(true) )+Cc(false) )*Carg(1)*Carg(2)/ranger*S(", ")^0 )^1*endofstring
function parsers.stepper(str,n,action)
+ local ts=type(str)
if type(n)=="function" then
- lpegmatch(stepper,str,1,false,n or print)
- else
+ if ts=="number" then
+ n(str)
+ elseif ts=="table" then
+ for i=1,#str do
+ n(str[i])
+ end
+ else
+ lpegmatch(stepper,str,1,false,n or print)
+ end
+ elseif ts=="string" then
lpegmatch(stepper,str,1,n,action or print)
end
end
@@ -9802,7 +9811,7 @@ local cache={}
local spaces=lpegpatterns.space^0
local dummy=function() end
setmetatableindex(cache,function(t,k)
- local separator=P(k)
+ local separator=S(k)
local value=(1-separator)^0
local pattern=spaces*C(value)*separator^0*Cp()
t[k]=pattern
@@ -9882,8 +9891,11 @@ local p_year=lpegpatterns.digit^4/tonumber
local pattern=Cf(Ct("")*(
(Cg(Cc("year")*p_year)*S("-/")*Cg(Cc("month")*cardinal)*S("-/")*Cg(Cc("day")*cardinal)
)+(Cg(Cc("day")*cardinal)*S("-/")*Cg(Cc("month")*cardinal)*S("-/")*Cg(Cc("year")*p_year)
+ )+(Cg(Cc("year")*p_year)*S("-/")*Cg(Cc("month")*cardinal)
+ )+(Cg(Cc("month")*cardinal)*S("-/")*Cg(Cc("year")*p_year)
)
- )*P(" ")*Cg(Cc("hour")*cardinal)*P(":")*Cg(Cc("min")*cardinal)*(P(":")*Cg(Cc("sec")*cardinal))^-1
+ )*(
+ P(" ")*Cg(Cc("hour")*cardinal)*P(":")*Cg(Cc("min")*cardinal)*(P(":")*Cg(Cc("sec")*cardinal))^-1+P(-1) )
,rawset)
lpegpatterns.splittime=pattern
function parsers.totime(str)
@@ -12809,7 +12821,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["trac-set"] = package.loaded["trac-set"] or true
--- original size: 13901, stripped down to: 9175
+-- original size: 14568, stripped down to: 9644
if not modules then modules={} end modules ['trac-set']={
version=1.001,
@@ -12952,6 +12964,9 @@ local function register_setter(t,what,...)
end
local s=fnc
fnc=function(value) set(t,s,value) end
+ elseif typ=="table" then
+ functions.values=fnc
+ fnc=nil
elseif typ~="function" then
fnc=nil
end
@@ -12996,35 +13011,42 @@ local function list_setter(t)
end
return user,system
end
-local function show_setter(t)
+local function show_setter(t,pattern)
local list=list_setter(t)
t.report()
for k=1,#list do
local name=list[k]
- local functions=t.data[name]
- if functions then
- local value=functions.value
- local default=functions.default
- local modules=#functions
- if default==nil then
- default="unset"
- elseif type(default)=="table" then
- default=concat(default,"|")
- else
- default=tostring(default)
+ if not pattern or find(name,pattern) then
+ local functions=t.data[name]
+ if functions then
+ local value=functions.value
+ local default=functions.default
+ local values=functions.values
+ local modules=#functions
+ if default==nil then
+ default="unset"
+ elseif type(default)=="table" then
+ default=concat(default,"|")
+ else
+ default=tostring(default)
+ end
+ if value==nil then
+ value="unset"
+ elseif type(value)=="table" then
+ value=concat(value,"|")
+ else
+ value=tostring(value)
+ end
+ t.report(name)
+ t.report(" modules : %i",modules)
+ t.report(" default : %s",default)
+ t.report(" value : %s",value)
+ if values then
+ local v={} for i=1,#values do v[i]=tostring(values[i]) end
+ t.report(" values : % t",v)
end
- if value==nil then
- value="unset"
- elseif type(value)=="table" then
- value=concat(value,"|")
- else
- value=tostring(value)
+ t.report()
end
- t.report(name)
- t.report(" modules : %i",modules)
- t.report(" default : %s",default)
- t.report(" value : %s",value)
- t.report()
end
end
end
@@ -13043,6 +13065,10 @@ local function setter_value(setter,name)
local d=setter.data[name]
return d and (d.value or d.default)
end
+local function setter_values(setter,name)
+ local d=setter.data[name]
+ return d and d.values
+end
local function new_setter(name)
local setter
setter={
@@ -13057,6 +13083,7 @@ local function new_setter(name)
show=function(...) show_setter (setter,...) end,
default=function(...) return setter_default (setter,...) end,
value=function(...) return setter_value (setter,...) end,
+ values=function(...) return setter_values (setter,...) end,
}
data[name]=setter
return setter
@@ -13128,7 +13155,7 @@ if environment then
end
if texconfig then
local function set(k,v)
- v=tonumber(v)
+ local v=tonumber(v)
if v then
texconfig[k]=v
end
@@ -14231,7 +14258,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["util-deb"] = package.loaded["util-deb"] or true
--- original size: 10136, stripped down to: 6832
+-- original size: 10593, stripped down to: 7102
if not modules then modules={} end modules ['util-deb']={
version=1.001,
@@ -14525,6 +14552,22 @@ local function showtraceback(rep)
end
end
debugger.showtraceback=showtraceback
+if luac then
+ local show,dump=luac.print,string.dump
+ function luac.inspect(v)
+ if type(v)=="function" then
+ local ok,str=xpcall(dump,function() end,v)
+ if ok then
+ v=str
+ end
+ end
+ if type(v)=="string" then
+ show(v,true)
+ else
+ print(v)
+ end
+ end
+end
end -- of closure
@@ -14686,7 +14729,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["util-sbx"] = package.loaded["util-sbx"] or true
--- original size: 21084, stripped down to: 13214
+-- original size: 21145, stripped down to: 13271
if not modules then modules={} end modules ['util-sbx']={
version=1.001,
@@ -14939,7 +14982,7 @@ local function validcommand(name,program,template,checkers,defaults,variables,re
if chktype=="verbose" then
else
local checker=validators[chktype]
- if checker then
+ if checker and type(value)=="string" then
value=checker(unquoted(value),strict)
if value then
variables[variable]=optionalquoted(value)
@@ -14958,7 +15001,7 @@ local function validcommand(name,program,template,checkers,defaults,variables,re
if not value or value=="" then
local chktype=checkers[variable]
if chktype=="verbose" then
- else
+ elseif type(default)=="string" then
local checker=validators[chktype]
if checker then
default=checker(unquoted(default),strict)
@@ -15759,7 +15802,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["util-zip"] = package.loaded["util-zip"] or true
--- original size: 19496, stripped down to: 10858
+-- original size: 23730, stripped down to: 14293
if not modules then modules={} end modules ['util-zip']={
version=1.001,
@@ -15768,12 +15811,20 @@ if not modules then modules={} end modules ['util-zip']={
license="see context related readme files"
}
local type,tostring,tonumber=type,tostring,tonumber
-local sort=table.sort
+local sort,concat=table.sort,table.concat
local find,format,sub,gsub=string.find,string.format,string.sub,string.gsub
local osdate,ostime,osclock=os.date,os.time,os.clock
local ioopen=io.open
local loaddata,savedata=io.loaddata,io.savedata
local filejoin,isdir,dirname,mkdirs=file.join,lfs.isdir,file.dirname,dir.mkdirs
+local suffix,suffixes=file.suffix,file.suffixes
+local openfile=io.open
+gzip=gzip or {}
+if not zlib then
+ zlib=xzip
+elseif not xzip then
+ xzip=zlib
+end
local files=utilities.files
local openfile=files.open
local closefile=files.close
@@ -15785,19 +15836,16 @@ local getposition=files.getposition
local band=bit32.band
local rshift=bit32.rshift
local lshift=bit32.lshift
-local decompress,expandsize,calculatecrc
- local zlibdecompress=zlib.decompress
- local zlibexpandsize=zlib.expandsize
- local zlibchecksum=zlib.crc32
- decompress=function(source)
- return zlibdecompress(source,-15)
- end
- expandsize=zlibexpandsize and function(source,targetsize)
- return zlibexpandsize(source,targetsize,-15)
- end or decompress
- calculatecrc=function(buffer,initial)
- return zlibchecksum(initial or 0,buffer)
- end
+local zlibdecompress=zlib.decompress
+local zlibdecompresssize=zlib.decompresssize
+local zlibchecksum=zlib.crc32
+if not CONTEXTLMTXMODE or CONTEXTLMTXMODE==0 then
+ local cs=zlibchecksum
+ zlibchecksum=function(str,n) return cs(n or 0,str) end
+end
+local decompress=function(source) return zlibdecompress (source,-15) end
+local decompresssize=function(source,targetsize) return zlibdecompresssize(source,targetsize,-15) end
+local calculatecrc=function(buffer,initial) return zlibchecksum (initial or 0,buffer) end
local zipfiles={}
utilities.zipfiles=zipfiles
local openzipfile,closezipfile,unzipfile,foundzipfile,getziphash,getziplist do
@@ -15922,8 +15970,8 @@ local openzipfile,closezipfile,unzipfile,foundzipfile,getziphash,getziplist do
setposition(handle,position)
local result=readstring(handle,compressed)
if data.method==8 then
- if expandsize then
- result=expandsize(result,data.uncompressed)
+ if decompresssize then
+ result=decompresssize(result,data.uncompressed)
else
result=decompress(result)
end
@@ -16187,7 +16235,127 @@ if xzip then
zipfiles.zipdir=zipdir
zipfiles.unzipdir=unzipdir
end
-zipfiles.gunzipfile=gzip.load
+local pattern="^\x1F\x8B\x08"
+local gziplevel=3
+function gzip.suffix(filename)
+ local suffix,extra=suffixes(filename)
+ local gzipped=extra=="gz"
+ return suffix,gzipped
+end
+function gzip.compressed(s)
+ return s and find(s,pattern)
+end
+local getdecompressed
+local putcompressed
+if gzip.compress then
+ local gzipwindow=15+16
+ local compress=zlib.compress
+ local decompress=zlib.decompress
+ getdecompressed=function(str)
+ return decompress(str,gzipwindow)
+ end
+ putcompressed=function(str,level)
+ return compress(str,level or gziplevel,nil,gzipwindow)
+ end
+else
+ local gzipwindow=-15
+ local identifier="\x1F\x8B"
+ local compress=zlib.compress
+ local decompress=zlib.decompress
+ local zlibchecksum=zlib.crc32
+ if not CONTEXTLMTXMODE or CONTEXTLMTXMODE==0 then
+ local cs=zlibchecksum
+ zlibchecksum=function(str,n) return cs(n or 0,str) end
+ end
+ local streams=utilities.streams
+ local openstream=streams.openstring
+ local closestream=streams.close
+ local getposition=streams.getposition
+ local readbyte=streams.readbyte
+ local readcardinal4=streams.readcardinal4le
+ local readcardinal2=streams.readcardinal2le
+ local readstring=streams.readstring
+ local readcstring=streams.readcstring
+ local skipbytes=streams.skip
+ local tocardinal1=streams.tocardinal1
+ local tocardinal4=streams.tocardinal4le
+ getdecompressed=function(str)
+ local s=openstream(str)
+ local identifier=readstring(s,2)
+ local method=readbyte(s,1)
+ local flags=readbyte(s,1)
+ local timestamp=readcardinal4(s)
+ local compression=readbyte(s,1)
+ local operating=readbyte(s,1)
+ local isjusttext=band(flags,0x01)~=0 and true or false
+ local extrasize=band(flags,0x04)~=0 and readcardinal2(s) or 0
+ local filename=band(flags,0x08)~=0 and readcstring(s) or ""
+ local comment=band(flags,0x10)~=0 and readcstring(s) or ""
+ local checksum=band(flags,0x02)~=0 and readcardinal2(s) or 0
+ local compressed=readstring(s,#str)
+ local data=decompress(compressed,gzipwindow)
+ return data
+ end
+ putcompressed=function(str,level,originalname)
+ return concat {
+ identifier,
+ tocardinal1(0x08),
+ tocardinal1(0x08),
+ tocardinal4(os.time()),
+ tocardinal1(0x02),
+ tocardinal1(0xFF),
+ (originalname or "unknownname").."\0",
+ compress(str,level,nil,gzipwindow),
+ tocardinal4(zlibchecksum(str)),
+ tocardinal4(#str),
+ }
+ end
+end
+function gzip.load(filename)
+ local f=openfile(filename,"rb")
+ if not f then
+ else
+ local data=f:read("*all")
+ f:close()
+ if data and data~="" then
+ if suffix(filename)=="gz" then
+ data=getdecompressed(data)
+ end
+ return data
+ end
+ end
+end
+function gzip.save(filename,data,level,originalname)
+ if suffix(filename)~="gz" then
+ filename=filename..".gz"
+ end
+ local f=openfile(filename,"wb")
+ if f then
+ data=putcompressed(data or "",level or gziplevel,originalname)
+ f:write(data)
+ f:close()
+ return #data
+ end
+end
+function gzip.compress(s,level)
+ if s and not find(s,pattern) then
+ if not level then
+ level=gziplevel
+ elseif level<=0 then
+ return s
+ elseif level>9 then
+ level=9
+ end
+ return putcompressed(s,level or gziplevel) or s
+ end
+end
+function gzip.decompress(s)
+ if s and find(s,pattern) then
+ return getdecompressed(s)
+ else
+ return s
+ end
+end
end -- of closure
@@ -16196,7 +16364,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["lxml-tab"] = package.loaded["lxml-tab"] or true
--- original size: 61808, stripped down to: 36227
+-- original size: 62810, stripped down to: 36225
if not modules then modules={} end modules ['lxml-tab']={
version=1.001,
@@ -16430,8 +16598,7 @@ end
local function add_text(text)
if text=="" then
return
- end
- if cleanup then
+ elseif cleanup then
if nt>0 then
local s=dt[nt]
if type(s)=="string" then
@@ -17001,7 +17168,7 @@ local function install(spacenewline,spacing,anything)
local attributes=(attribute+somespace^-1*(((anything-endofattributes)^1)/attribute_specification_error))^0
local parsedtext=text_parsed
local unparsedtext=text_unparsed/add_text
- local balanced=P { "["*((anything-S"[]")+V(1))^0*"]" }
+ local balanced=P { "["*((anything-S"[]")+V(1))^0*"]" }
local emptyelement=(spacing*open*name*attributes*optionalspace*slash*close)/add_empty
local beginelement=(spacing*open*name*attributes*optionalspace*close)/add_begin
local endelement=(spacing*open*slash*name*optionalspace*close)/add_end
@@ -17043,8 +17210,7 @@ local function install(spacenewline,spacing,anything)
local publicdoctype=doctypename*somespace*P("PUBLIC")*somespace*value*somespace*value*somespace*doctypeset
local systemdoctype=doctypename*somespace*P("SYSTEM")*somespace*value*somespace*doctypeset
local simpledoctype=(anything-close)^1
- local somedoctype=C((somespace*(
-publicentityfile+publicdoctype+systemdoctype+definitiondoctype+simpledoctype)*optionalspace)^0)
+ local somedoctype=C((somespace*(publicentityfile+publicdoctype+systemdoctype+definitiondoctype+simpledoctype)*optionalspace)^0)
local instruction=(spacing*begininstruction*someinstruction*endinstruction)/function(...) add_special("@pi@",...) end
local comment=(spacing*begincomment*somecomment*endcomment )/function(...) add_special("@cm@",...) end
local cdata=(spacing*begincdata*somecdata*endcdata )/function(...) add_special("@cd@",...) end
@@ -17654,7 +17820,7 @@ function xml.kind(e)
local tg=d.tg
if tg=="@cd@" then
return "cdata"
- elseif tg=="@cm" then
+ elseif tg=="@cm@" then
return "comment"
elseif tg=="@pi@" then
return "instruction"
@@ -17679,7 +17845,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["lxml-lpt"] = package.loaded["lxml-lpt"] or true
--- original size: 54667, stripped down to: 31258
+-- original size: 54733, stripped down to: 31258
if not modules then modules={} end modules ['lxml-lpt']={
version=1.001,
@@ -18999,7 +19165,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["lxml-aux"] = package.loaded["lxml-aux"] or true
--- original size: 33708, stripped down to: 20953
+-- original size: 34661, stripped down to: 21511
if not modules then modules={} end modules ['lxml-aux']={
version=1.001,
@@ -19265,6 +19431,36 @@ function xml.replace(root,pattern,whatever)
end
end
end
+function xml.expand(root,pattern,whatever)
+ local collected=root and xmlapplylpath(root,pattern)
+ if collected then
+ for c=1,#collected do
+ local e=collected[c]
+ local p=e.__p__
+ if p then
+ if trace_manipulations then
+ report('expanding',pattern,c,e)
+ end
+ local d=p.dt
+ local n=e.ni
+ local t=whatever(e,p)
+ if t then
+ if type(t)=="table" then
+ t=xmlcopy(t)
+ d[n]=t[1]
+ for i=2,#t do
+ n=n+1
+ insert(d,n,t[i])
+ end
+ else
+ d[n]=t
+ end
+ redo_ni(d)
+ end
+ end
+ end
+ end
+end
local function wrap(e,wrapper)
local t={
rn=e.rn,
@@ -21199,7 +21395,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["data-env"] = package.loaded["data-env"] or true
--- original size: 9501, stripped down to: 6411
+-- original size: 9501, stripped down to: 6413
if not modules then modules={} end modules ['data-env']={
version=1.001,
@@ -21291,8 +21487,8 @@ local relations=allocate {
names={ "mp" },
variable='MPINPUTS',
suffixes=CONTEXTLMTXMODE>0
- and { 'mp','mpxl','mpvi','mpiv','mpii' }
- or { 'mp','mpvi','mpiv','mpii' },
+ and { 'mpxl','mpvi','mpiv','mpii','mp' }
+ or { 'mpvi','mpiv','mpii','mp' },
usertype=true,
},
tex={
@@ -21486,7 +21682,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["data-tmp"] = package.loaded["data-tmp"] or true
--- original size: 16409, stripped down to: 11591
+-- original size: 16456, stripped down to: 11636
if not modules then modules={} end modules ['data-tmp']={
version=1.100,
@@ -21532,7 +21728,7 @@ local readables={}
local usedreadables={}
local compilelua=luautilities.compile
local luasuffixes=luautilities.suffixes
-caches.base=caches.base or "luatex-cache"
+caches.base=caches.base or (LUATEXENGINE and LUATEXENGINE.."-cache") or "luatex-cache"
caches.more=caches.more or "context"
caches.defaults={ "TMPDIR","TEMPDIR","TMP","TEMP","HOME","HOMEPATH" }
local direct_cache=false
@@ -23686,7 +23882,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["data-pre"] = package.loaded["data-pre"] or true
--- original size: 5088, stripped down to: 3144
+-- original size: 5872, stripped down to: 3691
if not modules then modules={} end modules ['data-pre']={
version=1.001,
@@ -23695,6 +23891,7 @@ if not modules then modules={} end modules ['data-pre']={
copyright="PRAGMA ADE / ConTeXt Development Team",
license="see context related readme files"
}
+local ipairs=ipairs
local insert,remove=table.insert,table.remove
local resolvers=resolvers
local prefixes=resolvers.prefixes
@@ -23706,6 +23903,7 @@ local basename=file.basename
local dirname=file.dirname
local joinpath=file.join
local isfile=lfs.isfile
+local isdir=lfs.isdir
prefixes.environment=function(str)
return cleanpath(expansion(str))
end
@@ -23766,6 +23964,30 @@ prefixes.home=function(str)
local pth=getenv('HOME')
return cleanpath(str and joinpath(pth,str) or pth)
end
+do
+ local tmppth
+ prefixes.temp=function(str)
+ if not tmppth then
+ for _,s in ipairs { "TMP","TEMP","TMPDIR","TEMPDIR" } do
+ tmppth=getenv(s)
+ if tmppth~="" and isdir(tmppth) then
+ break
+ end
+ end
+ if not tmppth or tmppth=="" then
+ tmppth="."
+ end
+ end
+ return cleanpath(str and joinpath(tmppth,str) or tmppth)
+ end
+ prefixes.texruns=function(str)
+ local pth=getenv('TEXRUNS')
+ if pth=="" then
+ pth=tmppth
+ end
+ return cleanpath(str and joinpath(pth,str) or pth)
+ end
+end
prefixes.env=prefixes.environment
prefixes.rel=prefixes.relative
prefixes.loc=prefixes.locate
@@ -23816,7 +24038,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["data-inp"] = package.loaded["data-inp"] or true
--- original size: 910, stripped down to: 818
+-- original size: 1050, stripped down to: 946
if not modules then modules={} end modules ['data-inp']={
version=1.001,
@@ -23832,12 +24054,15 @@ local registermethod=resolvers.registermethod
local finders=allocate { helpers={},notfound=function() end }
local openers=allocate { helpers={},notfound=function() end }
local loaders=allocate { helpers={},notfound=function() return false,nil,0 end }
+local tracers=allocate { helpers={},notfound=function() end }
registermethod("finders",finders,"uri")
registermethod("openers",openers,"uri")
registermethod("loaders",loaders,"uri")
+registermethod("tracers",tracers,"uri")
resolvers.finders=finders
resolvers.openers=openers
resolvers.loaders=loaders
+resolvers.tracers=tracers
end -- of closure
@@ -23846,7 +24071,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["data-out"] = package.loaded["data-out"] or true
--- original size: 551, stripped down to: 470
+-- original size: 682, stripped down to: 579
if not modules then modules={} end modules ['data-out']={
version=1.001,
@@ -23860,7 +24085,10 @@ local resolvers=resolvers
local registermethod=resolvers.registermethod
local savers=allocate { helpers={} }
resolvers.savers=savers
+local cleaners=allocate { helpers={} }
+resolvers.cleaners=cleaners
registermethod("savers",savers,"uri")
+registermethod("cleaners",cleaners,"uri")
end -- of closure
@@ -23998,7 +24226,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["data-con"] = package.loaded["data-con"] or true
--- original size: 5388, stripped down to: 3685
+-- original size: 5487, stripped down to: 3757
if not modules then modules={} end modules ['data-con']={
version=1.100,
@@ -24036,7 +24264,7 @@ local mt={
end,
__storage__=true
}
-function containers.define(category,subcategory,version,enabled)
+function containers.define(category,subcategory,version,enabled,reload)
if category and subcategory then
local c=allocated[category]
if not c then
@@ -24050,6 +24278,7 @@ function containers.define(category,subcategory,version,enabled)
subcategory=subcategory,
storage={},
enabled=enabled,
+ reload=reload,
version=version or math.pi,
trace=false,
}
@@ -24072,7 +24301,8 @@ function containers.is_valid(container,name)
end
function containers.read(container,name)
local storage=container.storage
- local stored=storage[name]
+ local reload=container.reload
+ local stored=not reload and storage[name]
if not stored and container.enabled and caches and containers.usecache then
stored=loaddatafromcache(container.readables,name,container.writable)
if stored and stored.cache_version==container.version then
@@ -24126,7 +24356,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["data-use"] = package.loaded["data-use"] or true
--- original size: 5785, stripped down to: 2905
+-- original size: 5806, stripped down to: 2925
if not modules then modules={} end modules ['data-use']={
version=1.001,
@@ -24156,14 +24386,14 @@ function statistics.savefmtstatus(texname,formatbanner,sourcefile,banner)
functionality=LUATEXFUNCTIONALITY,
}
io.savedata(luvname,table.serialize(luvdata,true))
- lua.registerfinalizer(function()
+ lua.registerinitexfinalizer(function()
if jit then
logs.report("format banner","%s lua: %s jit",banner,LUAVERSION)
else
logs.report("format banner","%s lua: %s",banner,LUAVERSION)
end
logs.newline()
- end)
+ end,"show banner")
end
end
function statistics.checkfmtstatus(texname)
@@ -24214,7 +24444,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["data-zip"] = package.loaded["data-zip"] or true
--- original size: 10725, stripped down to: 7949
+-- original size: 10805, stripped down to: 7951
if not modules then modules={} end modules ['data-zip']={
version=1.001,
@@ -24257,10 +24487,10 @@ if zipfiles then
local openstream=streams.open
local readstring=streams.readstring
local streamsize=streams.size
- local metatable={
+ local metatable={
close=streams.close,
read=function(stream,n)
- readstring(stream,n=="*a" and streamsize(stream) or n)
+ readstring(stream,n=="*a" and streamsize(stream) or n)
end
}
filehandle=function(zfile,queryname)
@@ -25287,7 +25517,7 @@ do -- create closure to overcome 200 locals limit
package.loaded["libs-ini"] = package.loaded["libs-ini"] or true
--- original size: 6459, stripped down to: 4006
+-- original size: 6524, stripped down to: 4064
if not modules then modules={} end modules ['libs-ini']={
version=1.001,
@@ -25329,10 +25559,10 @@ local function findlib(required)
for i=1,#list do
local name=list[i]
local found=findfile(name,"lib")
- if not found then
+ if not found or found=="" then
found=findfile(addsuffix(name,suffix),"lib")
end
- if found then
+ if found and found~="" then
if trace then
report("library %a resolved via %a path to %a",name,"tds lib",found)
end
@@ -25345,9 +25575,9 @@ local function findlib(required)
for i=1,#list do
local full=joinfile(list[i],base)
local found=isfile(full) and full
- if found then
+ if found and found~="" then
if trace then
- report("library %a resolved via %a path to %a",name,"system",found)
+ report("library %a resolved via %a path to %a",full,"system",found)
end
return found
end
@@ -25402,7 +25632,7 @@ function libraries.optionalloaded(name,libnames)
for i=1,#libnames do
local libname=libnames[i]
local filename=foundlibraries[libname]
- if filename then
+ if filename and filename~="" then
libnames[i]=filename
else
report("unable to locate library %a",libname)
@@ -25842,8 +26072,8 @@ end -- of closure
-- used libraries : l-bit32.lua l-lua.lua l-macro.lua l-sandbox.lua l-package.lua l-lpeg.lua l-function.lua l-string.lua l-table.lua l-io.lua l-number.lua l-set.lua l-os.lua l-file.lua l-gzip.lua l-md5.lua l-sha.lua l-url.lua l-dir.lua l-boolean.lua l-unicode.lua l-math.lua util-str.lua util-tab.lua util-fil.lua util-sac.lua util-sto.lua util-prs.lua util-fmt.lua util-soc-imp-reset.lua util-soc-imp-socket.lua util-soc-imp-copas.lua util-soc-imp-ltn12.lua util-soc-imp-mime.lua util-soc-imp-url.lua util-soc-imp-headers.lua util-soc-imp-tp.lua util-soc-imp-http.lua util-soc-imp-ftp.lua util-soc-imp-smtp.lua trac-set.lua trac-log.lua trac-inf.lua trac-pro.lua util-lua.lua util-deb.lua util-tpl.lua util-sbx.lua util-mrg.lua util-env.lua luat-env.lua util-zip.lua lxml-tab.lua lxml-lpt.lua lxml-mis.lua lxml-aux.lua lxml-xml.lua trac-xml.lua data-ini.lua data-exp.lua data-env.lua data-tmp.lua data-met.lua data-res.lua data-pre.lua data-inp.lua data-out.lua data-fil.lua data-con.lua data-use.lua data-zip.lua data-tre.lua data-sch.lua data-lua.lua data-aux.lua data-tmf.lua data-lst.lua libs-ini.lua luat-sta.lua luat-fmt.lua
-- skipped libraries : -
--- original bytes : 1025947
--- stripped bytes : 405652
+-- original bytes : 1034927
+-- stripped bytes : 407861
-- end library merge
@@ -27371,6 +27601,10 @@ end
if ok == false then ok = 1 elseif ok == true or ok == nil then ok = 0 end
+if lua and lua.getexitcode then
+ ok = lua.getexitcode()
+end
+
-- os.exit(ok,true) -- true forces a cleanup in 5.2+
os.exit(ok) -- true forces a cleanup in 5.2+ but reports a wrong number then
diff --git a/Master/texmf-dist/scripts/context/ruby/base/ctx.rb b/Master/texmf-dist/scripts/context/ruby/base/ctx.rb
deleted file mode 100644
index 13b4045afe0..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/ctx.rb
+++ /dev/null
@@ -1,462 +0,0 @@
-# module : base/ctx
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# todo: write systemcall for mpost to file so that it can be run
-# faster
-
-# report ?
-
-require 'base/system'
-require 'base/file'
-require 'base/switch' # has needsupdate, bad place
-
-require 'rexml/document'
-
-class CtxRunner
-
- attr_reader :environments, :modules, :filters, :flags, :modes
-
- @@suffix = 'prep'
-
- def initialize(jobname=nil,logger=nil)
- if @logger = logger then
- def report(str='')
- @logger.report(str)
- end
- else
- def report(str='')
- puts(str)
- end
- end
- @jobname = jobname
- @ctxname = nil
- @xmldata = nil
- @prepfiles = Hash.new
- @environments = Array.new
- @modules = Array.new
- @filters = Array.new
- @flags = Array.new
- @modes = Array.new
- @local = false
- @paths = Array.new
- end
-
- def register_path(str)
- @paths << str
- end
-
- def manipulate(ctxname=nil,defaultname=nil)
-
- if ctxname then
- @ctxname = ctxname
- @jobname = File.suffixed(@ctxname,'tex') unless @jobname
- else
- @ctxname = File.suffixed(@jobname,'ctx') if @jobname
- end
-
- if not @ctxname then
- report('no ctx file specified')
- return
- end
-
- if @ctxname !~ /\.[a-z]+$/ then
- @ctxname += ".ctx"
- end
-
- # name can be kpse:res-make.ctx
- if not FileTest.file?(@ctxname) then
- fullname, done = '', false
- if @ctxname =~ /^kpse:/ then
- begin
- if fullname = Kpse.found(@ctxname.sub(/^kpse:/,'')) then
- @ctxname, done = fullname, true
- end
- rescue
- # should not happen
- end
- else
- ['..','../..'].each do |path|
- begin
- fullname = File.join(path,@ctxname)
- if FileTest.file?(fullname) then
- @ctxname, done = fullname, true
- end
- rescue
- # probably strange join
- end
- break if done
- end
- if ! done then
- fullname = Kpse.found(@ctxname)
- if FileTest.file?(fullname) then
- @ctxname, done = fullname, true
- end
- end
- end
- if ! done && defaultname && FileTest.file?(defaultname) then
- report("using default ctxfile #{defaultname}")
- @ctxname, done = defaultname, true
- end
- if not done then
- report('no ctx file found')
- return false
- end
- end
-
- if FileTest.file?(@ctxname) then
- @xmldata = IO.read(@ctxname)
- else
- report('no ctx file found')
- return false
- end
-
- unless @xmldata =~ /^.*<\?xml.*?\?>/moi then
- report("ctx file #{@ctxname} is no xml file, skipping")
- return
- else
- report("loading ctx file #{@ctxname}")
- end
-
- if @xmldata then
- # out if a sudden rexml started to be picky about namespaces
- @xmldata.gsub!(/<ctx:job>/,"<ctx:job xmlns:ctx='http://www.pragma-ade.com/rng/ctx.rng'>")
- end
-
- begin
- @xmldata = REXML::Document.new(@xmldata)
- rescue
- report('provide valid ctx file (xml error)')
- return
- else
- include(@xmldata,'ctx:include','name')
- end
-
- begin
- variables = Hash.new
- if @jobname then
- variables['job'] = @jobname
- end
- root = @xmldata.root
- REXML::XPath.each(root,"/ctx:job//ctx:flags/ctx:flag") do |flg|
- @flags << justtext(flg)
- end
- REXML::XPath.each(root,"/ctx:job//ctx:resources/ctx:environment") do |sty|
- @environments << justtext(sty)
- end
- REXML::XPath.each(root,"/ctx:job//ctx:resources/ctx:module") do |mod|
- @modules << justtext(mod)
- end
- REXML::XPath.each(root,"/ctx:job//ctx:resources/ctx:filter") do |fil|
- @filters << justtext(fil)
- end
- REXML::XPath.each(root,"/ctx:job//ctx:resources/ctx:mode") do |fil|
- @modes << justtext(fil)
- end
- begin
- REXML::XPath.each(root,"//ctx:block") do |blk|
- if @jobname && blk.attributes['pattern'] then
- root.delete(blk) unless @jobname =~ /#{blk.attributes['pattern']}/
- else
- root.delete(blk)
- end
- end
- rescue
- end
- REXML::XPath.each(root,"//ctx:value[@name='job']") do |val|
- substititute(val,variables['job'])
- end
- REXML::XPath.each(root,"/ctx:job//ctx:message") do |mes|
- report("preprocessing: #{justtext(mes)}")
- end
- REXML::XPath.each(root,"/ctx:job//ctx:process/ctx:resources/ctx:environment") do |sty|
- @environments << justtext(sty)
- end
- REXML::XPath.each(root,"/ctx:job//ctx:process/ctx:resources/ctx:module") do |mod|
- @modules << justtext(mod)
- end
- REXML::XPath.each(root,"/ctx:job//ctx:process/ctx:resources/ctx:filter") do |fil|
- @filters << justtext(fil)
- end
- REXML::XPath.each(root,"/ctx:job//ctx:process/ctx:resources/ctx:mode") do |fil|
- @modes << justtext(fil)
- end
- REXML::XPath.each(root,"/ctx:job//ctx:process/ctx:flags/ctx:flag") do |flg|
- @flags << justtext(flg)
- end
- commands = Hash.new
- REXML::XPath.each(root,"/ctx:job//ctx:preprocess/ctx:processors/ctx:processor") do |pre|
- begin
- commands[pre.attributes['name']] = pre
- rescue
- end
- end
- suffix = @@suffix
- begin
- suffix = REXML::XPath.match(root,"/ctx:job//ctx:preprocess/@suffix").to_s
- rescue
- suffix = @@suffix
- else
- if suffix && suffix.empty? then suffix = @@suffix end
- end
- if (REXML::XPath.first(root,"/ctx:job//ctx:preprocess/ctx:processors/@local").to_s =~ /(yes|true)/io rescue false) then
- @local = true
- else
- @local = false
- end
- REXML::XPath.each(root,"/ctx:job//ctx:preprocess/ctx:files") do |files|
- REXML::XPath.each(files,"ctx:file") do |pattern|
- suffix = @@suffix
- begin
- suffix = REXML::XPath.match(root,"/ctx:job//ctx:preprocess/@suffix").to_s
- rescue
- suffix = @@suffix
- else
- if suffix && suffix.empty? then suffix = @@suffix end
- end
- preprocessor = pattern.attributes['processor']
- if preprocessor and not preprocessor.empty? then
- begin
- variables['old'] = @jobname
- variables['new'] = ""
- REXML::XPath.each(pattern,"ctx:value") do |value|
- if name = value.attributes['name'] then
- substititute(value,variables[name.to_s])
- end
- end
- rescue
- report('unable to resolve file pattern')
- return
- end
- pattern = justtext(pattern)
- oldfiles = Dir.glob(pattern)
- pluspath = false
- if oldfiles.length == 0 then
- report("no files match #{pattern}")
- if @paths.length > 0 then
- @paths.each do |p|
- oldfiles = Dir.glob("#{p}/#{pattern}")
- if oldfiles.length > 0 then
- pluspath = true
- break
- end
- end
- if oldfiles.length == 0 then
- report("no files match #{pattern} on path")
- end
- end
- end
- oldfiles.each do |oldfile|
- newfile = "#{oldfile}.#{suffix}"
- newfile = File.basename(newfile) if @local # or pluspath
- if File.expand_path(oldfile) != File.expand_path(newfile) && File.needsupdate(oldfile,newfile) then
- report("#{oldfile} needs preprocessing")
- begin
- File.delete(newfile)
- rescue
- # hope for the best
- end
- # there can be a sequence of processors
- preprocessor.split(',').each do |pp|
- if command = commands[pp] then
- # a lie: no <?xml ...?>
- command = REXML::Document.new(command.to_s) # don't infect original
- # command = command.deep_clone() # don't infect original
- command = command.elements["ctx:processor"]
- if suf = command.attributes['suffix'] then
- newfile = "#{oldfile}.#{suf}"
- end
- begin
- newfile = File.basename(newfile) if @local
- rescue
- end
- REXML::XPath.each(command,"ctx:old") do |value| replace(value,oldfile) end
- REXML::XPath.each(command,"ctx:new") do |value| replace(value,newfile) end
- report("preprocessing #{oldfile} into #{newfile} using #{pp}")
- variables['old'] = oldfile
- variables['new'] = newfile
- REXML::XPath.each(command,"ctx:value") do |value|
- if name = value.attributes['name'] then
- substititute(value,variables[name.to_s])
- end
- end
- command = justtext(command)
- report(command)
- unless ok = System.run(command) then
- report("error in preprocessing file #{oldfile}")
- end
- begin
- oldfile = File.basename(oldfile) if @local
- rescue
- end
- end
- end
- if FileTest.file?(newfile) then
- File.syncmtimes(oldfile,newfile)
- else
- report("check target location of #{newfile}")
- end
- else
- report("#{oldfile} needs no preprocessing (same file)")
- end
- @prepfiles[oldfile] = FileTest.file?(newfile)
- end
- end
- end
- end
- rescue
- report("fatal error in preprocessing #{@ctxname}: #{$!}")
- end
- end
-
- def savelog(ctlname=nil)
- unless ctlname then
- if @jobname then
- ctlname = File.suffixed(@jobname,'ctl')
- elsif @ctxname then
- ctlname = File.suffixed(@ctxname,'ctl')
- else
- return
- end
- end
- if @prepfiles.length > 0 then
- if log = File.open(ctlname,'w') then
- log << "<?xml version='1.0' standalone='yes'?>\n\n"
- if @local then
- log << "<ctx:preplist local='yes'>\n"
- else
- log << "<ctx:preplist local='no'>\n"
- end
- @prepfiles.keys.sort.each do |prep|
- # log << "\t<ctx:prepfile done='#{yes_or_no(@prepfiles[prep])}'>#{File.basename(prep)}</ctx:prepfile>\n"
- log << "\t<ctx:prepfile done='#{yes_or_no(@prepfiles[prep])}'>#{prep}</ctx:prepfile>\n"
- end
- log << "</ctx:preplist>\n"
- log.close
- end
- else
- begin
- File.delete(ctlname)
- rescue
- end
- end
- end
-
- private
-
- def include(xmldata,element='ctx:include',attribute='name')
- loop do
- begin
- more = false
- REXML::XPath.each(xmldata.root,element) do |e|
- begin
- name = e.attributes.get_attribute(attribute).to_s
- name = e.text.to_s if name.empty?
- name.strip! if name
- done = false
- if name and not name.empty? then
- ['.',File.dirname(@ctxname),'..','../..'].each do |path|
- begin
- fullname = if path == '.' then name else File.join(path,name) end
- if FileTest.file?(fullname) then
- if f = File.open(fullname,'r') and i = REXML::Document.new(f) then
- report("including ctx file #{name}")
- REXML::XPath.each(i.root,"*") do |ii|
- xmldata.root.insert_before(e,ii)
- more = true
- end
- end
- done = true
- end
- rescue
- end
- break if done
- end
- end
- report("no valid ctx inclusion file #{name}") unless done
- rescue Exception
- # skip this file
- ensure
- xmldata.root.delete(e)
- end
- end
- break unless more
- rescue Exception
- break # forget about inclusion
- end
- end
- end
-
- private
-
- def yes_or_no(b)
- if b then 'yes' else 'no' end
- end
-
- private # copied from rlxtools.rb
-
- def justtext(str)
- str = str.to_s
- str.gsub!(/<[^>]*?>/o, '')
- str.gsub!(/\s+/o, ' ')
- str.gsub!(/&lt;/o, '<')
- str.gsub!(/&gt;/o, '>')
- str.gsub!(/&amp;/o, '&')
- str.gsub!(/&quot;/o, '"')
- str.gsub!(/[\/\\]+/o, '/')
- return str.strip
- end
-
- def substititute(value,str)
- if str then
- begin
- if value.attributes.key?('method') then
- str = filtered(str.to_s,value.attributes['method'].to_s)
- end
- if str.empty? && value.attributes.key?('default') then
- str = value.attributes['default'].to_s
- end
- value.insert_after(value,REXML::Text.new(str.to_s))
- rescue Exception
- end
- end
- end
-
- def replace(value,str)
- if str then
- begin
- value.insert_after(value,REXML::Text.new(str.to_s))
- rescue Exception
- end
- end
- end
-
- def filtered(str,method)
- str = str.to_s # to be sure
- case method
- when 'name' then # no path, no suffix
- case str
- when /^.*[\\\/](.+?)\..*?$/o then $1
- when /^.*[\\\/](.+?)$/o then $1
- when /^(.*)\..*?$/o then $1
- else str
- end
- when 'path' then if str =~ /^(.+)([\\\/])(.*?)$/o then $1 else '' end
- when 'suffix' then if str =~ /^.*\.(.*?)$/o then $1 else '' end
- when 'nosuffix' then if str =~ /^(.*)\..*?$/o then $1 else str end
- when 'nopath' then if str =~ /^.*[\\\/](.*?)$/o then $1 else str end
- when 'base' then if str =~ /^.*[\\\/](.*?)$/o then $1 else str end
- when 'full' then str
- when 'complete' then str
- when 'expand' then File.expand_path(str).gsub(/\\/,"/")
- else str
- end
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/exa.rb b/Master/texmf-dist/scripts/context/ruby/base/exa.rb
deleted file mode 100644
index 7ba990cf900..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/exa.rb
+++ /dev/null
@@ -1,407 +0,0 @@
-# \setuplayout[width=3cm]
-#
-# tex.setup.setuplayout.width.[integer|real|dimension|string|key]
-# tex.[mp]var.whatever.width.[integer|real|dimension|string|key]
-
-require 'fileutils'
-# require 'ftools'
-require 'digest/md5'
-
-# this can become a lua thing
-
-# no .*? but 0-9a-z\:\. because other too slow (and greedy)
-
-class Hash
-
- def subset(pattern)
- h = Hash.new
- r = /^#{pattern.gsub('.','\.')}/
- self.keys.each do |k|
- h[k] = self[k].dup if k =~ r
- end
- return h
- end
-
-end
-
-module ExaEncrypt
-
- def ExaEncrypt.encrypt_base(logger, oldfilename, newfilename)
- if FileTest.file?(oldfilename) then
- logger.report("checking #{oldfilename}") if logger
- if data = IO.read(oldfilename) then
- done = false
- # cfg file:
- #
- # banner : exa configuration file
- # user : domain, name = password, projectlist
- #
- if data =~ /^\s*banner\s*\:\s*exa\s*configuration\s*file/ then
- data.gsub!(/^(\s*user\s*\:\s*.+?\s*\,\s*.+?\s*\=\s*)(.+?)(\s*\,\s*.+\s*)$/) do
- pre, password, post = $1, $2, $3
- unless password =~ /MD5:/i then
- done = true
- password = "MD5:" + Digest::MD5.hexdigest(password).upcase
- end
- "#{pre}#{password}#{post}"
- end
- else
- data.gsub!(/<exa:password([^>]*?)>(.*?)<\/exa:password>/moi) do
- attributes, password = $1, $2
- unless password =~ /^([0-9A-F][0-9A-F])+$/ then
- done = true
- password = Digest::MD5.hexdigest(password).upcase
- attributes = " encryption='md5'#{attributes}"
- end
- "<exa:password#{attributes}>#{password}</exa:password>"
- end
- end
- begin
- File.open(newfilename,'w') do |f|
- f.puts(data)
- end
- rescue
- logger.report("#{newfilename} cannot be written") if logger
- else
- logger.report("#{oldfilename} encrypted into #{newfilename}") if done and logger
- end
- end
- end
- end
-
-end
-
-module ExaModes
-
- @@modefile = 'examodes.tex'
-
- @@request = /(<exa:request.*?)(>.*?<\/exa:request>)/mo
- @@redone = /<exa:request[^>]*?texified=([\'\"])yes\1.*?>/mo
- @@reload = /<(exa:variable)([^>]+?label\=)([\"\'])([0-9A-Za-z\-\.\:]+?)(\3[^\/]*?)>(.*?)<(\/exa:variable)>/mo
- @@recalc = /<(exa:variable)([^>]+?label\=)([\"\'])([0-9A-Za-z\-\.\:]+?)([\.\:]calcmath)(\3[^\/]*?)>(.*?)<(\/exa:variable)>/mo
- @@rename = /<(exa:variable)([^>]+?label\=)([\"\'])([0-9A-Za-z\-\.\:]+?)(\3[^\/]*?)>(.*?)<(\/exa:variable)>/mo
- @@refile = /<(exa:filename|exa:filelist)>(.*?)<(\/\1)>/mo
-
- def ExaModes.cleanup_request(logger,filename='request.exa',modefile=@@modefile)
- begin File.delete(filename+'.raw') ; rescue ; end
- begin File.delete(modefile) ; rescue ; end
- if FileTest.file?(filename) then
- data, done = nil, false
- begin
- data = IO.read(filename)
- rescue
- data = nil
- end
- if data =~ @@request and data !~ @@redone then
- data.gsub!(@@rename) do
- done = true
- '<' + $1 + $2 + $3 + $4 + $5 + '>' +
- texifiedstr($4,$6) +
- '<' + $7 + '>'
- end
- data.gsub!(@@refile) do
- done = true
- '<' + $1 + '>' +
- cleanpath($2) +
- '<' + $3 + '>'
- end
- data.gsub!(@@recalc) do
- done = true
- '<' + $1 + $2 + $3 + $4 + ":raw" + $6 + '>' + $7 + '<' + $8 + '>' +
- '<' + $1 + $2 + $3 + $4 + $6 + '>' +
- calculatortexmath($7,false) +
- '<' + $8 + '>'
- end
- if done then
- data.gsub!(@@request) do
- $1 + " texified='yes'" + $2
- end
- begin File.copy(filename, filename+'.raw') ; rescue ; end
- begin
- logger.report("rewriting #{filename}") if logger
- File.open(filename,'w') do |f|
- f.puts(data)
- end
- rescue
- logger.report("#{filename} cannot be rewritten") if logger
- end
- end
- else
- logger.report("#{filename} is already ok") if logger
- end
- @variables = Hash.new
- data.scan(@@reload) do
- @variables[$4] = $5
- end
- vars = @variables.subset('data.tex.var')
- mpvars = @variables.subset('data.tex.mpvar')
- modes = @variables.subset('data.tex.mode')
- setups = @variables.subset('data.tex.setup')
- if not (modes.empty? and setups.empty? and vars.empty? and mpvars.empty?) then
- begin
- File.open(modefile,'w') do |mod|
- logger.report("saving modes and setups in #{modefile}") if logger
- if not modes.empty? then
- for key in modes.keys do
- k = key.dup
- k.gsub!(/\./,'-')
- mod.puts("\\enablemode[#{k}-#{modes[key]}]\n")
- if modes[key] =~ /(on|yes|start)/o then # ! ! ! ! !
- mod.puts("\\enablemode[#{k}]\n")
- end
- end
- mod.puts("\n\\readfile{cont-mod}{}{}\n")
- end
- if not setups.empty? then
- for key in setups.keys
- if key =~ /^(.+?)\.(.+?)\.(.+?)$/o then
- command, key, type, value = $1, $2, $3, setups[key]
- value = cleanedup(key,type,value)
- mod.puts("\\#{$1}[#{key}=#{value}]\n")
- elsif key =~ /^(.+?)\.(.+?)$/o then
- command, type, value = $1, $2, setups[key]
- mod.puts("\\#{$1}[#{value}]\n")
- end
- end
- end
- savevaroptions(vars, 'setvariables', mod)
- savevaroptions(mpvars,'setMPvariables',mod)
- end
- rescue
- logger.report("#{modefile} cannot be saved") if logger
- end
- else
- logger.report("#{modefile} is not created") if logger
- end
- end
- end
-
- private
-
- def ExaModes.autoparenthesis(str)
- if str =~ /[\+\-]/o then '[1]' + str + '[1]' else str end
- end
-
- def ExaModes.cleanedup(key,type,value)
- if type == 'dimension' then
- unless value =~ /(cm|mm|in|bp|sp|pt|dd|em|ex)/o
- value + 'pt'
- else
- value
- end
- elsif type == 'calcmath' then
- '{' + calculatortexmath(value,true) + '}'
- elsif type =~ /^filename|filelist$/ or key =~ /^filename|filelist$/ then
- cleanpath(value)
- else
- value
- end
- end
-
- def ExaModes.cleanpath(str)
- (str ||'').gsub(/\\/o,'/')
- end
-
- def ExaModes.texifiedstr(key,val)
- case key
- when 'filename' then
- cleanpath(val)
- when 'filelist' then
- cleanpath(val)
- else
- val
- end
- end
-
- def ExaModes.savevaroptions(vars,setvariables,mod)
- if not vars.empty? then
- for key in vars.keys do
- # var.whatever.width.dimension.value
- if key =~ /^(.+?)\.(.+?)\.(.+?)$/o then
- tag, key, type, value = $1, $2, $3, vars[key]
- value = cleanedup(key,type,value)
- mod.puts("\\#{setvariables}[#{tag}][#{key}=#{value}]\n")
- elsif key =~ /^(.+?)\.(.+?)$/o then
- tag, key, value = $1, $2, vars[key]
- mod.puts("\\#{setvariables}[#{tag}][#{key}=#{value}]\n")
- end
- end
- end
- end
-
- def ExaModes.calculatortexmath(str,tx=true)
- if tx then
- bdisp, edisp = "\\displaymath\{", "\}"
- binln, einln = "\\inlinemath\{" , "\}"
- egraf = "\\endgraf"
- else
- bdisp, edisp = "<displaytexmath>", "</displaytexmath>"
- binln, einln = "<inlinetexmath>" , "</inlinetexmath>"
- egraf = "<p/>"
- end
- str.gsub!(/\n\s*\n+/moi, "\\ENDGRAF ")
- str.gsub!(/(\[\[)\s*(.*?)\s*(\]\])/mos) do
- $1 + docalculatortexmath($2) + $3
- end
- str.gsub!(/(\\ENDGRAF)+\s*(\[\[)\s*(.*?)\s*(\]\])/moi) do
- $1 + bdisp + $3 + edisp
- end
- str.gsub!(/(\[\[)\s*(.*?)\s*(\]\])/o) do
- binln + $2 + einln
- end
- str.gsub!(/\\ENDGRAF/mos, egraf)
- str
- end
-
- def ExaModes.docalculatortexmath(str)
- str.gsub!(/\n/o) { ' ' }
- str.gsub!(/\s+/o) { ' ' }
- str.gsub!(/&gt;/o) { '>' }
- str.gsub!(/&lt;/o) { '<' }
- str.gsub!(/&.*?;/o) { }
- level = 0
- str.gsub!(/([\(\)])/o) do |chr|
- if chr == '(' then
- level = level + 1
- chr = '[' + level.to_s + ']'
- elsif chr == ')' then
- chr = '[' + level.to_s + ']'
- level = level - 1
- end
- chr
- end
- # ...E...
- loop do
- break unless str.gsub!(/([\d\.]+)E([\-\+]{0,1}[\d\.]+)/o) do
- "\{\\SCINOT\{#{$1}\}\{#{$2}\}\}"
- end
- end
- # ^-..
- loop do
- break unless str.gsub!(/\^([\-\+]*\d+)/o) do
- "\^\{#{$1}\}"
- end
- end
- # ^(...)
- loop do
- break unless str.gsub!(/\^(\[\d+\])(.*?)\1/o) do
- "\^\{#{$2}\}"
- end
- end
- # 1/x^2
- loop do
- break unless str.gsub!(/([\d\w\.]+)\/([\d\w\.]+)\^([\d\w\.]+)/o) do
- "@\{#{$1}\}\{#{$2}\^\{#{$3}\}\}"
- end
- end
- # int(a,b,c)
- loop do
- break unless str.gsub!(/(int|sum|prod)(\[\d+\])(.*?),(.*?),(.*?)\2/o) do
- "\\#{$1.upcase}\^\{#{$4}\}\_\{#{$5}\}\{#{autoparenthesis($3)}\}"
- end
- end
- # int(a,b)
- loop do
- break unless str.gsub!(/(int|sum|prod)(\[\d+\])(.*?),(.*?)\2/o) do
- "\\#{$1.upcase}\_\{#{$4}\}\{#{autoparenthesis($3)}\}"
- end
- end
- # int(a)
- loop do
- break unless str.gsub!(/(int|sum|prod)(\[\d+\])(.*?)\2/o) do
- "\\#{$1.upcase}\{#{autoparenthesis($3)}\}"
- end
- end
- # sin(x) => {\sin(x)}
- loop do
- break unless str.gsub!(/(median|min|max|round|sqrt|sin|cos|tan|sinh|cosh|tanh|ln|log)\s*(\[\d+\])(.*?)\2/o) do
- "\{\\#{$1.upcase}\{#{$2}#{$3}#{$2}\}\}"
- end
- end
- # mean
- str.gsub!(/(mean)(\[\d+\])(.*?)\2/o) do
- "\{\\OVERLINE\{#{$3}\}\}"
- end
- # sin x => {\sin(x)}
- # ...
- # (1+x)/(1+x) => \frac{1+x}{1+x}
- loop do
- break unless str.gsub!(/(\[\d+\])(.*?)\1\/(\[\d+\])(.*?)\3/o) do
- "@\{#{$2}\}\{#{$4}\}"
- end
- end
- # (1+x)/x => \frac{1+x}{x}
- loop do
- break unless str.gsub!(/(\[\d+\])(.*?)\1\/([a-zA-Z0-9]+)/o) do
- "@\{#{$2}\}\{#{$3}\}"
- end
- end
- # 1/(1+x) => \frac{1}{1+x}
- loop do
- break unless str.gsub!(/([a-zA-Z0-9]+)\/(\[\d+\])(.*?)\2/o) do
- "@\{#{$1}\}\{#{$3}\}"
- end
- end
- # 1/x => \frac{1}{x}
- loop do
- break unless str.gsub!(/([a-zA-Z0-9]+)\/([a-zA-Z0-9]+)/o) do
- "@\{#{$1}\}\{#{$2}\}"
- end
- end
- #
- str.gsub!(/\@/o) do
- "\\FRAC "
- end
- str.gsub!(/\*/o) do
- " "
- end
- str.gsub!(/\<\=/o) do
- "\\LE "
- end
- str.gsub!(/\>\=/o) do
- "\\GE "
- end
- str.gsub!(/\=/o) do
- "\\EQ "
- end
- str.gsub!(/\</o) do
- "\\LT "
- end
- str.gsub!(/\>/) do
- "\\GT "
- end
- str.gsub!(/(D)(\[\d+\])(.*?)\2/o) do
- "\{\\FRAC\{\\MBOX{d}\}\{\\MBOX{d}x\}\{#{$2}#{$3}#{$2}\}\}"
- end
- str.gsub!(/(exp)(\[\d+\])(.*?)\2/o) do
- "\{e^\{#{$3}\}\}"
- end
- str.gsub!(/(abs)(\[\d+\])(.*?)\2/o) do
- "\{\\left\|#{$3}\\right\|\}"
- end
- str.gsub!(/D([x|y])/o) do
- "\\FRAC\{\{\\rm d\}#{$1}\}\{\{\\rm d\}x\}"
- end
- str.gsub!(/D([f|g])(\[\d+\])(.*?)\2/o) do
- "\{\\rm #{$1}\}'#{$2}#{$3}#{$2}"
- end
- str.gsub!(/([f|g])(\[\d+\])(.*?)\2/o) do
- "\{\\rm #{$1}\}#{$2}#{$3}#{$2}"
- end
- str.gsub!(/(pi|inf)/io) do
- "\\#{$1} "
- end
- loop do
- break unless str.gsub!(/(\[\d+?\])(.*?)\1/o) do
- "\\left(#{$2}\\right)"
- end
- end
- str.gsub!(/\\([A-Z]+?)([\s\{\^\_\\])/io) do
- "\\#{$1.downcase}#{$2}"
- end
- str
- end
-
-end
-
-# ExaModes.cleanup_request()
diff --git a/Master/texmf-dist/scripts/context/ruby/base/file.rb b/Master/texmf-dist/scripts/context/ruby/base/file.rb
deleted file mode 100644
index 1aeac5fd697..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/file.rb
+++ /dev/null
@@ -1,150 +0,0 @@
-# module : base/file
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-require 'fileutils'
-# require 'ftools'
-
-class File
-
- def File.suffixed(name,sufa,sufb=nil)
- if sufb then
- if sufa.empty? then
- unsuffixed(name) + ".#{sufb}"
- else
- unsuffixed(name) + "-#{sufa}.#{sufb}"
- end
- else
- unsuffixed(name) + ".#{sufa}"
- end
- end
-
- def File.unsuffixed(name)
- name.sub(/\.[^\.]*?$/o, '')
- end
-
- def File.suffix(name,default='')
- if name =~ /\.([^\.]*?)$/o then
- $1
- else
- default
- end
- end
-
- def File.splitname(name,suffix='')
- if name =~ /^(.*)\.([^\.]*?)$/o then
- [$1, $2]
- else
- [name, suffix]
- end
- end
-
-end
-
-class File
-
- def File.silentopen(name,method='r')
- begin
- f = File.open(name,method)
- rescue
- return nil
- else
- return f
- end
- end
-
- def File.silentread(name)
- begin
- data = IO.read(name)
- rescue
- return nil
- else
- return data
- end
- end
-
- def File.atleast?(name,n=0)
- begin
- size = FileTest.size(name)
- rescue
- return false
- else
- return size > n
- end
- end
-
- def File.appended(name,str='')
- if FileTest.file?(name) then
- begin
- if f = File.open(name,'a') then
- f << str
- f.close
- return true
- end
- rescue
- end
- end
- return false
- end
-
- def File.written(name,str='')
- begin
- if f = File.open(name,'w') then
- f << str
- f.close
- return true
- end
- rescue
- end
- return false
- end
-
- def File.silentdelete(filename)
- File.delete(filename) rescue false
- end
-
- def File.silentcopy(oldname,newname)
- return if File.expand_path(oldname) == File.expand_path(newname)
- FileUtils.makedirs(File.dirname(newname)) rescue false
- File.copy(oldname,newname) rescue false
- end
-
- def File.silentrename(oldname,newname)
- # in case of troubles, we just copy the file; we
- # maybe working over multiple file systems or
- # apps may have mildly locked files (like gs does)
- return if File.expand_path(oldname) == File.expand_path(newname)
- File.delete(newname) rescue false
- begin
- File.rename(oldname,newname)
- rescue
- FileUtils.makedirs(File.dirname(newname)) rescue false
- File.copy(oldname,newname) rescue false
- end
- end
-
-end
-
-class File
-
- # handles "c:\tmp\test.tex" as well as "/${TEMP}/test.tex")
-
- def File.unixfied(filename)
- begin
- str = filename.gsub(/\$\{*([a-z0-9\_]+)\}*/oi) do
- if ENV.key?($1) then ENV[$1] else $1 end
- end
- str.gsub(/[\/\\]+/o, '/')
- rescue
- filename
- end
- end
-
-end
-
diff --git a/Master/texmf-dist/scripts/context/ruby/base/kpse.rb b/Master/texmf-dist/scripts/context/ruby/base/kpse.rb
deleted file mode 100644
index ec0b8810ba5..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/kpse.rb
+++ /dev/null
@@ -1,399 +0,0 @@
-# module : base/kpse
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# rename this one to environment
-#
-# todo: web2c vs miktex module and include in kpse
-
-require 'rbconfig'
-require 'fileutils'
-
-# beware $engine is lowercase in kpse
-#
-# miktex has mem|fmt|base paths
-
-class String
-
- def split_path
- if self =~ /\;/o || self =~ /^[a-z]\:/io then
- self.split(";")
- else
- self.split(":")
- end
- end
-
- def sane_path
- self.gsub(/\\/,'/')
- end
-
-end
-
-class Array
-
- def join_path
- self.join(File::PATH_SEPARATOR)
- end
-
- def non_empty
- self.delete_if do |i|
- (i == nil || i.empty?) rescue false
- end
- end
-
-end
-
-module Kpse
-
- @@located = Hash.new
- @@paths = Hash.new
- @@scripts = Hash.new
- @@formats = ['tex','texmfscripts','other text files']
- @@progname = 'context'
- @@ownpath = $0.sub(/[\\\/][a-z0-9\-]*?\.rb/i,'')
- @@problems = false
- @@tracing = false
- @@distribution = 'web2c'
- @@crossover = true
- @@mswindows = RbConfig::CONFIG['host_os'] =~ /mswin/
-
- # @@distribution = 'miktex' if ENV['PATH'] =~ /miktex[\\\/]bin/o
-
- # if ENV['PATH'] =~ /(.*?)miktex[\\\/]bin/i then
- # @@distribution = 'miktex' unless $1 =~ /(texmf\-mswin[\/\\]bin|bin[\/\\]win32)/i
- # end
-
- if @@mswindows && (ENV['PATH'] =~ /(.*?)miktex[\\\/]bin/i) then
- @@distribution = 'miktex' unless $1 =~ /(texmf\-mswin[\/\\]bin|bin[\/\\]win32)/i
- end
-
- @@re_true = /yes|on|true|1/i
-
- if (ENV['KPSEFAST'] =~ @@re_true) || (ENV['CTXMINIMAL'] =~ @@re_true) then
- @@usekpserunner = true
- require 'base/kpsefast'
- require 'base/kpserunner'
- else
- @@usekpserunner = false
- end
-
- if @@crossover then
- ENV.keys.each do |k|
- case k
- when /\_CTX\_KPSE\_V\_(.*?)\_/io then @@located[$1] = ENV[k].dup
- when /\_CTX\_KPSE\_P\_(.*?)\_/io then @@paths [$1] = ENV[k].dup.split(';')
- when /\_CTX\_KPSE\_S\_(.*?)\_/io then @@scripts[$1] = ENV[k].dup
- end
- end
- end
-
- def Kpse.distribution
- @@distribution
- end
-
- def Kpse.miktex?
- @@distribution == 'miktex'
- end
-
- def Kpse.web2c?
- @@distribution == 'web2c'
- end
-
- def Kpse.inspect
- @@located.keys.sort.each do |k| puts("located : #{k} -> #{@@located[k]}\n") end
- @@paths .keys.sort.each do |k| puts("paths : #{k} -> #{@@paths [k]}\n") end
- @@scripts.keys.sort.each do |k| puts("scripts : #{k} -> #{@@scripts[k]}\n") end
- end
-
- def Kpse.used_path(varname)
- begin
- if @@mswindows then
- path = run("--expand-path=\$#{varname}") rescue ''
- else
- path = run("--expand-path='$#{varname}'") rescue ''
- end
- rescue
- path = ''
- end
- return path.sane_path
- end
-
- def Kpse.found(filename, progname=nil, format=nil)
- begin
- tag = Kpse.key(filename) # all
- if @@located.key?(tag) then
- return @@located[tag].sane_path
- elsif FileTest.file?(filename) then
- setvariable(tag,filename)
- return filename
- elsif FileTest.file?(File.join(@@ownpath,filename)) then
- setvariable(tag,File.join(@@ownpath,filename))
- return @@located[tag].sane_path
- else
- [progname,@@progname].flatten.compact.uniq.each do |prg|
- [format,@@formats].flatten.compact.uniq.each do |fmt|
- begin
- tag = Kpse.key(filename,prg,fmt)
- if @@located.key?(tag) then
- return @@located[tag].sane_path
- elsif p = Kpse.kpsewhich(filename,prg,fmt) then
- setvariable(tag,p.chomp)
- return @@located[tag].sane_path
- end
- rescue
- end
- end
- end
- setvariable(tag,filename)
- return filename.sane_path
- end
- rescue
- filename.sane_path
- end
- end
-
- def Kpse.kpsewhich(filename,progname,format)
- p = if progname && ! progname.empty? then "-progname=#{progname}" else '' end
- f = if format && ! format.empty? then "-format=\"#{format}\"" else '' end
- Kpse.run("#{p} #{f} #{filename}")
- end
-
- def Kpse.which
- Kpse.kpsewhich
- end
-
- def Kpse.run(arguments)
- puts arguments if @@tracing
- begin
- if @@problems then
- results = ''
- elsif @@usekpserunner then
- results = KpseRunner.kpsewhich(arguments).chomp
- else
- results = `kpsewhich #{arguments}`.chomp
- end
- rescue
- puts "unable to run kpsewhich" if @@tracing
- @@problems, results = true, ''
- end
- puts results if @@tracing
- return results
- end
-
-
- def Kpse.formatpaths
- # maybe we should check for writeability
- unless @@paths.key?('formatpaths') then
- begin
- setpath('formatpaths',run("--show-path=fmt").sane_path.split_path)
- rescue
- setpath('formatpaths',[])
- end
- end
- return @@paths['formatpaths']
- end
-
- def Kpse.key(filename='',progname='all',format='all')
- [progname,format,filename].join('-')
- end
-
- def Kpse.formatpath(engine='pdftex',enginepath=true)
-
- # because engine support in distributions is not always
- # as we expect, we need to check for it;
-
- # todo: miktex
-
- if miktex? then
- return '.'
- else
- unless @@paths.key?(engine) then
- # savedengine = ENV['engine']
- if ENV['TEXFORMATS'] && ! ENV['TEXFORMATS'].empty? then
- # make sure that we have a lowercase entry
- ENV['TEXFORMATS'] = ENV['TEXFORMATS'].sub(/\$engine/io,"\$engine")
- # well, we will append anyway, so we could also strip it
- # ENV['TEXFORMATS'] = ENV['TEXFORMATS'].sub(/\$engine/io,"")
- end
- # use modern method
- if enginepath then
- formatpath = run("--engine=#{engine} --show-path=fmt")
- else
- # ENV['engine'] = engine if engine
- formatpath = run("--show-path=fmt")
- end
- # use ancient method
- if formatpath.empty? then
- if enginepath then
- if @@mswindows then
- formatpath = run("--engine=#{engine} --expand-path=\$TEXFORMATS")
- else
- formatpath = run("--engine=#{engine} --expand-path=\\\$TEXFORMATS")
- end
- end
- # either no enginepath or failed run
- if formatpath.empty? then
- if @@mswindows then
- formatpath = run("--expand-path=\$TEXFORMATS")
- else
- formatpath = run("--expand-path=\\\$TEXFORMATS")
- end
- end
- end
- # locate writable path
- if ! formatpath.empty? then
- formatpaths, done = formatpath.split_path, false
- formatpaths.collect! do |fp|
- fp.gsub!(/\\/o,'/')
- fp.gsub!(/\/\/$/o,'/')
- # remove funny patterns
- fp.sub!(/^!!/o,'')
- fp.sub!(/\/+$/o,'')
- fp.sub!(/(unsetengine|unset)/o,if enginepath then engine else '' end)
- fp
- end
- formatpaths.delete_if do |fp|
- fp.empty? || fp == '.'
- end
- # the engine path may not yet be present, find first writable
- formatpaths.each do |fp|
- # strip (possible engine) and test for writeability
- fpp = fp.sub(/#{engine}\/*$/o,'')
- if FileTest.directory?(fpp) && FileTest.writable?(fpp) then
- # use this path
- formatpath, done = fp.dup, true
- break
- end
- end
- unless done then
- formatpaths.each do |fp|
- fpp = fp.sub(/#{engine}\/*$/o,'')
- FileUtils.makedirs(fpp) rescue false # maybe we don't have an path yet
- if FileTest.directory?(fpp) && FileTest.writable?(fpp) then
- # use this path
- formatpath, done = fp.dup, true
- break
- end
- end
- end
- unless done then
- formatpath = '.'
- end
- end
- # needed !
- FileUtils.makedirs(formatpath) rescue false
- # fall back to current path
- formatpath = '.' if formatpath.empty? || ! FileTest.writable?(formatpath)
- # append engine but prevent duplicates
- formatpath = File.join(formatpath.sub(/\/*#{engine}\/*$/,''), engine) if enginepath
- FileUtils.makedirs(formatpath) rescue false
- setpath(engine,formatpath)
- # ENV['engine'] = savedengine
- end
- return @@paths[engine].first
- end
- end
-
- def Kpse.update
- system('initexmf -u') if Kpse.miktex?
- system('mktexlsr')
- end
-
- # engine support is either broken of not implemented in some
- # distributions, so we need to take care of it ourselves (without
- # delays due to kpse calls); there can be many paths in the string
- #
- # in a year or so, i will drop this check
-
- def Kpse.fixtexmfvars(engine=nil)
- ENV['ENGINE'] = engine if engine
- texformats = if ENV['TEXFORMATS'] then ENV['TEXFORMATS'].dup else '' end
- if texformats.empty? then
- if engine then
- if @@mswindows then
- texformats = `kpsewhich --engine=#{engine} --expand-var=\$TEXFORMATS`.chomp
- else
- texformats = `kpsewhich --engine=#{engine} --expand-var=\\\$TEXFORMATS`.chomp
- end
- else
- if @@mswindows then
- texformats = `kpsewhich --expand-var=\$TEXFORMATS`.chomp
- else
- texformats = `kpsewhich --expand-var=\\\$TEXFORMATS`.chomp
- end
- end
- end
- if engine then
- texformats.sub!(/unsetengine/,engine)
- else
- texformats.sub!(/unsetengine/,"\$engine")
- end
- if engine && (texformats =~ /web2c[\/\\].*#{engine}/o) then
- # ok, engine is seen
- return false
- elsif texformats =~ /web2c[\/\\].*\$engine/io then
- # shouldn't happen
- return false
- else
- ENV['TEXFORMATS'] = texformats.gsub(/(web2c\/\{)(,\})/o) do
- "#{$1}\$engine#{$2}"
- end
- if texformats !~ /web2c[\/\\].*\$engine/io then
- ENV['TEXFORMATS'] = texformats.gsub(/web2c\/*/, "web2c/{\$engine,}")
- end
- return true
- end
- end
-
- # def Kpse.runscript(name,filename=[],options=[])
- # setscript(name,`texmfstart --locate #{name}`) unless @@scripts.key?(name)
- # cmd = "#{@@scripts[name]} #{[options].flatten.join(' ')} #{[filename].flatten.join(' ')}"
- # system(cmd)
- # end
-
- # def Kpse.pipescript(name,filename=[],options=[])
- # setscript(name,`texmfstart --locate #{name}`) unless @@scripts.key?(name)
- # cmd = "#{@@scripts[name]} #{[options].flatten.join(' ')} #{[filename].flatten.join(' ')}"
- # `#{cmd}`
- # end
-
- def Kpse.runscript(name,filename=[],options=[])
- cmd = "mtxrun --script #{name} #{[options].flatten.join(' ')} #{[filename].flatten.join(' ')}"
- system(cmd)
- end
-
- def Kpse.pipescript(name,filename=[],options=[])
- cmd = "mtxrun --script #{name} #{[options].flatten.join(' ')} #{[filename].flatten.join(' ')}"
- `#{cmd}`
- end
-
- def Kpse.searchmethod
- if @@usekpserunner then 'kpsefast' else 'kpsewhich' end
- end
-
- private
-
- def Kpse.setvariable(key,value)
- @@located[key] = value
- ENV["_CTX_K_V_#{key}_"] = @@located[key] if @@crossover
- end
-
- def Kpse.setscript(key,value)
- @@scripts[key] = value
- ENV["_CTX_K_S_#{key}_"] = @@scripts[key] if @@crossover
- end
-
- def Kpse.setpath(key,value)
- @@paths[key] = [value].flatten.uniq.collect do |p|
- p.sub(/^!!/,'').sub(/\/*$/,'')
- end
- ENV["_CTX_K_P_#{key}_"] = @@paths[key].join(';') if @@crossover
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/kpse/drb.rb b/Master/texmf-dist/scripts/context/ruby/base/kpse/drb.rb
deleted file mode 100644
index db1ce0eec87..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/kpse/drb.rb
+++ /dev/null
@@ -1,57 +0,0 @@
-require 'drb'
-require 'base/kpse/trees'
-
-class KpseServer
-
- attr_accessor :port
-
- def initialize(port=7000)
- @port = port
- end
-
- def start
- puts "starting drb service at port #{@port}"
- DRb.start_service("druby://localhost:#{@port}", KpseTrees.new)
- trap(:INT) do
- DRb.stop_service
- end
- DRb.thread.join
- end
-
- def stop
- # todo
- end
-
-end
-
-class KpseClient
-
- attr_accessor :port
-
- def initialize(port=7000)
- @port = port
- @kpse = nil
- end
-
- def start
- # only needed when callbacks are used / slow, due to Socket::getaddrinfo
- # DRb.start_service
- end
-
- def object
- @kpse = DRbObject.new(nil,"druby://localhost:#{@port}")
- end
-
-end
-
-
-# SERVER_URI="druby://localhost:8787"
-#
-# # Start a local DRbServer to handle callbacks.
-# #
-# # Not necessary for this small example, but will be required
-# # as soon as we pass a non-marshallable object as an argument
-# # to a dRuby call.
-# DRb.start_service
-#
-# timeserver = DRbObject.new_with_uri(SERVER_URI)
diff --git a/Master/texmf-dist/scripts/context/ruby/base/kpse/soap.rb b/Master/texmf-dist/scripts/context/ruby/base/kpse/soap.rb
deleted file mode 100644
index c9ed75c446b..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/kpse/soap.rb
+++ /dev/null
@@ -1,79 +0,0 @@
-require 'soap/rpc/standaloneServer'
-require 'soap/rpc/driver'
-
-require 'base/kpse/trees'
-
-class KpseService < SOAP::RPC::StandaloneServer
-
- def on_init
- kpse = KpseTrees.new
- add_method(kpse, 'choose', 'files', 'environment')
- add_method(kpse, 'load', 'files', 'environment')
- add_method(kpse, 'expand_variables', 'tree')
- add_method(kpse, 'expand_braces', 'tree', 'str')
- add_method(kpse, 'expand_path', 'tree', 'str')
- add_method(kpse, 'expand_var', 'tree', 'str')
- add_method(kpse, 'show_path', 'tree', 'str')
- add_method(kpse, 'var_value', 'tree', 'str')
- add_method(kpse, 'find_file', 'tree', 'filename')
- add_method(kpse, 'find_files', 'tree', 'filename', 'first')
- end
-
-end
-
-class KpseServer
-
- @@url = 'http://kpse.thismachine.org/KpseService'
-
- attr_accessor :port
-
- def initialize(port=7000)
- @port = port
- @server = nil
- end
-
- def start
- puts "starting soap service at port #{@port}"
- @server = KpseService.new('KpseServer', @@url, '0.0.0.0', @port.to_i)
- trap(:INT) do
- @server.shutdown
- end
- status = @server.start
- end
-
- def stop
- @server.shutdown rescue false
- end
-
-end
-
-class KpseClient
-
- @@url = 'http://kpse.thismachine.org/KpseService'
-
- attr_accessor :port
-
- def initialize(port=7000)
- @port = port
- @kpse = nil
- end
-
- def start
- @kpse = SOAP::RPC::Driver.new("http://localhost:#{port}/", @@url)
- @kpse.add_method('choose','files', 'environment')
- @kpse.add_method('load','files', 'environment')
- @kpse.add_method('expand_variables', 'tree')
- @kpse.add_method('expand_braces', 'tree', 'str')
- @kpse.add_method('expand_path', 'tree', 'str')
- @kpse.add_method('expand_var', 'tree', 'str')
- @kpse.add_method('show_path', 'tree', 'str')
- @kpse.add_method('var_value', 'tree', 'str')
- @kpse.add_method('find_file', 'tree', 'filename')
- @kpse.add_method('find_files', 'tree', 'filename', 'first')
- end
-
- def object
- @kpse
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/kpse/trees.rb b/Master/texmf-dist/scripts/context/ruby/base/kpse/trees.rb
deleted file mode 100644
index 9c872eb18c1..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/kpse/trees.rb
+++ /dev/null
@@ -1,84 +0,0 @@
-require 'monitor'
-require 'base/kpsefast'
-
-class KpseTrees < Monitor
-
- def initialize
- @trees = Hash.new
- end
-
- def pattern(filenames)
- filenames.join('|').gsub(/\\+/o,'/').downcase
- end
-
- def choose(filenames,environment)
- current = pattern(filenames)
- load(filenames,environment) unless @trees[current]
- puts "enabling tree #{current}"
- current
- end
-
- def fetch(filenames,environment) # will send whole object !
- current = pattern(filenames)
- load(filenames,environment) unless @trees[current]
- puts "fetching tree #{current}"
- @trees[current]
- end
-
- def load(filenames,environment)
- current = pattern(filenames)
- puts "loading tree #{current}"
- @trees[current] = KpseFast.new
- @trees[current].push_environment(environment)
- @trees[current].load_cnf(filenames)
- @trees[current].expand_variables
- @trees[current].load_lsr
- end
-
- def set(tree,key,value)
- case key
- when 'progname' then @trees[tree].progname = value
- when 'engine' then @trees[tree].engine = value
- when 'format' then @trees[tree].format = value
- end
- end
- def get(tree,key)
- case key
- when 'progname' then @trees[tree].progname
- when 'engine' then @trees[tree].engine
- when 'format' then @trees[tree].format
- end
- end
-
- def load_cnf(tree)
- @trees[tree].load_cnf
- end
- def load_lsr(tree)
- @trees[tree].load_lsr
- end
- def expand_variables(tree)
- @trees[tree].expand_variables
- end
- def expand_braces(tree,str)
- @trees[tree].expand_braces(str)
- end
- def expand_path(tree,str)
- @trees[tree].expand_path(str)
- end
- def expand_var(tree,str)
- @trees[tree].expand_var(str)
- end
- def show_path(tree,str)
- @trees[tree].show_path(str)
- end
- def var_value(tree,str)
- @trees[tree].var_value(str)
- end
- def find_file(tree,filename)
- @trees[tree].find_file(filename)
- end
- def find_files(tree,filename,first)
- @trees[tree].find_files(filename,first)
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/kpsedirect.rb b/Master/texmf-dist/scripts/context/ruby/base/kpsedirect.rb
deleted file mode 100644
index 6fa8c8601a9..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/kpsedirect.rb
+++ /dev/null
@@ -1,34 +0,0 @@
-class KpseDirect
-
- attr_accessor :progname, :format, :engine
-
- def initialize
- @progname, @format, @engine = '', '', ''
- end
-
- def expand_path(str)
- clean_name(`kpsewhich -expand-path=#{str}`.chomp)
- end
-
- def expand_var(str)
- clean_name(`kpsewhich -expand-var=#{str}`.chomp)
- end
-
- def find_file(str)
- clean_name(`kpsewhich #{_progname_} #{_format_} #{str}`.chomp)
- end
-
- def _progname_
- if @progname.empty? then '' else "-progname=#{@progname}" end
- end
- def _format_
- if @format.empty? then '' else "-format=\"#{@format}\"" end
- end
-
- private
-
- def clean_name(str)
- str.gsub(/\\/,'/')
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/kpsefast.rb b/Master/texmf-dist/scripts/context/ruby/base/kpsefast.rb
deleted file mode 100644
index 8a9f895933b..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/kpsefast.rb
+++ /dev/null
@@ -1,934 +0,0 @@
-# module : base/kpsefast
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# todo: multiple cnf files
-#
-# todo: cleanup, string or table store (as in lua variant)
-
-class String
-
- def split_path
- if self =~ /\;/o || self =~ /^[a-z]\:/io then
- self.split(";")
- else
- self.split(":")
- end
- end
-
-end
-
-class Array
-
- def join_path
- self.join(File::PATH_SEPARATOR)
- end
-
-end
-
-class File
-
- def File.locate_file(path,name)
- begin
- files = Dir.entries(path)
- if files.include?(name) then
- fullname = File.join(path,name)
- return fullname if FileTest.file?(fullname)
- end
- files.each do |p|
- fullname = File.join(path,p)
- if p != '.' and p != '..' and FileTest.directory?(fullname) and result = locate_file(fullname,name) then
- return result
- end
- end
- rescue
- # bad path
- end
- return nil
- end
-
- def File.glob_file(pattern)
- return Dir.glob(pattern).first
- end
-
-end
-
-module KpseUtil
-
- # to be adapted, see loading cnf file
-
- @@texmftrees = ['texmf-local','texmf.local','../..','texmf'] # '../..' is for gwtex
- @@texmfcnf = 'texmf.cnf'
-
- def KpseUtil::identify
- # we mainly need to identify the local tex stuff and wse assume that
- # the texmfcnf variable is set; otherwise we need to expand the
- # TEXMF variable and that takes time since it may involve more
- ownpath = File.expand_path($0)
- if ownpath.gsub!(/texmf.*?$/o, '') then
- ENV['SELFAUTOPARENT'] = ownpath
- else
- ENV['SELFAUTOPARENT'] = '.' # fall back
- # may be too tricky:
- #
- # (ENV['PATH'] ||'').split_path.each do |p|
- # if p.gsub!(/texmf.*?$/o, '') then
- # ENV['SELFAUTOPARENT'] = p
- # break
- # end
- # end
- end
- filenames = Array.new
- if ENV['TEXMFCNF'] && ! ENV['TEXMFCNF'].empty? then
- ENV['TEXMFCNF'].to_s.split_path.each do |path|
- filenames << File.join(path,@@texmfcnf)
- end
- elsif ENV['SELFAUTOPARENT'] == '.' then
- filenames << File.join('.',@@texmfcnf)
- else
- @@texmftrees.each do |tree|
- filenames << File.join(ENV['SELFAUTOPARENT'],tree,'web2c',@@texmfcnf)
- end
- end
- loop do
- busy = false
- filenames.collect! do |f|
- f.gsub(/\$([a-zA-Z0-9\_\-]+)/o) do
- if (! ENV[$1]) || (ENV[$1] == $1) then
- "$#{$1}"
- else
- busy = true
- ENV[$1]
- end
- end
- end
- break unless busy
- end
- filenames.delete_if do |f|
- ! FileTest.file?(f)
- end
- return filenames
- end
-
- def KpseUtil::environment
- Hash.new.merge(ENV)
- end
-
-end
-
-class KpseFast
-
- # formats are an incredible inconsistent mess
-
- @@suffixes = Hash.new
- @@formats = Hash.new
- @@suffixmap = Hash.new
-
- @@texmfcnf = 'texmf.cnf'
-
- @@suffixes['gf'] = ['.<resolution>gf'] # todo
- @@suffixes['pk'] = ['.<resolution>pk'] # todo
- @@suffixes['tfm'] = ['.tfm']
- @@suffixes['afm'] = ['.afm']
- @@suffixes['base'] = ['.base']
- @@suffixes['bib'] = ['.bib']
- @@suffixes['bst'] = ['.bst']
- @@suffixes['cnf'] = ['.cnf']
- @@suffixes['ls-R'] = ['ls-R', 'ls-r']
- @@suffixes['fmt'] = ['.fmt', '.efmt', '.efm', '.ofmt', '.ofm', '.oft', '.eofmt', '.eoft', '.eof', '.pfmt', '.pfm', '.epfmt', '.epf', '.xpfmt', '.xpf', '.afmt', '.afm']
- @@suffixes['map'] = ['.map']
- @@suffixes['mem'] = ['.mem']
- @@suffixes['mf'] = ['.mf']
- @@suffixes['mfpool'] = ['.pool']
- @@suffixes['mft'] = ['.mft']
- @@suffixes['mp'] = ['.mp']
- @@suffixes['mppool'] = ['.pool']
- @@suffixes['ocp'] = ['.ocp']
- @@suffixes['ofm'] = ['.ofm', '.tfm']
- @@suffixes['opl'] = ['.opl']
- @@suffixes['otp'] = ['.otp']
- @@suffixes['ovf'] = ['.ovf']
- @@suffixes['ovp'] = ['.ovp']
- @@suffixes['graphic/figure'] = ['.eps', '.epsi']
- @@suffixes['tex'] = ['.tex']
- @@suffixes['texpool'] = ['.pool']
- @@suffixes['PostScript header'] = ['.pro']
- @@suffixes['type1 fonts'] = ['.pfa', '.pfb']
- @@suffixes['vf'] = ['.vf']
- @@suffixes['ist'] = ['.ist']
- @@suffixes['truetype fonts'] = ['.ttf', '.ttc']
- @@suffixes['web'] = ['.web', '.ch']
- @@suffixes['cweb'] = ['.w', '.web', '.ch']
- @@suffixes['enc files'] = ['.enc']
- @@suffixes['cmap files'] = ['.cmap']
- @@suffixes['subfont definition files'] = ['.sfd']
- @@suffixes['lig files'] = ['.lig']
- @@suffixes['bitmap font'] = []
- @@suffixes['MetaPost support'] = []
- @@suffixes['TeX system documentation'] = []
- @@suffixes['TeX system sources'] = []
- @@suffixes['Troff fonts'] = []
- @@suffixes['dvips config'] = []
- @@suffixes['type42 fonts'] = []
- @@suffixes['web2c files'] = []
- @@suffixes['other text files'] = []
- @@suffixes['other binary files'] = []
- @@suffixes['misc fonts'] = []
- @@suffixes['opentype fonts'] = []
- @@suffixes['pdftex config'] = []
- @@suffixes['texmfscripts'] = []
-
- # replacements
-
- @@suffixes['fmt'] = ['.fmt']
- @@suffixes['type1 fonts'] = ['.pfa', '.pfb', '.pfm']
- @@suffixes['tex'] = ['.tex', '.xml']
- @@suffixes['texmfscripts'] = ['rb','lua','py','pl']
-
- @@suffixes.keys.each do |k| @@suffixes[k].each do |s| @@suffixmap[s] = k end end
-
- # TTF2TFMINPUTS
- # MISCFONTS
- # TEXCONFIG
- # DVIPDFMINPUTS
- # OTFFONTS
-
- @@formats['gf'] = ''
- @@formats['pk'] = ''
- @@formats['tfm'] = 'TFMFONTS'
- @@formats['afm'] = 'AFMFONTS'
- @@formats['base'] = 'MFBASES'
- @@formats['bib'] = ''
- @@formats['bst'] = ''
- @@formats['cnf'] = ''
- @@formats['ls-R'] = ''
- @@formats['fmt'] = 'TEXFORMATS'
- @@formats['map'] = 'TEXFONTMAPS'
- @@formats['mem'] = 'MPMEMS'
- @@formats['mf'] = 'MFINPUTS'
- @@formats['mfpool'] = 'MFPOOL'
- @@formats['mft'] = ''
- @@formats['mp'] = 'MPINPUTS'
- @@formats['mppool'] = 'MPPOOL'
- @@formats['ocp'] = 'OCPINPUTS'
- @@formats['ofm'] = 'OFMFONTS'
- @@formats['opl'] = 'OPLFONTS'
- @@formats['otp'] = 'OTPINPUTS'
- @@formats['ovf'] = 'OVFFONTS'
- @@formats['ovp'] = 'OVPFONTS'
- @@formats['graphic/figure'] = ''
- @@formats['tex'] = 'TEXINPUTS'
- @@formats['texpool'] = 'TEXPOOL'
- @@formats['PostScript header'] = 'TEXPSHEADERS'
- @@formats['type1 fonts'] = 'T1FONTS'
- @@formats['vf'] = 'VFFONTS'
- @@formats['ist'] = ''
- @@formats['truetype fonts'] = 'TTFONTS'
- @@formats['web'] = ''
- @@formats['cweb'] = ''
- @@formats['enc files'] = 'ENCFONTS'
- @@formats['cmap files'] = 'CMAPFONTS'
- @@formats['subfont definition files'] = 'SFDFONTS'
- @@formats['lig files'] = 'LIGFONTS'
- @@formats['bitmap font'] = ''
- @@formats['MetaPost support'] = ''
- @@formats['TeX system documentation'] = ''
- @@formats['TeX system sources'] = ''
- @@formats['Troff fonts'] = ''
- @@formats['dvips config'] = ''
- @@formats['type42 fonts'] = 'T42FONTS'
- @@formats['web2c files'] = 'WEB2C'
- @@formats['other text files'] = ''
- @@formats['other binary files'] = ''
- @@formats['misc fonts'] = ''
- @@formats['opentype fonts'] = 'OPENTYPEFONTS'
- @@formats['pdftex config'] = 'PDFTEXCONFIG'
- @@formats['texmfscripts'] = 'TEXMFSCRIPTS'
-
- attr_accessor :progname, :engine, :format, :rootpath, :treepath,
- :verbose, :remember, :scandisk, :diskcache, :renewcache
-
- @@cacheversion = '1'
-
- def initialize
- @rootpath = ''
- @treepath = ''
- @progname = 'kpsewhich'
- @engine = 'pdftex'
- @variables = Hash.new
- @expansions = Hash.new
- @files = Hash.new
- @found = Hash.new
- @kpsevars = Hash.new
- @lsrfiles = Array.new
- @cnffiles = Array.new
- @verbose = true
- @remember = true
- @scandisk = true
- @diskcache = true
- @renewcache = false
- @isolate = false
-
- @diskcache = false
- @cachepath = nil
- @cachefile = 'tmftools.log'
-
- @environment = ENV
- end
-
- def set(key,value)
- case key
- when 'progname' then @progname = value
- when 'engine' then @engine = value
- when 'format' then @format = value
- end
- end
-
- def push_environment(env)
- @environment = env
- end
-
- # {$SELFAUTOLOC,$SELFAUTODIR,$SELFAUTOPARENT}{,{/share,}/texmf{-local,}/web2c}
- #
- # $SELFAUTOLOC : /usr/tex/bin/platform
- # $SELFAUTODIR : /usr/tex/bin
- # $SELFAUTOPARENT : /usr/tex
- #
- # since we live in scriptpath we need a slightly different method
-
- def load_cnf(filenames=nil)
- unless filenames then
- ownpath = File.expand_path($0)
- if ownpath.gsub!(/texmf.*?$/o, '') then
- @environment['SELFAUTOPARENT'] = ownpath
- else
- @environment['SELFAUTOPARENT'] = '.'
- end
- unless @treepath.empty? then
- unless @rootpath.empty? then
- @treepath = @treepath.split(',').collect do |p| File.join(@rootpath,p) end.join(',')
- end
- @environment['TEXMF'] = @treepath
- # only the first one
- @environment['TEXMFCNF'] = File.join(@treepath.split(',').first,'texmf/web2c')
- end
- unless @rootpath.empty? then
- @environment['TEXMFCNF'] = File.join(@rootpath,'texmf/web2c')
- @environment['SELFAUTOPARENT'] = @rootpath
- @isolate = true
- end
- filenames = Array.new
- if @environment['TEXMFCNF'] and not @environment['TEXMFCNF'].empty? then
- @environment['TEXMFCNF'].to_s.split_path.each do |path|
- filenames << File.join(path,@@texmfcnf)
- end
- elsif @environment['SELFAUTOPARENT'] == '.' then
- filenames << File.join('.',@@texmfcnf)
- else
- ['texmf-local','texmf'].each do |tree|
- filenames << File.join(@environment['SELFAUTOPARENT'],tree,'web2c',@@texmfcnf)
- end
- end
- end
- # <root>/texmf/web2c/texmf.cnf
- filenames = _expanded_path_(filenames)
- @rootpath = filenames.first
- 3.times do
- @rootpath = File.dirname(@rootpath)
- end
- filenames.collect! do |f|
- f.gsub("\\", '/')
- end
- filenames.each do |fname|
- if FileTest.file?(fname) and f = File.open(fname) then
- @cnffiles << fname
- while line = f.gets do
- loop do
- # concatenate lines ending with \
- break unless line.sub!(/\\\s*$/o) do
- f.gets || ''
- end
- end
- case line
- when /^[\%\#]/o then
- # comment
- when /^\s*(.*?)\s*\=\s*(.*?)\s*$/o then
- key, value = $1, $2
- unless @variables.key?(key) then
- value.sub!(/\%.*$/,'')
- value.sub!(/\~/, "$HOME")
- @variables[key] = value
- end
- @kpsevars[key] = true
- end
- end
- f.close
- end
- end
- end
-
- def load_lsr
- @lsrfiles = []
- simplified_list(expansion('TEXMF')).each do |p|
- ['ls-R','ls-r'].each do |f|
- filename = File.join(p,f)
- if FileTest.file?(filename) then
- @lsrfiles << [filename,File.size(filename)]
- break
- end
- end
- end
- @files = Hash.new
- if @diskcache then
- ['HOME','TEMP','TMP','TMPDIR'].each do |key|
- if @environment[key] then
- if FileTest.directory?(@environment[key]) then
- @cachepath = @environment[key]
- @cachefile = [@rootpath.gsub(/[^A-Z0-9]/io, '-').gsub(/\-+/,'-'),File.basename(@cachefile)].join('-')
- break
- end
- end
- end
- if @cachepath and not @renewcache and FileTest.file?(File.join(@cachepath,@cachefile)) then
- begin
- if f = File.open(File.join(@cachepath,@cachefile)) then
- cacheversion = Marshal.load(f)
- if cacheversion == @@cacheversion then
- lsrfiles = Marshal.load(f)
- if lsrfiles == @lsrfiles then
- @files = Marshal.load(f)
- end
- end
- f.close
- end
- rescue
- @files = Hash.new
- end
- end
- end
- return if @files.size > 0
- @lsrfiles.each do |filedata|
- filename, filesize = filedata
- filepath = File.dirname(filename)
- begin
- path = '.'
- data = IO.readlines(filename)
- if data[0].chomp =~ /% ls\-R \-\- filename database for kpathsea\; do not change this line\./io then
- data.each do |line|
- case line
- when /^[a-zA-Z0-9]/o then
- line.chomp!
- if @files[line] then
- @files[line] << path
- else
- @files[line] = [path]
- end
- when /^\.\/(.*?)\:$/o then
- path = File.join(filepath,$1)
- end
- end
- end
- rescue
- # sorry
- end
- end
- if @diskcache and @cachepath and f = File.open(File.join(@cachepath,@cachefile),'wb') then
- f << Marshal.dump(@@cacheversion)
- f << Marshal.dump(@lsrfiles)
- f << Marshal.dump(@files)
- f.close
- end
- end
-
- def expand_variables
- @expansions = Hash.new
- if @isolate then
- @variables['TEXMFCNF'] = @environment['TEXMFCNF'].dup
- @variables['SELFAUTOPARENT'] = @environment['SELFAUTOPARENT'].dup
- else
- @environment.keys.each do |e|
- if e =~ /^([a-zA-Z]+)\_(.*)\s*$/o then
- @expansions["#{$1}.#{$2}"] = (@environment[e] ||'').dup
- else
- @expansions[e] = (@environment[e] ||'').dup
- end
- end
- end
- @variables.keys.each do |k|
- @expansions[k] = @variables[k].dup unless @expansions[k]
- end
- loop do
- busy = false
- @expansions.keys.each do |k|
- @expansions[k].gsub!(/\$([a-zA-Z0-9\_\-]*)/o) do
- busy = true
- @expansions[$1] || ''
- end
- @expansions[k].gsub!(/\$\{([a-zA-Z0-9\_\-]*)\}/o) do
- busy = true
- @expansions[$1] || ''
- end
- end
- break unless busy
- end
- @expansions.keys.each do |k|
- @expansions[k] = @expansions[k].gsub("\\", '/')
- end
- end
-
- def variable(name='')
- (name and not name.empty? and @variables[name.sub('$','')]) or ''
- end
-
- def expansion(name='')
- (name and not name.empty? and @expansions[name.sub('$','')]) or ''
- end
-
- def variable?(name='')
- name and not name.empty? and @variables.key?(name.sub('$',''))
- end
-
- def expansion?(name='')
- name and not name.empty? and @expansions.key?(name.sub('$',''))
- end
-
- def simplified_list(str)
- lst = str.gsub(/^\{/o,'').gsub(/\}$/o,'').split(",")
- lst.collect do |l|
- l.sub(/^[\!]*/,'').sub(/[\/\\]*$/o,'')
- end
- end
-
- def original_variable(variable)
- if variable?("#{@progname}.#{variable}") then
- variable("#{@progname}.#{variable}")
- elsif variable?(variable) then
- variable(variable)
- else
- ''
- end
- end
-
- def expanded_variable(variable)
- if expansion?("#{variable}.#{@progname}") then
- expansion("#{variable}.#{@progname}")
- elsif expansion?(variable) then
- expansion(variable)
- else
- ''
- end
- end
-
- def original_path(filename='')
- _expanded_path_(original_variable(var_of_format_or_suffix(filename)).split(";"))
- end
-
- def expanded_path(filename='')
- _expanded_path_(expanded_variable(var_of_format_or_suffix(filename)).split(";"))
- end
-
- def _expanded_path_(pathlist)
- i, n = 0, 0
- pathlist.collect! do |mainpath|
- mainpath.gsub(/([\{\}])/o) do
- if $1 == "{" then
- i += 1 ; n = i if i > n ; "<#{i}>"
- else
- i -= 1 ; "</#{i+1}>"
- end
- end
- end
- n.times do |i|
- loop do
- more = false
- newlist = []
- pathlist.each do |path|
- unless path.sub!(/^(.*?)<(#{n-i})>(.*?)<\/\2>(.*?)$/) do
- pre, mid, post = $1, $3, $4
- mid.gsub!(/\,$/,',.')
- mid.split(',').each do |m|
- more = true
- if m == '.' then
- newlist << "#{pre}#{post}"
- else
- newlist << "#{pre}#{m}#{post}"
- end
- end
- end then
- newlist << path
- end
- end
- if more then
- pathlist = [newlist].flatten # copy -)
- else
- break
- end
- end
- end
- pathlist = pathlist.uniq.collect do |path|
- p = path
- # p.gsub(/^\/+/o) do '' end
- # p.gsub!(/(.)\/\/(.)/o) do "#{$1}/#{$2}" end
- # p.gsub!(/\/\/+$/o) do '//' end
- p.gsub!(/\/\/+/o) do '//' end
- p
- end
- pathlist
- end
-
- # todo: ignore case
-
- def var_of_format(str)
- @@formats[str] || ''
- end
-
- def var_of_suffix(str) # includes .
- if @@suffixmap.key?(str) then @@formats[@@suffixmap[str]] else '' end
- end
-
- def var_of_format_or_suffix(str)
- if @@formats.key?(str) then
- @@formats[str]
- elsif @@suffixmap.key?(File.extname(str)) then # extname includes .
- @@formats[@@suffixmap[File.extname(str)]] # extname includes .
- else
- ''
- end
- end
-
-end
-
-class KpseFast
-
- # test things
-
- def list_variables(kpseonly=true)
- @variables.keys.sort.each do |k|
- if kpseonly then
- puts("#{k} = #{@variables[k]}") if @kpsevars[k]
- else
- puts("#{if @kpsevars[k] then 'K' else 'E' end} #{k} = #{@variables[k]}")
- end
- end
- end
-
- def list_expansions(kpseonly=true)
- @expansions.keys.sort.each do |k|
- if kpseonly then
- puts("#{k} = #{@expansions[k]}") if @kpsevars[k]
- else
- puts("#{if @kpsevars[k] then 'K' else 'E' end} #{k} = #{@expansions[k]}")
- end
- end
- end
-
- def list_lsr
- puts("files = #{@files.size}")
- end
-
- def set_test_patterns
- @variables["KPSE_TEST_PATTERN_A"] = "foo/{1,2}/bar//"
- @variables["KPSE_TEST_PATTERN_B"] = "!!x{A,B{1,2}}y"
- @variables["KPSE_TEST_PATTERN_C"] = "x{A,B//{1,2}}y"
- @variables["KPSE_TEST_PATTERN_D"] = "x{A,B//{1,2,}}//y"
- end
-
- def show_test_patterns
- ['A','B','D'].each do |i|
- puts ""
- puts @variables ["KPSE_TEST_PATTERN_#{i}"]
- puts ""
- puts expand_path("KPSE_TEST_PATTERN_#{i}").split_path
- puts ""
- end
- end
-
-end
-
-class KpseFast
-
- # kpse stuff
-
- def expand_braces(str) # output variable and brace expansion of STRING.
- _expanded_path_(original_variable(str).split_path).join_path
- end
-
- def expand_path(str) # output complete path expansion of STRING.
- _expanded_path_(expanded_variable(str).split_path).join_path
- end
-
- def expand_var(str) # output variable expansion of STRING.
- expanded_variable(str)
- end
-
- def show_path(str) # output search path for file type NAME
- expanded_path(str).join_path
- end
-
- def var_value(str) # output the value of variable $STRING.
- original_variable(str)
- end
-
-end
-
-class KpseFast
-
- def _is_cnf_?(filename)
- filename == File.basename((@cnffiles.first rescue @@texmfcnf) || @@texmfcnf)
- end
-
- def find_file(filename)
- if _is_cnf_?(filename) then
- @cnffiles.first rescue ''
- else
- [find_files(filename,true)].flatten.first || ''
- end
- end
-
- def find_files(filename,first=false)
- if _is_cnf_?(filename) then
- result = @cnffiles.dup
- else
- if @remember then
- # stamp = "#{filename}--#{@format}--#{@engine}--#{@progname}"
- stamp = "#{filename}--#{@engine}--#{@progname}"
- return @found[stamp] if @found.key?(stamp)
- end
- pathlist = expanded_path(filename)
- result = []
- filelist = if @files.key?(filename) then @files[filename].uniq else nil end
- done = false
- if pathlist.size == 0 then
- if FileTest.file?(filename) then
- done = true
- result << '.'
- end
- else
- pathlist.each do |path|
- doscan = if path =~ /^\!\!/o then false else true end
- recurse = if path =~ /\/\/$/o then true else false end
- pathname = path.dup
- pathname.gsub!(/^\!+/o, '')
- done = false
- if not done and filelist then
- # checking for exact match
- if filelist.include?(pathname) then
- result << pathname
- done = true
- end
- if not done and recurse then
- # checking for fuzzy //
- pathname.gsub!(/\/+$/o, '/.*')
- # pathname.gsub!(/\/\//o,'/[\/]*/')
- pathname.gsub!(/\/\//o,'/.*?/')
- re = /^#{pathname}/
- filelist.each do |f|
- if re =~ f then
- result << f # duplicates will be filtered later
- done = true
- end
- break if done
- end
- end
- end
- if not done and doscan then
- # checking for path itself
- pname = pathname.sub(/\.\*$/,'')
- if not pname =~ /\*/o and FileTest.file?(File.join(pname,filename)) then
- result << pname
- done = true
- end
- end
- break if done and first
- end
- end
- if not done and @scandisk then
- pathlist.each do |path|
- pathname = path.dup
- unless pathname.gsub!(/^\!+/o, '') then # !! prevents scan
- recurse = pathname.gsub!(/\/+$/o, '')
- complex = pathname.gsub!(/\/\//o,'/*/')
- if recurse then
- if complex then
- if ok = File.glob_file("#{pathname}/**/#{filename}") then
- result << File.dirname(ok)
- done = true
- end
- elsif ok = File.locate_file(pathname,filename) then
- result << File.dirname(ok)
- done = true
- end
- elsif complex then
- if ok = File.glob_file("#{pathname}/#{filename}") then
- result << File.dirname(ok)
- done = true
- end
- elsif FileTest.file?(File.join(pathname,filename)) then
- result << pathname
- done = true
- end
- break if done and first
- end
- end
- end
- result = result.uniq.collect do |pathname|
- File.join(pathname,filename)
- end
- @found[stamp] = result if @remember
- end
- return result # redundant
- end
-
-end
-
-class KpseFast
-
- class FileData
- attr_accessor :tag, :name, :size, :date
- def initialize(tag=0,name=nil,size=nil,date=nil)
- @tag, @name, @size, @date = tag, name, size, date
- end
- def FileData.sizes(a)
- a.collect do |aa|
- aa.size
- end
- end
- def report
- case @tag
- when 1 then "deleted | #{@size.to_s.rjust(8)} | #{@date.strftime('%m/%d/%Y %I:%M')} | #{@name}"
- when 2 then "present | #{@size.to_s.rjust(8)} | #{@date.strftime('%m/%d/%Y %I:%M')} | #{@name}"
- when 3 then "obsolete | #{' '*8} | #{' '*16} | #{@name}"
- end
- end
- end
-
- def analyze_files(filter='',strict=false,sort='',delete=false)
- puts("command line = #{ARGV.join(' ')}")
- puts("number of files = #{@files.size}")
- puts("filter pattern = #{filter}")
- puts("loaded cnf files = #{@cnffiles.join(' ')}")
- puts('')
- if filter.gsub!(/^not:/,'') then
- def the_same(filter,filename)
- not filter or filter.empty? or /#{filter}/ !~ filename
- end
- else
- def the_same(filter,filename)
- not filter or filter.empty? or /#{filter}/ =~ filename
- end
- end
- @files.keys.each do |name|
- if @files[name].size > 1 then
- data = Array.new
- @files[name].each do |path|
- filename = File.join(path,name)
- # if not filter or filter.empty? or /#{filter}/ =~ filename then
- if the_same(filter,filename) then
- if FileTest.file?(filename) then
- if delete then
- data << FileData.new(1,filename,File.size(filename),File.mtime(filename))
- begin
- File.delete(filename) if delete
- rescue
- end
- else
- data << FileData.new(2,filename,File.size(filename),File.mtime(filename))
- end
- else
- # data << FileData.new(3,filename)
- end
- end
- end
- if data.length > 1 then
- if strict then
- # if data.collect do |d| d.size end.uniq! then
- # data.sort! do |a,b| b.size <=> a.size end
- # data.each do |d| puts d.report end
- # puts ''
- # end
- data.sort! do |a,b|
- if a.size and b.size then
- b.size <=> a.size
- else
- 0
- end
- end
- bunch = Array.new
- done = false
- data.each do |d|
- if bunch.size == 0 then
- bunch << d
- elsif bunch[0].size == d.size then
- bunch << d
- else
- if bunch.size > 1 then
- bunch.each do |b|
- puts b.report
- end
- done = true
- end
- bunch = [d]
- end
- end
- puts '' if done
- else
- case sort
- when 'size' then data.sort! do |a,b| a.size <=> b.size end
- when 'revsize' then data.sort! do |a,b| b.size <=> a.size end
- when 'date' then data.sort! do |a,b| a.date <=> b.date end
- when 'revdate' then data.sort! do |a,b| b.date <=> a.date end
- end
- data.each do |d| puts d.report end
- puts ''
- end
- end
- end
- end
- end
-
-end
-
-# if false then
-
- # k = KpseFast.new # (root)
- # k.set_test_patterns
- # k.load_cnf
- # k.expand_variables
- # k.load_lsr
-
- # k.show_test_patterns
-
- # puts k.list_variables
- # puts k.list_expansions
- # k.list_lsr
- # puts k.expansion("$TEXMF")
- # puts k.expanded_path("TEXINPUTS","context")
-
- # k.progname, k.engine, k.format = 'context', 'pdftex', 'tfm'
- # k.scandisk = false # == must_exist
- # k.expand_variables
-
- # 10.times do |i| puts k.find_file('texnansi-lmr10.tfm') end
-
- # puts "expand braces $TEXMF"
- # puts k.expand_braces("$TEXMF")
- # puts "expand path $TEXMF"
- # puts k.expand_path("$TEXMF")
- # puts "expand var $TEXMF"
- # puts k.expand_var("$TEXMF")
- # puts "expand path $TEXMF"
- # puts k.show_path('tfm')
- # puts "expand value $TEXINPUTS"
- # puts k.var_value("$TEXINPUTS")
- # puts "expand value $TEXINPUTS.context"
- # puts k.var_value("$TEXINPUTS.context")
-
- # exit
-
-# end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/kpseremote.rb b/Master/texmf-dist/scripts/context/ruby/base/kpseremote.rb
deleted file mode 100644
index 9a73b88b00e..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/kpseremote.rb
+++ /dev/null
@@ -1,116 +0,0 @@
-require 'base/kpsefast'
-
-case ENV['KPSEMETHOD']
- when /soap/o then require 'base/kpse/soap'
- when /drb/o then require 'base/kpse/drb'
- else require 'base/kpse/drb'
-end
-
-class KpseRemote
-
- @@port = ENV['KPSEPORT'] || 7000
- @@method = ENV['KPSEMETHOD'] || 'drb'
-
- def KpseRemote::available?
- @@method && @@port
- end
-
- def KpseRemote::start_server(port=nil)
- kpse = KpseServer.new(port || @@port)
- kpse.start
- end
-
- def KpseRemote::start_client(port=nil) # keeps object in server
- kpseclient = KpseClient.new(port || @@port)
- kpseclient.start
- kpse = kpseclient.object
- tree = kpse.choose(KpseUtil::identify, KpseUtil::environment)
- [kpse, tree]
- end
-
- def KpseRemote::fetch(port=nil) # no need for defining methods but slower, send whole object
- kpseclient = KpseClient.new(port || @@port)
- kpseclient.start
- kpseclient.object.fetch(KpseUtil::identify, KpseUtil::environment) rescue nil
- end
-
- def initialize(port=nil)
- if KpseRemote::available? then
- begin
- @kpse, @tree = KpseRemote::start_client(port)
- rescue
- @kpse, @tree = nil, nil
- end
- else
- @kpse, @tree = nil, nil
- end
- end
-
- def progname=(value)
- @kpse.set(@tree,'progname',value)
- end
- def format=(value)
- @kpse.set(@tree,'format',value)
- end
- def engine=(value)
- @kpse.set(@tree,'engine',value)
- end
-
- def progname
- @kpse.get(@tree,'progname')
- end
- def format
- @kpse.get(@tree,'format')
- end
- def engine
- @kpse.get(@tree,'engine')
- end
-
- def load
- @kpse.load(KpseUtil::identify, KpseUtil::environment)
- end
- def okay?
- @kpse && @tree
- end
- def set(key,value)
- @kpse.set(@tree,key,value)
- end
- def load_cnf
- @kpse.load_cnf(@tree)
- end
- def load_lsr
- @kpse.load_lsr(@tree)
- end
- def expand_variables
- @kpse.expand_variables(@tree)
- end
- def expand_braces(str)
- clean_name(@kpse.expand_braces(@tree,str))
- end
- def expand_path(str)
- clean_name(@kpse.expand_path(@tree,str))
- end
- def expand_var(str)
- clean_name(@kpse.expand_var(@tree,str))
- end
- def show_path(str)
- clean_name(@kpse.show_path(@tree,str))
- end
- def var_value(str)
- clean_name(@kpse.var_value(@tree,str))
- end
- def find_file(filename)
- clean_name(@kpse.find_file(@tree,filename))
- end
- def find_files(filename,first=false)
- # dodo: each filename
- @kpse.find_files(@tree,filename,first)
- end
-
- private
-
- def clean_name(str)
- str.gsub(/\\/,'/')
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/kpserunner.rb b/Master/texmf-dist/scripts/context/ruby/base/kpserunner.rb
deleted file mode 100644
index cfc2ad4fbfd..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/kpserunner.rb
+++ /dev/null
@@ -1,87 +0,0 @@
-require 'base/kpsefast'
-
-module KpseRunner
-
- @@kpse = nil
-
- def KpseRunner.kpsewhich(arg='')
- options, arguments = split_args(arg)
- unless @@kpse then
- if ENV['KPSEMETHOD'] && ENV['KPSEPORT'] then
- require 'base/kpseremote'
- @@kpse = KpseRemote.new
- else
- @@kpse = nil
- end
- if @@kpse && @@kpse.okay? then
- @@kpse.progname = options['progname'] || ''
- @@kpse.engine = options['engine'] || ''
- @@kpse.format = options['format'] || ''
- else
- require 'base/kpsefast'
- @@kpse = KpseFast.new
- @@kpse.load_cnf
- @@kpse.progname = options['progname'] || ''
- @@kpse.engine = options['engine'] || ''
- @@kpse.format = options['format'] || ''
- @@kpse.expand_variables
- @@kpse.load_lsr
- end
- else
- @@kpse.progname = options['progname'] || ''
- @@kpse.engine = options['engine'] || ''
- @@kpse.format = options['format'] || ''
- @@kpse.expand_variables
- end
- if option = options['expand-braces'] and not option.empty? then
- @@kpse.expand_braces(option)
- elsif option = options['expand-path'] and not option.empty? then
- @@kpse.expand_path(option)
- elsif option = options['expand-var'] and not option.empty? then
- @@kpse.expand_var(option)
- elsif option = options['show-path'] and not option.empty? then
- @@kpse.show_path(option)
- elsif option = options['var-value'] and not option.empty? then
- @@kpse.expand_var(option)
- elsif arguments.size > 0 then
- files = Array.new
- arguments.each do |option|
- if file = @@kpse.find_file(option) and not file.empty? then
- files << file
- end
- end
- files.join("\n")
- else
- ''
- end
- end
-
- def KpseRunner.kpsereset
- @@kpse = nil
- end
-
- private
-
- def KpseRunner.split_args(arg)
- vars, args = Hash.new, Array.new
- arg.gsub!(/([\"\'])(.*?)\1/o) do
- $2.gsub(' ','<space/>')
- end
- arg = arg.split(/\s+/o)
- arg.collect! do |a|
- a.gsub('<space/>',' ')
- end
- arg.each do |a|
- if a =~ /^(.*?)\=(.*?)$/o then
- k, v = $1, $2
- vars[k.sub(/^\-+/,'')] = v
- else
- args << a
- end
- end
- # puts vars.inspect
- # puts args.inspect
- return vars, args
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/logger.rb b/Master/texmf-dist/scripts/context/ruby/base/logger.rb
deleted file mode 100644
index 2245ab331f0..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/logger.rb
+++ /dev/null
@@ -1,105 +0,0 @@
-# module : base/logger
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-require 'thread'
-
-# The next calls are valid:
-
-# @log.report('a','b','c', 'd')
-# @log.report('a','b',"c #{d}")
-# @log.report("a b c #{d}")
-
-# Keep in mind that "whatever #{something}" is two times faster than
-# 'whatever ' + something or ['whatever',something].join and that
-# when verbosity is not needed the following is much faster too:
-
-# @log.report('a','b','c', 'd') if @log.verbose?
-# @log.report('a','b',"c #{d}") if @log.verbose?
-# @log.report("a b c #{d}") if @log.verbose?
-
-# The last three cases are equally fast when verbosity is turned off.
-
-# Under consideration: verbose per instance
-
-class Logger
-
- @@length = 0
- @@verbose = false
-
- def initialize(tag=nil,length=0,verbose=false)
- @tag = tag || ''
- @@verbose = @@verbose || verbose
- @@length = @tag.length if @tag.length > @@length
- @@length = length if length > @@length
- end
-
- def report(*str)
- begin
- case str.length
- when 0
- print("\n")
- return true
- when 1
- # message = str.first
- message = str.first.join(' ')
- else
- message = [str].flatten.collect{|s| s.to_s}.join(' ').chomp
- end
- if @tag.empty? then
- print("#{message}\n")
- else
- # try to avoid too many adjustments
- @tag = @tag.ljust(@@length) unless @tag.length == @@length
- print("#{@tag} | #{message}\n")
- end
- rescue
- end
- return true
- end
-
- def reportlines(*str)
- unless @tag.empty? then
- @tag = @tag.ljust(@@length) unless @tag.length == @@length
- end
- report([str].flatten.collect{|s| s.gsub(/\n/,"\n#{@tag} | ")}.join(' '))
- end
-
- def debug(*str)
- report(str) if @@verbose
- end
-
- def error(*str)
- if ! $! || $!.to_s.empty? then
- report(str)
- else
- report(str,$!)
- end
- end
-
- def verbose
- @@verbose = true
- end
-
- def silent
- @@verbose = false
- end
-
- def verbose?
- @@verbose
- end
-
- # attr_reader :tag
-
- # alias fatal error
- # alias info debug
- # alias warn debug
- # alias debug? :verbose?
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/merge.rb b/Master/texmf-dist/scripts/context/ruby/base/merge.rb
deleted file mode 100644
index a66b97e916b..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/merge.rb
+++ /dev/null
@@ -1,139 +0,0 @@
-# module : base/merge
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2006
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# --selfmerg ewill create stand alone script (--selfcleanup does the opposite)
-
-# this module will package all the used modules in the file itself
-# so that we can relocate the file at wish, usage:
-#
-# merge:
-#
-# unless SelfMerge::ok? && SelfMerge::merge then
-# puts("merging should happen on the path were the base inserts reside")
-# end
-#
-# cleanup:
-#
-# unless SelfMerge::cleanup then
-# puts("merging should happen on the path were the base inserts reside")
-# end
-
-module SelfMerge
-
- @@kpsemergestart = "\# kpse_merge_start"
- @@kpsemergestop = "\# kpse_merge_stop"
- @@kpsemergefile = "\# kpse_merge_file: "
- @@kpsemergedone = "\# kpse_merge_done: "
-
- @@filename = File.basename($0)
- @@ownpath = File.expand_path(File.dirname($0))
- @@modroot = '(base|graphics|rslb|www)' # needed in regex in order not to mess up SelfMerge
- @@modules = $".collect do |file| File.expand_path(file) end
-
- @@modules.delete_if do |file|
- file !~ /^#{@@ownpath}\/#{@@modroot}.*$/i
- end
-
- def SelfMerge::ok?
- begin
- @@modules.each do |file|
- return false unless FileTest.file?(file)
- end
- rescue
- return false
- else
- return true
- end
- end
-
- def SelfMerge::merge
- begin
- if SelfMerge::ok? && rbfile = IO.read(@@filename) then
- begin
- inserts = "#{@@kpsemergestart}\n\n"
- @@modules.each do |file|
- inserts << "#{@@kpsemergefile}'#{file}'\n\n"
- inserts << IO.read(file).gsub(/^#.*?\n$/,'')
- inserts << "\n\n"
- end
- inserts << "#{@@kpsemergestop}\n\n"
- # no gsub! else we end up in SelfMerge
- rbfile.sub!(/#{@@kpsemergestart}\s*#{@@kpsemergestop}/moi) do
- inserts
- end
- rbfile.gsub!(/^(.*)(require [\"\'].*?#{@@modroot}.*)$/) do
- pre, post = $1, $2
- if pre =~ /#{@@kpsemergedone}/ then
- "#{pre}#{post}"
- else
- "#{pre}#{@@kpsemergedone}#{post}"
- end
- end
- rescue
- return false
- else
- begin
- File.open(@@filename,'w') do |f|
- f << rbfile
- end
- rescue
- return false
- end
- end
- end
- rescue
- return false
- else
- return true
- end
- end
-
- def SelfMerge::cleanup
- begin
- if rbfile = IO.read(@@filename) then
- begin
- rbfile.sub!(/#{@@kpsemergestart}(.*)#{@@kpsemergestop}\s*/moi) do
- "#{@@kpsemergestart}\n\n#{@@kpsemergestop}\n\n"
- end
- rbfile.gsub!(/^(.*#{@@kpsemergedone}.*)$/) do
- str = $1
- if str =~ /require [\"\']/ then
- str.gsub(/#{@@kpsemergedone}/, '')
- else
- str
- end
- end
- rescue
- return false
- else
- begin
- File.open(@@filename,'w') do |f|
- f << rbfile
- end
- rescue
- return false
- end
- end
- end
- rescue
- return false
- else
- return true
- end
- end
-
- def SelfMerge::replace
- if SelfMerge::ok? then
- SelfMerge::cleanup
- SelfMerge::merge
- end
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/mp.rb b/Master/texmf-dist/scripts/context/ruby/base/mp.rb
deleted file mode 100644
index d168bde1d43..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/mp.rb
+++ /dev/null
@@ -1,167 +0,0 @@
-# module : base/mp
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2005-2006
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-module MPTools
-
- @@definitions, @@start, @@stop, @@before, @@after = Hash.new, Hash.new, Hash.new, Hash.new, Hash.new
-
-
- @@definitions['plain'] = <<EOT
-\\gdef\\mpxshipout{\\shipout\\hbox\\bgroup
- \\setbox0=\\hbox\\bgroup}
-
-\\gdef\\stopmpxshipout{\\egroup \\dimen0=\\ht0 \\advance\\dimen0\\dp0
- \\dimen1=\\ht0 \\dimen2=\\dp0
- \\setbox0=\\hbox\\bgroup
- \\box0
- \\ifnum\\dimen0>0 \\vrule width1sp height\\dimen1 depth\\dimen2
- \\else \\vrule width1sp height1sp depth0sp\\relax
- \\fi\\egroup
- \\ht0=0pt \\dp0=0pt \\box0 \\egroup}
-EOT
-
- @@start ['plain'] = ""
- @@before['plain'] = "\\mpxshipout"
- @@after ['plain'] = "\\stopmpxshipout"
- @@stop ['plain'] = "\\end{document}"
-
- @@definitions['context'] = <<EOT
-\\ifx\\startMPXpage\\undefined
-
- \\ifx\\loadallfontmapfiles\\undefined \\let\\loadallfontmapfiles\\relax \\fi
-
- \\gdef\\startMPXpage
- {\\shipout\\hbox
- \\bgroup
- \\setbox0=\\hbox
- \\bgroup}
-
- \\gdef\\stopMPXpage
- {\\egroup
- \\dimen0=\\ht0
- \\advance\\dimen0\\dp0
- \\dimen1=\\ht0
- \\dimen2=\\dp0
- \\setbox0=\\hbox\\bgroup
- \\box0
- \\ifnum\\dimen0>0
- \\vrule width 1sp height \\dimen1 depth \\dimen2
- \\else
- \\vrule width 1sp height 1sp depth 0sp \\relax
- \\fi
- \\egroup
- \\ht0=0pt
- \\dp0=0pt
- \\loadallfontmapfiles
- \\box0
- \\egroup}
-
-\\fi
-
-\\ifx\\starttext\\undefined
-
- \\let\\starttext\\relax
- \\def\\stoptext{\\end{document}}
-
-\\fi
-EOT
-
- @@start ['context'] = "\\starttext"
- @@before['context'] = "\\startMPXpage"
- @@after ['context'] = "\\stopMPXpage"
- @@stop ['context'] = "\\stoptext"
-
- # todo: \usemodule[m-mpx ] and test fo defined
-
- def MPTools::mptotex(from,to=nil,method='plain')
- begin
- if from && data = IO.read(from) then
- f = if to then File.open(to,'w') else $stdout end
- f.puts("% file: #{from}")
- f.puts("")
- f.puts(@@definitions[method])
- unless @@start[method].empty? then
- f.puts("")
- f.puts(@@start[method])
- end
- data.gsub!(/([^\\])%.*?$/mo) do
- $1
- end
- data.scan(/(verbatim|b)tex\s*(.*?)\s*etex/mo) do
- tag, text = $1, $2
- f.puts("")
- if tag == 'b' then
- f.puts(@@before[method])
- f.puts("#{text}%")
- f.puts(@@after [method])
- else
- f.puts("#{text}")
- end
- f.puts("")
- end
- f.puts("")
- f.puts(@@stop[method])
- f.close
- else
- return false
- end
- rescue
- File.delete(to) rescue false
- return false
- else
- return true
- end
- end
-
- @@splitMPlines = false
-
- def MPTools::splitmplines(str)
- if @@splitMPlines then
- btex, verbatimtex, strings, result = Array.new, Array.new, Array.new, str.dup
- # protect texts
- result.gsub!(/btex\s*(.*?)\s*etex/) do
- btex << $1
- "btex(#{btex.length-1})"
- end
- result.gsub!(/verbatimtex\s*(.*?)\s*etex/) do
- verbatimtex << $1
- "verbatimtex(#{verbatimtex.length-1})"
- end
- result.gsub!(/\"(.*?)\"/) do
- strings << $1
- "\"#{strings.length-1}\""
- end
- result.gsub!(/\;/) do
- ";\n"
- end
- result.gsub!(/(.{80,})(\-\-\-|\-\-|\.\.\.|\.\.)/) do
- "#{$1}#{$2}\n"
- end
- result.gsub!(/\n[\s\n]+/moi) do
- "\n"
- end
- result.gsub!(/btex\((\d+)\)/) do
- "btex #{btex[$1.to_i]} etex"
- end
- result.gsub!(/verbatimtex\((\d+)\)/) do
- "verbatimtex #{verbatimtex[$1.to_i]} etex"
- end
- result.gsub!(/\"(\d+)\"/) do
- "\"#{strings[$1.to_i]}\""
- end
- # return result # let's catch xetex bug
- return result.gsub(/\^\^(M|J)/o, "\n")
- else
- # return str # let's catch xetex bug
- return str.gsub(/\^\^(M|J)/o, "\n")
- end
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/pdf.rb b/Master/texmf-dist/scripts/context/ruby/base/pdf.rb
deleted file mode 100644
index 6be0d3f987e..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/pdf.rb
+++ /dev/null
@@ -1,83 +0,0 @@
-module PDFview
-
- @files = Hash.new
- @opencalls = Hash.new
- @closecalls = Hash.new
- @allcalls = Hash.new
-
- # acrobat no longer is a valid default as (1) it keeps crashing with pdfopen due to a dual acrobat/reader install (a side effect
- # of the api changing every version, and (2) because there are all these anyoing popups with respect to signed, review, online
- # this and that stuff ... hardly useable as fast previewer, and (3) sumatra is faster and nicer and doesn't block (okay, we have to
- # get rid of this horrible yellow bg-coloring buts that is doable
-
- @method = 'sumatra' # 'default' # 'xpdf'
-
- @opencalls['default'] = "pdfopen --file" # "pdfopen --back --file"
- @opencalls['xpdf'] = "xpdfopen"
- @opencalls['sumatra'] = 'start "test" sumatrapdf.exe -reuse-instance -bg-color 0xCCCCCC'
-
- @closecalls['default'] = "pdfclose --file"
- @closecalls['xpdf'] = nil
- @closecalls['sumatra'] = nil
-
- @allcalls['default'] = "pdfclose --all"
- @allcalls['xpdf'] = nil
- @allcalls['sumatra'] = nil
-
- def PDFview.setmethod(method)
- @method = method
- end
-
- def PDFview.open(*list)
- begin
- [*list].flatten.each do |file|
- filename = fullname(file)
- if FileTest.file?(filename) then
- if @opencalls[@method] then
- result = `#{@opencalls[@method]} #{filename} 2>&1`
- @files[filename] = true
- end
- end
- end
- rescue
- end
- end
-
- def PDFview.close(*list)
- [*list].flatten.each do |file|
- filename = fullname(file)
- begin
- if @files.key?(filename) then
- if @closecalls[@method] then
- result = `#{@closecalls[@method]} #{filename} 2>&1`
- end
- else
- closeall
- return
- end
- rescue
- end
- @files.delete(filename)
- end
- end
-
- def PDFview.closeall
- begin
- if @allcalls[@method] then
- result = `#{@allcalls[@method]} 2>&1`
- end
- rescue
- end
- @files.clear
- end
-
- def PDFview.fullname(name)
- name + if name =~ /\.pdf$/ then '' else '.pdf' end
- end
-
-end
-
-# PDFview.open("t:/document/show-exa.pdf")
-# PDFview.open("t:/document/show-gra.pdf")
-# PDFview.close("t:/document/show-exa.pdf")
-# PDFview.close("t:/document/show-gra.pdf")
diff --git a/Master/texmf-dist/scripts/context/ruby/base/state.rb b/Master/texmf-dist/scripts/context/ruby/base/state.rb
deleted file mode 100644
index 76ef50b2563..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/state.rb
+++ /dev/null
@@ -1,75 +0,0 @@
-require 'digest/md5'
-
-# todo: register omissions per file
-
-class FileState
-
- def initialize
- @states = Hash.new
- @omiter = Hash.new
- end
-
- def reset
- @states.clear
- @omiter.clear
- end
-
- def register(filename,omit=nil)
- unless @states.key?(filename) then
- @states[filename] = Array.new
- @omiter[filename] = omit
- end
- @states[filename] << checksum(filename,@omiter[filename])
- end
-
- def update(filename=nil)
- [filename,@states.keys].flatten.compact.uniq.each do |fn|
- register(fn)
- end
- end
-
- def inspect(filename=nil)
- result = ''
- [filename,@states.keys].flatten.compact.uniq.sort.each do |fn|
- if @states.key?(fn) then
- result += "#{fn}: #{@states[fn].inspect}\n"
- end
- end
- result
- end
-
- def changed?(filename)
- if @states.key?(filename) then
- n = @states[filename].length
- if n>1 then
- changed = @states[filename][n-1] != @states[filename][n-2]
- else
- changed = true
- end
- else
- changed = true
- end
- return changed
- end
-
- def checksum(filename,omit=nil)
- sum = ''
- begin
- if FileTest.file?(filename) && (data = IO.read(filename)) then
- data.gsub!(/\n.*?(#{[omit].flatten.join('|')}).*?\n/) do "\n" end if omit
- sum = Digest::MD5.hexdigest(data).upcase
- end
- rescue
- sum = ''
- end
- return sum
- end
-
- def stable?
- @states.keys.each do |s|
- return false if changed?(s)
- end
- return true
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/switch.rb b/Master/texmf-dist/scripts/context/ruby/base/switch.rb
deleted file mode 100644
index 73f53208281..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/switch.rb
+++ /dev/null
@@ -1,637 +0,0 @@
-#encoding: ASCII-8BIT
-
-# module : base/switch
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# we cannot use getoptlong because we want to be more
-# tolerant; also we want to be case insensitive (2002).
-
-# we could make each option a class itself, but this is
-# simpler; also we can put more in the array
-
-# beware: regexps/o in methods are optimized globally
-
-require "rbconfig"
-
-$mswindows = RbConfig::CONFIG['host_os'] =~ /mswin/
-$separator = File::PATH_SEPARATOR
-
-class String
-
- def has_suffix?(suffix)
- self =~ /\.#{suffix}$/i
- end
-
-end
-
-# may move to another module
-
-class File
-
- @@update_eps = 1
-
- def File.needsupdate(oldname,newname)
- begin
- oldtime = File.stat(oldname).mtime.to_i
- newtime = File.stat(newname).mtime.to_i
- if newtime >= oldtime then
- return false
- elsif oldtime-newtime < @@update_eps then
- return false
- else
- return true
- end
- rescue
- return true
- end
- end
-
- def File.syncmtimes(oldname,newname)
- return
- begin
- if $mswindows then
- # does not work (yet) / gives future timestamp
- # t = File.mtime(oldname) # i'm not sure if the time is frozen, so we do it here
- # File.utime(0,t,oldname,newname)
- else
- t = File.mtime(oldname) # i'm not sure if the time is frozen, so we do it here
- File.utime(0,t,oldname,newname)
- end
- rescue
- end
- end
-
- def File.timestamp(name)
- begin
- "#{File.stat(name).mtime}"
- rescue
- return 'unknown'
- end
- end
-
-end
-
-# main thing
-
-module CommandBase
-
- # this module can be used as a mixin in a command handler
-
- $stdout.sync = true
-
- def initialize(commandline,logger,banner)
- @commandline, @logger, @banner = commandline, logger, banner
- @forcenewline, @versiondone, @error = false, false, false
- version if @commandline.option('version')
- end
-
- def reportlines(*str)
- @logger.reportlines(str)
- end
-
- # only works in 1.8
- #
- # def report(*str)
- # @logger.report(str)
- # end
- #
- # def version # just a bit of playing with defs
- # report(@banner.join(' - '))
- # def report(*str)
- # @logger.report
- # @logger.report(str)
- # def report(*str)
- # @logger.report(str)
- # end
- # end
- # def version
- # end
- # end
-
- def report(*str)
- initlogger ; @logger.report(str)
- end
-
- def seterror
- @error = true
- end
-
- def error?
- return @error
- end
-
- def exit
- if @error then Kernel.exit(1) else Kernel.exit(0) end
- end
-
- def execute(str=nil)
- send(str || action || 'main')
- exit
- end
-
- def debug(*str)
- initlogger ; @logger.debug(str)
- end
-
- def error(*str)
- initlogger ; @logger.error(str)
- end
-
- def initlogger
- if @forcenewline then
- @logger.report
- @forcenewline = false
- end
- end
-
- def logger
- @logger
- end
-
- def version # just a bit of playing with defs
- unless @versiondone then
- report(@banner.join(' - '))
- @forcenewline = true
- @versiondone = true
- end
- end
-
- def help
- version # is nilled when already given
- @commandline.helpkeys.each do |k|
- if @commandline.help?(k) then
- kstr = ('--'+k).ljust(@commandline.helplength+2)
- message = @commandline.helptext(k)
- message = '' if message == CommandLine::NOHELP
- message = message.split(/\s*\n\s*/)
- loop do
- report("#{kstr} #{message.shift}")
- kstr = ' '*kstr.length
- break if message.length == 0
- end
- end
- end
- end
-
- def option(key)
- @commandline.option(key)
- end
- def oneof(*key)
- @commandline.oneof(*key)
- end
-
- def globfiles(pattern='*',suffix=nil)
- @commandline.setarguments([pattern].flatten)
- if files = findfiles(suffix) then
- @commandline.setarguments(files)
- else
- @commandline.setarguments
- end
- end
-
- private
-
- def findfiles(suffix=nil)
-
- if @commandline.arguments.length>1 then
- return @commandline.arguments
- else
- pattern = @commandline.argument('first')
- pattern = '*' if pattern.empty?
- if suffix && ! pattern.match(/\..+$/o) then
- suffix = '.' + suffix
- pattern += suffix unless pattern =~ /#{suffix}$/
- end
- # not {} safe
- pattern = '**/' + pattern if @commandline.option('recurse')
- files = Dir[pattern]
- if files && files.length>0 then
- return files
- else
- pattern = @commandline.argument('first')
- if FileTest.file?(pattern) then
- return [pattern]
- else
- report("no files match pattern #{pattern}")
- return nil
- end
- end
- end
-
- end
-
- def globbed(pattern,recurse=false)
-
- files = Array.new
- pattern.split(' ').each do |p|
- if recurse then
- if p =~ /^(.*)(\/.*?)$/i then
- p = $1 + '/**' + $2
- else
- p = '**/' + p
- end
- p.gsub!(/[\\\/]+/, '/')
- end
- files.push(Dir.glob(p))
- end
- files.flatten.sort do |a,b|
- pathcompare(a,b)
- end
- end
-
- def pathcompare(a,b)
-
- aa, bb = a.split('/'), b.split('/')
- if aa.length == bb.length then
- aa.each_index do |i|
- if aa[i]<bb[i] then
- return -1
- elsif aa[i]>bb[i] then
- return +1
- end
- end
- return 0
- else
- return aa.length <=> bb.length
- end
-
- end
-
-end
-
-class CommandLine
-
- VALUE, FLAG = 1, 2
- NOHELP = 'no arguments'
-
- def initialize(prefix='-')
-
- @registered = Array.new
- @options = Hash.new
- @unchecked = Hash.new
- @arguments = Array.new
- @original = ARGV.join(' ')
- @helptext = Hash.new
- @mandated = Hash.new
- @provided = Hash.new
- @prefix = prefix
- @actions = Array.new
-
- # The quotes in --switch="some value" get lost in ARGV, so we need to do some trickery here.
-
- @original = ''
- ARGV.each do |a|
- aa = a.strip.gsub(/^([#{@prefix}]+\w+\=)([^\"].*?\s+.*[^\"])$/) do
- $1 + "\"" + $2 + "\""
- end
- @original += if @original.empty? then '' else ' ' end + aa
- end
-
- end
-
- def setarguments(args=[])
- @arguments = if args then args else [] end
- end
-
- def register(option,shortcut,kind,default=false,action=false,helptext='')
- if kind == FLAG then
- @options[option] = default
- elsif not default then
- @options[option] = ''
- else
- @options[option] = default
- end
- @registered.push([option,shortcut,kind])
- @mandated[option] = false
- # @provided[option] = false
- @helptext[option] = helptext
- @actions.push(option) if action
- end
-
- def registerflag(option,default=false,helptext='')
- if default.class == String then
- register(option,'',FLAG,false,false,default)
- else
- register(option,'',FLAG,false,false,helptext)
- end
- end
-
- def registervalue(option,default='',helptext='')
- register(option,'',VALUE,default,false,helptext)
- end
-
- def registeraction(option,helptext='')
- register(option,'',FLAG,false,true,helptext)
- end
-
- def registermandate(*option)
- [*option].each do |o|
- [o].each do |oo|
- @mandated[oo] = true
- end
- end
- end
-
- def actions
- a = @actions.delete_if do |t|
- ! option(t)
- end
- if a && a.length>0 then
- return a
- else
- return nil
- end
- end
-
- def action
- @actions.each do |t|
- return t if option(t)
- end
- return nil
- end
-
- def forgotten
- @mandated.keys.sort - @provided.keys.sort
- end
-
- def registerhelp(option,text='')
- @helptext['unknown'] = if text.empty? then option else text end
- end
-
- def helpkeys(option='.*')
- @helptext.keys.sort.grep(/#{option}/)
- end
-
- def helptext(option)
- @helptext.fetch(option,'')
- end
-
- def help?(option)
- @helptext[option] && ! @helptext[option].empty?
- end
-
- def helplength
- n = 0
- @helptext.keys.each do |h|
- n = h.length if h.length>n
- end
- return n
- end
-
- def expand
-
- # todo : '' or false, depending on type
- # @options.clear
- # @arguments.clear
-
- dirtyvalue(@original).split(' ').each do |arg|
- case arg
- when /^[#{@prefix}][#{@prefix}](.+?)\=(.*?)$/ then locatedouble($1,$2)
- when /^[#{@prefix}][#{@prefix}](.+?)$/ then locatedouble($1,false)
- when /^[#{@prefix}](.)\=(.)$/ then locatesingle($1,$2)
- when /^[#{@prefix}](.+?)$/ then locateseries($1,false)
- when /^[\+\-]+/o then # do nothing
- else
- arguments.push(arg)
- end
- end
-
- @options or @unchecked or @arguments
-
- end
-
- def extend (str)
- @original = @original + ' ' + str
- end
-
- def replace (str)
- @original = str
- end
-
- def show
- # print "-- options --\n"
- @options.keys.sort.each do |key|
- print "option: #{key} -> #{@options[key]}\n"
- end
- # print "-- arguments --\n"
- @arguments.each_index do |key|
- print "argument: #{key} -> #{@arguments[key]}\n"
- end
- end
-
- def option(str,default=nil)
- if @options.key?(str) then
- @options[str]
- elsif default then
- default
- else
- @options[str]
- end
- end
-
- def checkedoption(str,default='')
- if @options.key?(str) then
- if @options[str].empty? then default else @options[str] end
- else
- default
- end
- end
-
- def foundoption(str,default='')
- str = str.split(',') if str.class == String
- str.each do |s|
- return str if @options.key?(str)
- end
- return default
- end
-
- def oneof(*key)
- [*key].flatten.compact.each do |k|
- return true if @options.key?(k) && @options[k]
- end
- return false
- end
-
- def setoption(str,value)
- @options[str] = value
- end
-
- def getoption(str,value='') # value ?
- @options[str]
- end
-
- def argument(n=0)
- if n.class == String then
- case n
- when 'first' then argument(0)
- when 'second' then argument(1)
- when 'third' then argument(2)
- else
- argument(0)
- end
- elsif @arguments[n] then
- @arguments[n]
- else
- ''
- end
- end
-
- # a few local methods, cannot be defined nested (yet)
-
- private
-
- def dirtyvalue(value) # \xFF suddenly doesn't work any longer
- if value then
- value.gsub(/([\"\'])(.*?)\1/) do
- $2.gsub(/\s+/o, "\0xFF")
- end
- else
- ''
- end
- end
-
- def cleanvalue(value) # \xFF suddenly doesn't work any longer
- if value then
- # value.sub(/^([\"\'])(.*?)\1$/) { $2.gsub(/\xFF/o, ' ') }
- value.gsub(/\0xFF/o, ' ')
- else
- ''
- end
- end
-
- def locatedouble(key, value)
-
- foundkey, foundkind = nil, nil
-
- @registered.each do |option, shortcut, kind|
- if option == key then
- foundkey, foundkind = option, kind
- break
- end
- end
- unless foundkey then
- @registered.each do |option, shortcut, kind|
- n = 0
- begin
- re = /^#{key}/i
- rescue
- key = key.inspect.sub(/^\"(.*)\"$/) do $1 end
- re = /^#{key}/i
- ensure
- if option =~ re then
- case n
- when 0
- foundkey, foundkind, n = option, kind, 1
- when 1
- # ambiguous matches, like --fix => --fixme --fixyou
- foundkey, foundkind = nil, nil
- break
- end
- end
- end
- end
- end
- if foundkey then
- @provided[foundkey] = true
- if foundkind == VALUE then
- @options[foundkey] = cleanvalue(value)
- else
- @options[foundkey] = true
- end
- else
- if value.class == FalseClass then
- @unchecked[key] = true
- else
- @unchecked[key] = cleanvalue(value)
- end
- end
-
- end
-
- def locatesingle(key, value)
-
- @registered.each do |option, shortcut, kind|
- if shortcut == key then
- @provided[option] = true
- @options[option] = if kind == VALUE then '' else cleanvalue(value) end
- break
- end
- end
-
- end
-
- def locateseries(series, value)
-
- series.each_char do |key| # was .each but there is no alias to each_char any longer
- locatesingle(key,cleanvalue(value))
- end
-
- end
-
- public
-
- attr_reader :arguments, :options, :original, :unchecked
-
-end
-
-# options = CommandLine.new
-#
-# options.register("filename", "f", CommandLine::VALUE)
-# options.register("request" , "r", CommandLine::VALUE)
-# options.register("verbose" , "v", CommandLine::FLAG)
-#
-# options.expand
-# options.extend(str)
-# options.show
-#
-# c = CommandLine.new
-#
-# c.registervalue('aaaa')
-# c.registervalue('test')
-# c.registervalue('zzzz')
-#
-# c.registerhelp('aaaa','some aaaa to enter')
-# c.registerhelp('test','some text to enter')
-# c.registerhelp('zzzz','some zzzz to enter')
-#
-# c.registermandate('test')
-#
-# c.expand
-#
-# class CommandLine
-#
-# def showhelp (banner,*str)
-# if helpkeys(*str).length>0
-# print banner
-# helpkeys(*str).each do |h|
-# print helptext(h) + "\n"
-# end
-# true
-# else
-# false
-# end
-# end
-#
-# def showmandate(banner)
-# if forgotten.length>0
-# print banner
-# forgotten.each do |f|
-# print helptext(f) + "\n"
-# end
-# true
-# else
-# false
-# end
-# end
-#
-# end
-#
-# c.showhelp("you can provide:\n\n")
-# c.showmandate("you also need to provide:\n\n")
diff --git a/Master/texmf-dist/scripts/context/ruby/base/system.rb b/Master/texmf-dist/scripts/context/ruby/base/system.rb
deleted file mode 100644
index 71c0af421f9..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/system.rb
+++ /dev/null
@@ -1,121 +0,0 @@
-# module : base/system
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-require "rbconfig"
-
-module System
-
- @@mswindows = RbConfig::CONFIG['host_os'] =~ /mswin/
- @@binpaths = ENV['PATH'].split(File::PATH_SEPARATOR)
- @@binsuffixes = if $mswindows then ['.exe','.com','.bat'] else ['','.sh','.csh'] end
- @@located = Hash.new
- @@binnames = Hash.new
-
- if @@mswindows then
- @@binnames['ghostscript'] = ['gswin32c.exe','gs.cmd','gs.bat']
- @@binnames['imagemagick'] = ['imagemagick.exe','convert.exe']
- @@binnames['inkscape'] = ['inkscape.exe']
- else
- @@binnames['ghostscript'] = ['gs']
- @@binnames['imagemagick'] = ['convert']
- @@binnames['inkscape'] = ['inkscape']
- end
-
-
- def System.null
- if @@mswindows then 'nul' else '/dev/null' end
- end
-
- def System.unix?
- not @@mswindows
- end
- def System.mswin?
- @@mswindows
- end
-
- def System.binnames(str)
- if @@binnames.key?(str) then
- @@binnames[str]
- else
- [str]
- end
- end
-
- def System.prependengine(str)
- if str =~ /^\S+\.(pl|rb|lua|py)/io then
- case $1
- when 'pl' then return "perl #{str}"
- when 'rb' then return "ruby #{str}"
- when 'lua' then return "lua #{str}"
- when 'py' then return "python #{str}"
- end
- end
- return str
- end
-
- def System.locatedprogram(program)
- if @@located.key?(program) then
- return @@located[program]
- else
- System.binnames(program).each do |binname|
- if binname =~ /\..*$/io then
- @@binpaths.each do |path|
- if FileTest.file?(str = File.join(path,binname)) then
- return @@located[program] = System.prependengine(str)
- end
- end
- end
- binname.gsub!(/\..*$/io, '')
- @@binpaths.each do |path|
- @@binsuffixes.each do |suffix|
- if FileTest.file?(str = File.join(path,"#{binname}#{suffix}")) then
- return @@located[program] = System.prependengine(str)
- end
- end
- end
- end
- end
- return @@located[program] = "texmfstart #{program}"
- end
-
- def System.command(program,arguments='')
- if program =~ /^(.*?) (.*)$/ then
- program = System.locatedprogram($1) + ' ' + $2
- else
- program = System.locatedprogram(program)
- end
- program = program + ' ' + arguments if ! arguments.empty?
- program.gsub!(/\s+/io, ' ')
- #program.gsub!(/(\/\.\/)+/io, '/')
- program.gsub!(/\\/io, '/')
- return program
- end
-
- def System.run(program,arguments='',pipe=false,collect=false)
- if pipe then
- if collect then
- `#{System.command(program,arguments)} 2>&1`
- else
- `#{System.command(program,arguments)}`
- end
- else
- system(System.command(program,arguments))
- end
- end
-
- def System.pipe(program,arguments='',collect=false)
- System.run(program,arguments,true)
- end
-
- def System.safepath(path)
- if path.match(/ /o) then "\"#{path}\"" else path end
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/tex.rb b/Master/texmf-dist/scripts/context/ruby/base/tex.rb
deleted file mode 100644
index 9a520f3131f..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/tex.rb
+++ /dev/null
@@ -1,2182 +0,0 @@
-#encoding: ASCII-8BIT
-
-# module : base/tex
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# todo:
-#
-# - write systemcall for mpost to file so that it can be run faster
-# - use -8bit and -progname
-#
-
-# report ?
-
-require 'fileutils'
-
-require 'base/variables'
-require 'base/kpse'
-require 'base/system'
-require 'base/state'
-require 'base/pdf'
-require 'base/file'
-require 'base/ctx'
-require 'base/mp'
-
-class String
-
- def standard?
- begin
- self == 'standard'
- rescue
- false
- end
- end
-
-end
-
-# class String
- # def utf_bom?
- # self.match(/^\357\273\277/o).length>0 rescue false
- # end
-# end
-
-class Array
-
- def standard?
- begin
- self.include?('standard')
- rescue
- false
- end
- end
-
- def join_path
- self.join(File::PATH_SEPARATOR)
- end
-
-end
-
-class TEX
-
- # The make-part of this class was made on a rainy day while listening
- # to "10.000 clowns on a rainy day" by Jan Akkerman. Unfortunately the
- # make method is not as swinging as this live cd.
-
- include Variables
-
- @@texengines = Hash.new
- @@mpsengines = Hash.new
- @@backends = Hash.new
- @@mappaths = Hash.new
- @@runoptions = Hash.new
- @@draftoptions = Hash.new
- @@synctexcoptions = Hash.new
- @@texformats = Hash.new
- @@mpsformats = Hash.new
- @@prognames = Hash.new
- @@texmakestr = Hash.new
- @@texprocstr = Hash.new
- @@mpsmakestr = Hash.new
- @@mpsprocstr = Hash.new
- @@texmethods = Hash.new
- @@mpsmethods = Hash.new
- @@pdftex = 'pdftex'
-
- @@platformslash = if System.unix? then "\\\\" else "\\" end
-
- ['tex','etex','pdftex','standard'] .each do |e| @@texengines[e] = 'pdftex' end
- ['aleph','omega'] .each do |e| @@texengines[e] = 'aleph' end
- ['xetex'] .each do |e| @@texengines[e] = 'xetex' end
- ['petex'] .each do |e| @@texengines[e] = 'petex' end
-
- ['metapost','mpost', 'standard'] .each do |e| @@mpsengines[e] = 'mpost' end
-
- ['pdftex','pdf','pdftex','standard'] .each do |b| @@backends[b] = 'pdftex' end
- ['dvipdfmx','dvipdfm','dpx','dpm'] .each do |b| @@backends[b] = 'dvipdfmx' end
- ['xetex','xtx'] .each do |b| @@backends[b] = 'xetex' end
- ['petex'] .each do |b| @@backends[b] = 'dvipdfmx' end
- ['aleph'] .each do |b| @@backends[b] = 'dvipdfmx' end
- ['dvips','ps','dvi'] .each do |b| @@backends[b] = 'dvips' end
- ['dvipsone'] .each do |b| @@backends[b] = 'dvipsone' end
- ['acrobat','adobe','distiller'] .each do |b| @@backends[b] = 'acrobat' end
- ['xdv','xdv2pdf'] .each do |b| @@backends[b] = 'xdv2pdf' end
-
- ['tex','standard'] .each do |b| @@mappaths[b] = 'dvips' end
- ['pdftex'] .each do |b| @@mappaths[b] = 'pdftex' end
- ['aleph','omega','xetex','petex'] .each do |b| @@mappaths[b] = 'dvipdfmx' end
- ['dvipdfm', 'dvipdfmx', 'xdvipdfmx'] .each do |b| @@mappaths[b] = 'dvipdfmx' end
- ['xdv','xdv2pdf'] .each do |b| @@mappaths[b] = 'dvips' end
-
- # todo norwegian (no)
-
- ['plain'] .each do |f| @@texformats[f] = 'plain' end
- ['cont-en','en','english','context','standard'].each do |f| @@texformats[f] = 'cont-en.mkii' end
- ['cont-nl','nl','dutch'] .each do |f| @@texformats[f] = 'cont-nl.mkii' end
- ['cont-de','de','german'] .each do |f| @@texformats[f] = 'cont-de.mkii' end
- ['cont-it','it','italian'] .each do |f| @@texformats[f] = 'cont-it.mkii' end
- ['cont-fr','fr','french'] .each do |f| @@texformats[f] = 'cont-fr.mkii' end
- ['cont-cs','cs','cont-cz','cz','czech'] .each do |f| @@texformats[f] = 'cont-cs.mkii' end
- ['cont-ro','ro','romanian'] .each do |f| @@texformats[f] = 'cont-ro.mkii' end
- ['cont-gb','gb','cont-uk','uk','british'] .each do |f| @@texformats[f] = 'cont-gb.mkii' end
- ['mptopdf'] .each do |f| @@texformats[f] = 'mptopdf' end
-
- ['latex'] .each do |f| @@texformats[f] = 'latex.ltx' end
-
- ['plain','mpost'] .each do |f| @@mpsformats[f] = 'mpost' end
- ['metafun','context','standard'] .each do |f| @@mpsformats[f] = 'metafun' end
-
- ['pdftex','aleph','omega','petex','xetex'] .each do |p| @@prognames[p] = 'context' end
- ['mpost'] .each do |p| @@prognames[p] = 'metafun' end
- ['latex','pdflatex'] .each do |p| @@prognames[p] = 'latex' end
-
- ['plain','default','standard','mptopdf'] .each do |f| @@texmethods[f] = 'plain' end
- ['cont-en','cont-en.mkii',
- 'cont-nl','cont-nl.mkii',
- 'cont-de','cont-de.mkii',
- 'cont-it','cont-it.mkii',
- 'cont-fr','cont-fr.mkii',
- 'cont-cs','cont-cs.mkii',
- 'cont-ro','cont-ro.mkii',
- 'cont-gb','cont-gb.mkii'] .each do |f| @@texmethods[f] = 'context' end
- ['latex','latex.ltx','pdflatex'] .each do |f| @@texmethods[f] = 'latex' end # untested
-
- ['plain','default','standard'] .each do |f| @@mpsmethods[f] = 'plain' end
- ['metafun'] .each do |f| @@mpsmethods[f] = 'metafun' end
-
- @@texmakestr['plain'] = @@platformslash + "dump"
- @@mpsmakestr['plain'] = @@platformslash + "dump"
-
- ['cont-en','cont-nl','cont-de','cont-it',
- 'cont-fr','cont-cs','cont-ro','cont-gb',
- 'cont-pe','cont-xp'] .each do |f| @@texprocstr[f] = @@platformslash + "emergencyend" end
-
- @@runoptions['aleph'] = ['--8bit']
- @@runoptions['mpost'] = ['--8bit']
- @@runoptions['pdftex'] = ['--8bit']
- # @@runoptions['petex'] = []
- @@runoptions['xetex'] = ['--8bit','-output-driver="xdvipdfmx -E -d 4 -V 5"']
- @@draftoptions['pdftex'] = ['--draftmode']
- @@synctexcoptions['pdftex'] = ['--synctex=1']
- @@synctexcoptions['xetex'] = ['--synctex=1']
-
- @@mainbooleanvars = [
- 'batchmode', 'nonstopmode', 'fast', 'final',
- 'paranoid', 'notparanoid', 'nobanner', 'once', 'allpatterns', 'draft',
- 'nompmode', 'nomprun', 'automprun', 'combine',
- 'nomapfiles', 'local',
- 'arrange', 'noarrange',
- 'forcexml', 'foxet',
- 'alpha', 'beta',
- 'mpyforce', 'forcempy',
- 'forcetexutil', 'texutil',
- 'globalfile', 'autopath',
- 'purge', 'purgeall', 'keep', 'autopdf', 'xpdf', 'simplerun', 'verbose',
- 'nooptionfile', 'nobackend', 'noctx', 'utfbom',
- 'mkii','mkiv',
- 'synctex',
- ]
- @@mainstringvars = [
- 'modefile', 'result', 'suffix', 'response', 'path',
- 'filters', 'usemodules', 'environments', 'separation', 'setuppath',
- 'arguments', 'input', 'output', 'randomseed', 'modes', 'mode', 'filename',
- 'ctxfile', 'printformat', 'paperformat', 'paperoffset',
- 'timeout', 'passon', 'pdftitle'
- ]
- @@mainstandardvars = [
- 'mainlanguage', 'bodyfont', 'language'
- ]
- @@mainknownvars = [
- 'engine', 'distribution', 'texformats', 'mpsformats', 'progname', 'interface',
- 'runs', 'backend'
- ]
-
- @@extrabooleanvars = []
- @@extrastringvars = []
-
- def booleanvars
- [@@mainbooleanvars,@@extrabooleanvars].flatten.uniq
- end
- def stringvars
- [@@mainstringvars,@@extrastringvars].flatten.uniq
- end
- def standardvars
- [@@mainstandardvars].flatten.uniq
- end
- def knownvars
- [@@mainknownvars].flatten.uniq
- end
- def allbooleanvars
- [@@mainbooleanvars,@@extrabooleanvars].flatten.uniq
- end
- def allstringvars
- [@@mainstringvars,@@extrastringvars,@@mainstandardvars,@@mainknownvars].flatten.uniq
- end
-
- def setextrastringvars(vars)
- # @@extrastringvars << vars -- problems in 1.9
- @@extrastringvars = [@@extrastringvars,vars].flatten
- end
- def setextrabooleanvars(vars)
- # @@extrabooleanvars << vars -- problems in 1.9
- @@extrabooleanvars = [@@extrabooleanvars,vars].flatten
- end
-
- # def jobvariables(names=nil)
- # if [names ||[]].flatten.size == 0 then
- # names = [allbooleanvars,allstringvars].flatten
- # end
- # data = Hash.new
- # names.each do |name|
- # if allbooleanvars.include?(name) then
- # data[name] = if getvariable(name) then "yes" else "no" end
- # else
- # data[name] = getvariable(name)
- # end
- # end
- # data
- # end
-
- # def setjobvariables(names=nil)
- # assignments = Array.new
- # jobvariables(names).each do |k,v|
- # assignments << "#{k}=\{#{v}\}"
- # end
- # "\setvariables[exe][#{assignments.join(", ")}]"
- # end
-
- @@temprunfile = 'texexec'
- @@temptexfile = 'texexec.tex'
-
- def initialize(logger=nil)
- if @logger = logger then
- def report(str='')
- @logger.report(str)
- end
- else
- def report(str='')
- puts(str)
- end
- end
- @cleanups = Array.new
- @variables = Hash.new
- @startuptime = Time.now
- # options
- booleanvars.each do |k|
- setvariable(k,false)
- end
- stringvars.each do |k|
- setvariable(k,'')
- end
- standardvars.each do |k|
- setvariable(k,'standard')
- end
- setvariable('distribution', Kpse.distribution)
- setvariable('texformats', defaulttexformats)
- setvariable('mpsformats', defaultmpsformats)
- setvariable('progname', 'standard') # or ''
- setvariable('interface', 'standard')
- setvariable('engine', 'standard') # replaced by tex/mpsengine
- setvariable('backend', 'pdftex')
- setvariable('runs', '8')
- setvariable('randomseed', rand(1440).to_s) # we want the same seed for one run
- # files
- setvariable('files', [])
- # defaults
- setvariable('texengine', 'standard')
- setvariable('mpsengine', 'standard')
- setvariable('backend', 'standard')
- setvariable('error', '')
- end
-
- def error?
- not getvariable('error').empty?
- end
-
- def runtime
- Time.now - @startuptime
- end
-
- def reportruntime
- report("runtime: #{runtime}")
- end
-
- def runcommand(something)
- command = [something].flatten.join(' ')
- report("running: #{command}") if getvariable('verbose')
- system(command)
- end
-
- def inspect(name=nil)
- if ! name || name.empty? then
- name = [booleanvars,stringvars,standardvars,knownvars]
- end
- str = '' # allocate
- [name].flatten.each do |n|
- if str = getvariable(n) then
- str = str.join(" ") if str.class == Array
- unless (str.class == String) && str.empty? then
- report("option '#{n}' is set to '#{str}'")
- end
- end
- end
- end
-
- def tempfilename(suffix='')
- @@temprunfile + if suffix.empty? then '' else ".#{suffix}" end
- end
-
- def cleanup
- @cleanups.each do |name|
- begin
- File.delete(name) if FileTest.file?(name)
- rescue
- report("unable to delete #{name}")
- end
- end
- end
-
- def cleanuptemprunfiles
- begin
- Dir.glob("#{@@temprunfile}*").each do |name|
- if File.file?(name) && (File.splitname(name)[1] !~ /(pdf|dvi)/o) then
- File.delete(name) rescue false
- end
- end
- rescue
- end
- # ['mpgraph.mp'].each do |file|
- # (File.delete(file) if (FileTest.size?(file) rescue 10) < 10) rescue false
- # end
- end
-
- def backends() @@backends.keys.sort end
-
- def texengines() @@texengines.keys.sort end
- def mpsengines() @@mpsengines.keys.sort end
- def texformats() @@texformats.keys.sort end
- def mpsformats() @@mpsformats.keys.sort end
-
- def defaulttexformats() ['en','nl','mptopdf'] end
- def defaultmpsformats() ['metafun'] end # no longer formats
-
- def texmakeextras(format) @@texmakestr[format] || '' end
- def mpsmakeextras(format) @@mpsmakestr[format] || '' end
- def texprocextras(format) @@texprocstr[format] || '' end
- def mpsprocextras(format) @@mpsprocstr[format] || '' end
-
- def texmethod(format) @@texmethods[str] || @@texmethods['standard'] end
- def mpsmethod(format) @@mpsmethods[str] || @@mpsmethods['standard'] end
-
- def runoptions(engine)
- options = if getvariable('draft') then @@draftoptions[engine] else [] end
- options = if getvariable('synctex') then @@synctexcoptions[engine] else [] end
- begin
- if str = getvariable('passon') then
- options = [options,str.split(' ')].flatten
- end
- rescue
- end
- if @@runoptions.key?(engine) then
- [options,@@runoptions[engine]].flatten.join(' ')
- else
- options.join(' ')
- end
- end
-
- # private
-
- def cleanuplater(name)
- begin
- @cleanups.push(File.expand_path(name))
- rescue
- @cleanups.push(name)
- end
- end
-
- def openedfile(name)
- begin
- f = File.open(name,'w')
- rescue
- report("file '#{File.expand_path(name)}' cannot be opened for writing")
- return nil
- else
- cleanuplater(name) if f
- return f
- end
- end
-
- def prefixed(format,engine)
- # format
- case engine
- when /etex|pdftex|aleph|xetex/io then
- "*#{format}"
- else
- format
- end
- end
-
- def quoted(str)
- if str =~ /^[^\"].* / then "\"#{str}\"" else str end
- end
-
- def getarrayvariable(str='')
- str = getvariable(str)
- if str.class == String then str.split(',') else str.flatten end
- end
-
- def validsomething(str,something,type=nil)
- if str then
- list = [str].flatten.collect do |s|
- if something[s] then
- something[s]
- elsif type && s =~ /\.#{type}$/ then
- s
- else
- nil
- end
- end .compact.uniq
- if list.length>0 then
- if str.class == String then list.first else list end
- else
- false
- end
- else
- false
- end
- end
-
- def validtexformat(str) validsomething(str,@@texformats,'tex') ||
- validsomething(str,@@texformats,'mkii') end
- def validmpsformat(str) validsomething(str,@@mpsformats,'mp' ) end
- def validtexengine(str) validsomething(str,@@texengines,'pdftex') end
- def validmpsengine(str) validsomething(str,@@mpsengines,'mpost' ) end
-
- def validtexmethod(str) [validsomething(str,@@texmethods)].flatten.first end
- def validmpsmethod(str) [validsomething(str,@@mpsmethods)].flatten.first end
-
- def validbackend(str)
- if str && @@backends.key?(str) then
- @@backends[str]
- else
- @@backends['standard']
- end
- end
-
- def validprogname(str)
- if str then
- [str].flatten.each do |s|
- s = s.sub(/\.\S*/,"")
- return @@prognames[s] if @@prognames.key?(s)
- end
- return str[0].sub(/\.\S*/,"")
- else
- return nil
- end
- end
-
- # we no longer support the & syntax
-
- def formatflag(engine=nil,format=nil)
- case getvariable('distribution')
- when 'standard' then prefix = "--fmt"
- when /web2c/io then prefix = web2cformatflag(engine)
- when /miktex/io then prefix = "--undump"
- else return ""
- end
- if format then
- "#{prefix}=#{format.sub(/\.\S+$/,"")}"
- else
- prefix
- end
- end
-
- def web2cformatflag(engine=nil)
- # funny that we've standardized on the fmt suffix (at the cost of
- # upward compatibility problems) but stuck to the bas/mem/fmt flags
- if engine then
- case validmpsengine(engine)
- when /mpost/ then "-mem"
- when /mfont/ then "-bas"
- else "-fmt"
- end
- else
- "-fmt"
- end
- end
-
- def prognameflag(progname=nil)
- case getvariable('distribution')
- when 'standard' then prefix = "-progname"
- when /web2c/io then prefix = "-progname"
- when /miktex/io then prefix = "-alias"
- else return ""
- end
- if progname and not progname.empty? then
- "#{prefix}=#{progname}"
- else
- prefix
- end
- end
-
- def iniflag() # should go to kpse and kpse should become texenv
- if Kpse.miktex? then
- "-initialize"
- else
- "--ini"
- end
- end
-
- # # obsolete
- #
- # def tcxflag(engine)
- # if @@tcxflag[engine] then
- # file = "natural.tcx"
- # if Kpse.miktex? then
- # "-tcx=#{file}"
- # else
- # "-translate-file=#{file}"
- # end
- # else
- # ""
- # end
- # end
-
- def filestate(file)
- File.mtime(file).strftime("%d/%m/%Y %H:%M:%S")
- end
-
- # will go to context/process context/listing etc
-
- def contextversion # ook elders gebruiken
- filename = Kpse.found('context.mkii')
- version = 'unknown'
- begin
- if FileTest.file?(filename) && IO.read(filename).match(/\\contextversion\{(\d+\.\d+\.\d+.*?)\}/) then
- version = $1
- end
- rescue
- end
- return version
- end
-
- # we need engine methods
-
- def makeformats
-
- checktestversion
-
- report("using search method '#{Kpse.searchmethod}'")
- if getvariable('fast') then
- report('using existing database')
- else
- report('updating file database')
- Kpse.update # obsolete here
- end
- # goody
- if getvariable('texformats') == 'standard' then
- setvariable('texformats',[getvariable('interface')]) unless getvariable('interface').empty?
- end
- # prepare
- texformats = validtexformat(getarrayvariable('texformats'))
- mpsformats = validmpsformat(getarrayvariable('mpsformats'))
- texengine = validtexengine(getvariable('texengine'))
- mpsengine = validmpsengine(getvariable('mpsengine'))
- # save current path
- savedpath = Dir.getwd
- # generate tex formats
- unless texformats || mpsformats then
- report('provide valid format (name.tex, name.mp, ...) or format id (metafun, en, nl, ...)')
- setvariable('error','no format specified')
- end
- if texformats && texengine then
- report("using tex engine #{texengine}")
- texformatpath = if getvariable('local') then '.' else Kpse.formatpath(texengine,true) end
- # can be empty, to do
- report("using tex format path #{texformatpath}")
- Dir.chdir(texformatpath) rescue false
- if FileTest.writable?(texformatpath) then
- # from now on we no longer support this; we load
- # all patterns and if someone wants another
- # interface language ... cook up a fmt or usr file
- #
- # if texformats.length > 0 then
- # makeuserfile
- # makeresponsefile
- # end
- texformats.each do |texformat|
- report("generating tex format #{texformat}")
- progname = validprogname([getvariable('progname'),texformat,texengine])
- runcommand([quoted(texengine),prognameflag(progname),iniflag,prefixed(texformat,texengine),texmakeextras(texformat)])
- end
- else
- report("unable to make format due to lack of permissions")
- texformatpath = ''
- setvariable('error','no permissions to write')
- end
- if not mpsformats then
- # we want metafun to be in sync
- setvariable('mpsformats',defaultmpsformats)
- mpsformats = validmpsformat(getarrayvariable('mpsformats'))
- end
- else
- texformatpath = ''
- end
- # generate mps formats
- # if mpsformats && mpsengine then
- # report("using mp engine #{mpsengine}")
- # mpsformatpath = if getvariable('local') then '.' else Kpse.formatpath(mpsengine,false) end
- # report("using mps format path #{mpsformatpath}")
- # Dir.chdir(mpsformatpath) rescue false
- # if FileTest.writable?(mpsformatpath) then
- # mpsformats.each do |mpsformat|
- # report("generating mps format #{mpsformat}")
- # progname = validprogname([getvariable('progname'),mpsformat,mpsengine])
- # if not runcommand([quoted(mpsengine),prognameflag(progname),iniflag,runoptions(mpsengine),mpsformat,mpsmakeextras(mpsformat)]) then
- # setvariable('error','no format made')
- # end
- # end
- # else
- # report("unable to make format due to lack of permissions")
- # mpsformatpath = ''
- # setvariable('error','file permission problem')
- # end
- # else
- # mpsformatpath = ''
- # end
- # check for problems
- report("")
- report("tex engine path: #{texformatpath}") unless texformatpath.empty?
- # report("mps engine path: #{mpsformatpath}") unless mpsformatpath.empty?
- report("")
- # [['fmt','tex'],['mem','mps']].each do |f|
- # [[texformatpath,'global'],[mpsformatpath,'global'],[savedpath,'current']].each do |p|
- [['fmt','tex']].each do |f|
- [[texformatpath,'global'],[savedpath,'current']].each do |p|
- begin
- Dir.chdir(p[0])
- rescue
- else
- Dir.glob("*.#{f[0]}").each do |file|
- report("#{f[1]}: #{filestate(file)} > #{File.expand_path(file)} (#{File.size(file)})")
- end
- end
- end
- end
- # to be sure, go back to current path
- begin
- Dir.chdir(savedpath)
- rescue
- end
- # finalize
- cleanup
- report("")
- reportruntime
- end
-
- def checkcontext
-
- # todo : report texmf.cnf en problems
-
- # basics
- report("current distribution: #{Kpse.distribution}")
- report("context source date: #{contextversion}")
- formatpaths = Kpse.formatpaths
- globpattern = "**/{#{formatpaths.join(',')}}/*/*.{fmt,efmt,ofmt,xfmt,mem}"
- report("format path: #{formatpaths.join(' ')}")
- # utilities
- report('start of analysis')
- results = Array.new
- # ['texexec','texutil','ctxtools'].each do |program|
- ['texexec'].each do |program|
- result = `texmfstart #{program} --help`
- result.sub!(/.*?(#{program}[^\n]+)\n.*/mi) do $1 end
- results.push("#{result}")
- end
- # formats
- cleanuptemprunfiles
- if formats = Dir.glob(globpattern) then
- formats.sort.each do |name|
- cleanuptemprunfiles
- if f = open(tempfilename('tex'),'w') then
- # kind of aleph-run-out-of-par safe
- f << "\\starttext\n"
- f << " \\relax test \\relax\n"
- f << "\\stoptext\n"
- f << "\\endinput\n"
- f.close
- if FileTest.file?(tempfilename('tex')) then
- format = File.basename(name)
- engine = if name =~ /(pdftex|aleph|xetex)[\/\\]#{format}/ then $1 else '' end
- if engine.empty? then
- engineflag = ""
- else
- engineflag = "--engine=#{$1}"
- end
- case format
- when /cont\-([a-z]+)/ then
- interface = $1.sub(/cont\-/,'')
- results.push('')
- results.push("testing interface #{interface}")
- flags = ['--noctx','--process','--batch','--once',"--interface=#{interface}",engineflag]
- # result = Kpse.pipescript('texexec',tempfilename,flags)
- result = runtexexec([tempfilename], flags, 1)
- if FileTest.file?("#{@@temprunfile}.log") then
- logdata = IO.read("#{@@temprunfile}.log")
- if logdata =~ /^\s*This is (.*?)[\s\,]+(.*?)$/moi then
- if validtexengine($1.downcase) then
- results.push("#{$1} #{$2.gsub(/\(format.*$/,'')}".strip)
- end
- end
- if logdata =~ /^\s*(ConTeXt)\s+(.*int:\s+[a-z]+.*?)\s*$/moi then
- results.push("#{$1} #{$2}".gsub(/\s+/,' ').strip)
- end
- else
- results.push("format #{format} does not work")
- end
- when /metafun/ then
- # todo
- when /mptopdf/ then
- # todo
- end
- else
- results.push("error in creating #{tempfilename('tex')}")
- end
- end
- cleanuptemprunfiles
- end
- end
- report('end of analysis')
- report
- results.each do |line|
- report(line)
- end
- cleanuptemprunfiles
-
- end
-
- private
-
- def makeuserfile
- language = getvariable('language')
- mainlanguage = getvariable('mainlanguage')
- bodyfont = getvariable('bodyfont')
- if f = openedfile("cont-fmt.tex") then
- f << "\\unprotect\n"
- case language
- when 'all' then
- f << "\\preloadallpatterns\n"
- when '' then
- f << "% no language presets\n"
- when 'standard'
- f << "% using defaults\n"
- else
- languages = language.split(',')
- languages.each do |l|
- f << "\\installlanguage[\\s!#{l}][\\c!state=\\v!start]\n"
- end
- mainlanguage = languages.first
- end
- unless mainlanguage == 'standard' then
- f << "\\setupcurrentlanguage[\\s!#{mainlanguage}]\n";
- end
- unless bodyfont == 'standard' then
- # ~ will become obsolete when lmr is used
- f << "\\definetypescriptsynonym[cmr][#{bodyfont}]"
- # ~ is already obsolete for some years now
- f << "\\definefilesynonym[font-cmr][font-#{bodyfont}]\n"
- end
- f << "\\protect\n"
- f << "\\endinput\n"
- f.close
- end
- end
-
- def makeresponsefile
- interface = getvariable('interface')
- if f = openedfile("mult-def.tex") then
- case interface
- when 'standard' then
- f << "% using default response interface"
- else
- f << "\\def\\currentresponses\{#{interface}\}\n"
- end
- f << "\\endinput\n"
- f.close
- end
- end
-
- private # will become base/context
-
- @@preamblekeys = [
- ['tex','texengine'],
- ['engine','texengine'],
- ['program','texengine'],
- # ['translate','tcxfilter'],
- # ['tcx','tcxfilter'],
- ['output','backend'],
- ['mode','mode'],
- ['ctx','ctxfile'],
- ['version','contextversion'],
- ['format','texformats'],
- ['interface','texformats'],
- ]
-
- @@re_utf_bom = /^\357\273\277/o
-
- def scantexpreamble(filename)
- begin
- if FileTest.file?(filename) and tex = File.open(filename,'rb') then
- bomdone = false
- while str = tex.gets and str.chomp! do
- unless bomdone then
- if str.sub!(@@re_utf_bom, '')
- report("utf mode forced (bom found)")
- setvariable('utfbom',true)
- end
- bomdone = true
- end
- if str =~ /^\%\s*(.*)/o then
- # we only accept lines with key=value pairs
- vars, ok = Hash.new, true
- $1.split(/\s+/o).each do |s|
- k, v = s.split('=')
- if k && v then
- vars[k] = v
- else
- ok = false
- break
- end
- end
- if ok then
- # we have a valid line
-
- @@preamblekeys.each do |v|
- setvariable(v[1],vars[v[0]]) if vars.key?(v[0]) && vars[v[0]]
- end
-
-if getvariable('given.backend') == "standard" or getvariable('given.backend') == "" then
- setvariable('backend',@@backends[getvariable('texengine')] || 'standard')
-end
- break
- end
- else
- break
- end
- end
- tex.close
- end
- rescue
- # well, let's not worry too much
- end
- end
-
- def scantexcontent(filename)
- if FileTest.file?(filename) and tex = File.open(filename,'rb') then
- while str = tex.gets do
- case str.chomp
- when /^\%/o then
- # next
- # when /\\(starttekst|stoptekst|startonderdeel|startdocument|startoverzicht)/o then
- when /\\(starttekst|stoptekst|startonderdeel|startoverzicht)/o then
- setvariable('texformats','nl') ; break
- when /\\(stelle|verwende|umgebung|benutze)/o then
- setvariable('texformats','de') ; break
- when /\\(stel|gebruik|omgeving)/o then
- setvariable('texformats','nl') ; break
- when /\\(use|setup|environment)/o then
- setvariable('texformats','en') ; break
- when /\\(usa|imposta|ambiente)/o then
- setvariable('texformats','it') ; break
- when /(height|width|style)=/o then
- setvariable('texformats','en') ; break
- when /(hoehe|breite|schrift)=/o then
- setvariable('texformats','de') ; break
- when /(hoogte|breedte|letter)=/o then
- setvariable('texformats','nl') ; break
- when /(altezza|ampiezza|stile)=/o then
- setvariable('texformats','it') ; break
- when /externfiguur/o then
- setvariable('texformats','nl') ; break
- when /externalfigure/o then
- setvariable('texformats','en') ; break
- when /externeabbildung/o then
- setvariable('texformats','de') ; break
- when /figuraesterna/o then
- setvariable('texformats','it') ; break
- end
- end
- tex.close
- end
-
- end
-
- private # will become base/context
-
- def pushresult(filename,resultname)
- fname = File.unsuffixed(filename)
- rname = File.unsuffixed(resultname)
- if ! rname.empty? && (rname != fname) then
- report("outputfile #{rname}")
- ['tuo','tuc','log','dvi','pdf'].each do |s|
- File.silentrename(File.suffixed(fname,s),File.suffixed('texexec',s))
- end
- ['tuo','tuc'].each do |s|
- File.silentrename(File.suffixed(rname,s),File.suffixed(fname,s)) if FileTest.file?(File.suffixed(rname,s))
- end
- end
- end
-
- def popresult(filename,resultname)
- fname = File.unsuffixed(filename)
- rname = File.unsuffixed(resultname)
- if ! rname.empty? && (rname != fname) then
- report("renaming #{fname} to #{rname}")
- ['tuo','tuc','log','dvi','pdf'].each do |s|
- File.silentrename(File.suffixed(fname,s),File.suffixed(rname,s))
- end
- report("restoring #{fname}")
- unless $fname == 'texexec' then
- ['tuo','tuc','log','dvi','pdf'].each do |s|
- File.silentrename(File.suffixed('texexec',s),File.suffixed(fname,s))
- end
- end
- end
- end
-
- def makestubfile(rawname,rawbase,forcexml=false)
- if tmp = openedfile(File.suffixed(rawbase,'run')) then
- tmp << "\\starttext\n"
- if forcexml then
- # tmp << checkxmlfile(rawname)
- if getvariable('mkiv') then
- tmp << "\\xmlprocess{\\xmldocument}{#{rawname}}{}\n"
- else
- tmp << "\\processXMLfilegrouped{#{rawname}}\n"
- end
- else
- tmp << "\\processfile{#{rawname}}\n"
- end
- tmp << "\\stoptext\n"
- tmp.close
- return "run"
- else
- return File.splitname(rawname)[1]
- end
- end
-
- # def checkxmlfile(rawname)
- # tmp = ''
- # if FileTest.file?(rawname) && (xml = File.open(rawname)) then
- # xml.each do |line|
- # case line
- # when /<\?context\-directive\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*?)\s*\?>/o then
- # category, key, value, rest = $1, $2, $3, $4
- # case category
- # when 'job' then
- # case key
- # when 'control' then
- # setvariable(value,if rest.empty? then true else rest end)
- # when 'mode', 'modes' then
- # tmp << "\\enablemode[#{value}]\n"
- # when 'stylefile', 'environment' then
- # tmp << "\\environment #{value}\n"
- # when 'module' then
- # tmp << "\\usemodule[#{value}]\n"
- # when 'interface' then
- # contextinterface = value
- # when 'ctxfile' then
- # setvariable('ctxfile', value)
- # report("using source driven ctxfile #{value}")
- # end
- # end
- # when /<[a-z]+/io then # beware of order, first pi test
- # break
- # end
- # end
- # xml.close
- # end
- # return tmp
- # end
-
- def extendvariable(name,value)
- set = getvariable(name).split(',')
- set << value
- str = set.uniq.join(',')
- setvariable(name,str)
- end
-
- def checkxmlfile(rawname)
- if FileTest.file?(rawname) && (xml = File.open(rawname,'rb')) then
- xml.each do |line|
- case line
- when /<\?context\-directive\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*?)\s*\?>/o then
- category, key, value, rest = $1, $2, $3, $4
- case category
- when 'job' then
- case key
- when 'control' then
- setvariable(value,if rest.empty? then true else rest end)
- when /^(mode)(s|)$/ then
- extendvariable('modes',value)
- when /^(stylefile|environment)(s|)$/ then
- extendvariable('environments',value)
- when /^(use|)(module)(s|)$/ then
- extendvariable('usemodules',value)
- when /^(filter)(s|)$/ then
- extendvariable('filters',value)
- when 'interface' then
- contextinterface = value
- when 'ctxfile' then
- setvariable('ctxfile', value)
- report("using source driven ctxfile #{value}")
- end
- end
- when /<[a-z]+/io then # beware of order, first pi test
- break
- end
- end
- xml.close
- end
- end
-
-end
-
-class TEX
-
- def timedrun(delay, &block)
- delay = delay.to_i rescue 0
- if delay > 0 then
- begin
- report("job started with timeout '#{delay}'")
- timeout(delay) do
- yield block
- end
- rescue TimeoutError
- report("job aborted due to timeout '#{delay}'")
- setvariable('error','timeout')
- rescue
- report("job aborted due to error")
- setvariable('error','fatal error')
- else
- report("job finished within timeout '#{delay}'")
- end
- else
- yield block
- end
- end
-
- def processtex # much to do: mp, xml, runs etc
- setvariable('texformats',[getvariable('interface')]) unless getvariable('interface').empty?
- getarrayvariable('files').each do |filename|
- setvariable('filename',filename)
- report("processing document '#{filename}'")
- timedrun(getvariable('timeout')) do
- processfile
- end
- end
- reportruntime
- end
-
- def processmptex
- getarrayvariable('files').each do |filename|
- setvariable('filename',filename)
- report("processing graphic '#{filename}'")
- runtexmp(filename)
- end
- reportruntime
- end
-
- private
-
- def load_map_files(filename) # tui basename
- # c \usedmapfile{=}{lm-texnansi}
- begin
- str = ""
- IO.read(filename).scan(/^c\s+\\usedmapfile\{(.*?)\}\{(.*?)\}\s*$/o) do
- str << "\\loadmapfile[#{$2}.map]\n"
- end
- rescue
- return ""
- else
- return str
- end
- end
-
- public
-
- def processmpgraphic
- getarrayvariable('files').each do |filename|
- setvariable('filename',filename)
- report("processing graphic '#{filename}'")
- runtexmp(filename,'',false) # no purge
- mapspecs = load_map_files(File.suffixed(filename,'temp','tui'))
- unless getvariable('keep') then
- # not enough: purge_mpx_files(filename)
- Dir.glob(File.suffixed(filename,'temp*','*')).each do |fname|
- File.delete(fname) unless File.basename(filename) == File.basename(fname)
- end
- end
- begin
- data = IO.read(File.suffixed(filename,'log'))
- basename = filename.sub(/\.mp$/, '')
- if data =~ /output files* written\:\s*(.*)$/moi then
- files, number, range, list = $1.split(/\s+/), 0, false, []
- files.each do |fname|
- if fname =~ /^.*\.(\d+)$/ then
- if range then
- (number+1 .. $1.to_i).each do |i|
- list << i
- end
- range = false
- else
- number = $1.to_i
- list << number
- end
- elsif fname =~ /\.\./ then
- range = true
- else
- range = false
- next
- end
- end
- begin
- if getvariable('combine') then
- fullname = "#{basename}.#{number}"
- File.open("texexec.tex",'w') do |f|
- f << "\\setupoutput[pdftex]\n"
- f << "\\setupcolors[state=start]\n"
- f << mapspecs
- f << "\\starttext\n"
- list.each do |number|
- f << "\\startTEXpage\n"
- f << "\\convertMPtoPDF{#{fullname}}{1}{1}"
- f << "\\stopTEXpage\n"
- end
- f << "\\stoptext\n"
- end
- report("converting graphic '#{fullname}'")
- runtex("texexec.tex")
- pdffile = File.suffixed(basename,'pdf')
- File.silentrename("texexec.pdf",pdffile)
- report ("#{basename}.* converted to #{pdffile}")
- else
- list.each do |number|
- begin
- fullname = "#{basename}.#{number}"
- File.open("texexec.tex",'w') do |f|
- f << "\\setupoutput[pdftex]\n"
- f << "\\setupcolors[state=start]\n"
- f << mapspecs
- f << "\\starttext\n"
- f << "\\startTEXpage\n"
- f << "\\convertMPtoPDF{#{fullname}}{1}{1}"
- f << "\\stopTEXpage\n"
- f << "\\stoptext\n"
- end
- report("converting graphic '#{fullname}'")
- runtex("texexec.tex")
- if files.length>1 then
- pdffile = File.suffixed(basename,number.to_s,'pdf')
- else
- pdffile = File.suffixed(basename,'pdf')
- end
- File.silentrename("texexec.pdf",pdffile)
- report ("#{fullname} converted to #{pdffile}")
- end
- end
- end
- rescue
- report ("error when converting #{fullname} (#{$!})")
- end
- end
- rescue
- report("error in converting #{filename}")
- end
- end
- reportruntime
- end
-
- def processmpstatic
- if filename = getvariable('filename') then
- filename += ".mp" unless filename =~ /\..+?$/
- if FileTest.file?(filename) then
- begin
- data = IO.read(filename)
- File.open("texexec.tex",'w') do |f|
- f << "\\setupoutput[pdftex]\n"
- f << "\\setupcolors[state=start]\n"
- data.sub!(/^%mpenvironment\:\s*(.*?)$/moi) do
- f << $1
- "\n"
- end
- f << "\\starttext\n"
- f << "\\startMPpage\n"
- f << data.gsub(/end\.*\s*$/m, '') # a bit of a hack
- f << "\\stopMPpage\n"
- f << "\\stoptext\n"
- end
- report("converting static '#{filename}'")
- runtex("texexec.tex")
- pdffile = File.suffixed(filename,'pdf')
- File.silentrename("texexec.pdf",pdffile)
- report ("#{filename} converted to #{pdffile}")
- rescue
- report("error in converting #{filename} (#{$!}")
- end
- end
- end
- reportruntime
- end
-
- def processmpxtex
- getarrayvariable('files').each do |filename|
- setvariable('filename',filename)
- report("processing text of graphic '#{filename}'")
- processmpx(filename,false,true,true)
- end
- reportruntime
- end
-
- def deleteoptionfile(rawname)
- ['top','top.keep'].each do |suffix|
- begin
- File.delete(File.suffixed(rawname,suffix))
- rescue
- end
- end
- end
-
- def makeoptionfile(rawname, jobname, jobsuffix, finalrun, fastdisabled, kindofrun, currentrun=1)
- begin
- # jobsuffix = orisuffix
- if topname = File.suffixed(rawname,'top') and opt = File.open(topname,'w') then
- report("writing option file #{topname}")
- # local handies
- opt << "\% #{topname}\n"
- opt << "\\unprotect\n"
- #
- # feedback and basic control
- #
- if getvariable('batchmode') then
- opt << "\\batchmode\n"
- end
- if getvariable('nonstopmode') then
- opt << "\\nonstopmode\n"
- end
- if getvariable('paranoid') then
- opt << "\\def\\maxreadlevel{1}\n"
- end
- if getvariable('nomapfiles') then
- opt << "\\disablemapfiles\n"
- end
- if getvariable('nompmode') || getvariable('nomprun') || getvariable('automprun') then
- opt << "\\runMPgraphicsfalse\n"
- end
- if getvariable('utfbom') then
- opt << "\\enableregime[utf]"
- end
- progname = validprogname(['metafun']) # [getvariable('progname'),mpsformat,mpsengine]
- opt << "\\def\\MPOSTformatswitch\{#{prognameflag(progname)} #{formatflag('mpost')}=\}\n"
- #
- # process info
- #
- opt << "\\setupsystem[\\c!n=#{kindofrun},\\c!m=#{currentrun}]\n"
- if (str = File.unixfied(getvariable('modefile'))) && ! str.empty? then
- opt << "\\readlocfile{#{str}}{}{}\n"
- end
- if (str = File.unixfied(getvariable('result'))) && ! str.empty? then
- opt << "\\setupsystem[file=#{str}]\n"
- elsif (str = getvariable('suffix')) && ! str.empty? then
- opt << "\\setupsystem[file=#{jobname}.#{str}]\n"
- end
- opt << "\\setupsystem[\\c!method=2]\n" # 1=oldtexexec 2=newtexexec (obsolete)
- opt << "\\setupsystem[\\c!type=#{Tool.ruby_platform()}]\n"
- if (str = File.unixfied(getvariable('path'))) && ! str.empty? then
- opt << "\\usepath[#{str}]\n" unless str.empty?
- end
- if (str = getvariable('mainlanguage').downcase) && ! str.empty? && ! str.standard? then
- opt << "\\setuplanguage[#{str}]\n"
- end
- if (str = getvariable('arguments')) && ! str.empty? then
- opt << "\\setupenv[#{str}]\n"
- end
- if (str = getvariable('setuppath')) && ! str.empty? then
- opt << "\\setupsystem[\\c!directory=\{#{str}\}]\n"
- end
- if (str = getvariable('randomseed')) && ! str.empty? then
- report("using randomseed #{str}")
- opt << "\\setupsystem[\\c!random=#{str}]\n"
- end
- if (str = getvariable('input')) && ! str.empty? then
- opt << "\\setupsystem[inputfile=#{str}]\n"
- else
- opt << "\\setupsystem[inputfile=#{rawname}]\n"
- end
- #
- # modes
- #
- # we handle both "--mode" and "--modes", else "--mode" is mapped onto "--modefile"
- if (str = getvariable('modes')) && ! str.empty? then
- opt << "\\enablemode[#{str}]\n"
- end
- if (str = getvariable('mode')) && ! str.empty? then
- opt << "\\enablemode[#{str}]\n"
- end
- #
- # options
- #
- opt << "\\startsetups *runtime:options\n"
- if str = validbackend(getvariable('backend')) then
- opt << "\\setupoutput[#{str}]\n"
- elsif str = validbackend(getvariable('output')) then
- opt << "\\setupoutput[#{str}]\n"
- end
- if getvariable('color') then
- opt << "\\setupcolors[\\c!state=\\v!start]\n"
- end
- if (str = getvariable('separation')) && ! str.empty? then
- opt << "\\setupcolors[\\c!split=#{str}]\n"
- end
- if (str = getvariable('paperformat')) && ! str.empty? && ! str.standard? then
- if str =~ /^([a-z]+\d+)([a-z]+\d+)$/io then # A5A4 A4A3 A2A1 ...
- opt << "\\setuppapersize[#{$1.upcase}][#{$2.upcase}]\n"
- else # ...*...
- pf = str.upcase.split(/[x\*]/o)
- pf << pf[0] if pf.size == 1
- opt << "\\setuppapersize[#{pf[0]}][#{pf[1]}]\n"
- end
- end
- if (str = getvariable('background')) && ! str.empty? then
- opt << "\\defineoverlay[whatever][{\\externalfigure[#{str}][\\c!factor=\\v!max]}]\n"
- opt << "\\setupbackgrounds[\\v!page][\\c!background=whatever]\n"
- end
- if getvariable('centerpage') then
- opt << "\\setuplayout[\\c!location=\\v!middle,\\c!marking=\\v!on]\n"
- end
- if getvariable('noarrange') then
- opt << "\\setuparranging[\\v!disable]\n"
- elsif getvariable('arrange') then
- arrangement = Array.new
- if finalrun then
- arrangement << "\\v!doublesided" unless getvariable('noduplex')
- case getvariable('printformat')
- when '' then arrangement << "\\v!normal"
- when /.*up/oi then arrangement << ["2UP","\\v!rotated"]
- when /.*down/oi then arrangement << ["2DOWN","\\v!rotated"]
- when /.*side/oi then arrangement << ["2SIDE","\\v!rotated"]
- end
- else
- arrangement << "\\v!disable"
- end
- opt << "\\setuparranging[#{arrangement.flatten.join(',')}]\n" if arrangement.size > 0
- end
- if (str = getvariable('pages')) && ! str.empty? then
- if str.downcase == 'odd' then
- opt << "\\chardef\\whichpagetoshipout=1\n"
- elsif str.downcase == 'even' then
- opt << "\\chardef\\whichpagetoshipout=2\n"
- else
- pagelist = Array.new
- str.split(/\,/).each do |page|
- pagerange = page.split(/\D+/o)
- if pagerange.size > 1 then
- pagerange.first.to_i.upto(pagerange.last.to_i) do |p|
- pagelist << p.to_s
- end
- else
- pagelist << page
- end
- end
- opt << "\\def\\pagestoshipout\{#{pagelist.join(',')}\}\n";
- end
- end
- opt << "\\stopsetups\n"
- #
- # styles and modules
- #
- opt << "\\startsetups *runtime:modules\n"
- begin getvariable('filters' ).split(',').uniq.each do |f| opt << "\\useXMLfilter[#{f}]\n" end ; rescue ; end
- begin getvariable('usemodules' ).split(',').uniq.each do |m| opt << "\\usemodule [#{m}]\n" end ; rescue ; end
- begin getvariable('environments').split(',').uniq.each do |e| opt << "\\environment #{e} \n" end ; rescue ; end
- opt << "\\stopsetups\n"
- #
- opt << "\\protect \\endinput\n"
- #
- opt.close
- else
- report("unable to write option file #{topname}")
- end
- rescue
- report("fatal error in writing option file #{topname} (#{$!})")
- end
- end
-
- def takeprecautions
- ENV['MPXCOMAND'] = '0' # else loop
- if getvariable('paranoid') then
- ENV['SHELL_ESCAPE'] = ENV['SHELL_ESCAPE'] || 'f'
- ENV['OPENOUT_ANY'] = ENV['OPENOUT_ANY'] || 'p'
- ENV['OPENIN_ANY'] = ENV['OPENIN_ANY'] || 'p'
- elsif getvariable('notparanoid') then
- ENV['SHELL_ESCAPE'] = ENV['SHELL_ESCAPE'] || 't'
- ENV['OPENOUT_ANY'] = ENV['OPENOUT_ANY'] || 'a'
- ENV['OPENIN_ANY'] = ENV['OPENIN_ANY'] || 'a'
- end
- if ENV['OPENIN_ANY'] && (ENV['OPENIN_ANY'] == 'p') then # first test redundant
- setvariable('paranoid', true)
- end
- if ENV.key?('SHELL_ESCAPE') && (ENV['SHELL_ESCAPE'] == 'f') then
- setvariable('automprun',true)
- end
- done = false
- ['TXRESOURCES','MPRESOURCES','MFRESOURCES'].each do |res|
- [getvariable('runpath'),getvariable('path')].each do |pat|
- unless pat.empty? then
- if ENV.key?(res) then
- # ENV[res] = if ENV[res].empty? then pat else pat + ":" + ENV[res] end
-if ENV[res].empty? then
- ENV[res] = pat
-elsif ENV[res] == pat || ENV[res] =~ /^#{pat}\:/ || ENV[res] =~ /\:#{pat}\:/ then
- # skip
-else
- ENV[res] = pat + ":" + ENV[res]
-end
- else
- ENV[res] = pat
- end
- report("setting #{res} to #{ENV[res]}") unless done
- end
- end
- done = true
- end
- end
-
- def checktestversion
- #
- # one can set TEXMFALPHA and TEXMFBETA for test versions
- # but keep in mind that the format as well as the test files
- # then need the --alpha or --beta flag
- #
- done, tree = false, ''
- ['alpha', 'beta'].each do |what|
- if getvariable(what) then
- if ENV["TEXMF#{what.upcase}"] then
- done, tree = true, ENV["TEXMF#{what.upcase}"]
- elsif ENV["TEXMFLOCAL"] then
- done, tree = true, File.join(File.dirname(ENV['TEXMFLOCAL']), "texmf-#{what}")
- end
- end
- break if done
- end
- if done then
- tree = tree.strip
- ENV['TEXMFPROJECT'] = tree
- report("using test tree '#{tree}'")
- ['MP', 'MF', 'TX'].each do |ctx|
- ENV['CTXDEV#{ctx}PATH'] = ''
- end
- unless (FileTest.file?(File.join(tree,'ls-r')) || FileTest.file?(File.join(tree,'ls-R'))) then
- report("no ls-r/ls-R file for tree '#{tree}' (run: mktexlsr #{tree})")
- end
- end
- # puts `kpsewhich --expand-path=$TEXMF`
- # exit
- end
-
- def runtex(filename)
- checktestversion
- texengine = validtexengine(getvariable('texengine'))
- texformat = validtexformat(getarrayvariable('texformats').first)
- report("tex engine: #{texengine}")
- report("tex format: #{texformat}")
- if texengine && texformat then
- fixbackendvars(@@mappaths[texengine])
- progname = validprogname([getvariable('progname'),texformat,texengine])
- runcommand([quoted(texengine),prognameflag(progname),formatflag(texengine,texformat),runoptions(texengine),filename,texprocextras(texformat)])
- else
- false
- end
- end
-
- def runmp(mpname,mpx=false)
- checktestversion
- mpsengine = validmpsengine(getvariable('mpsengine'))
- mpsformat = validmpsformat(getarrayvariable('mpsformats').first)
- if mpsengine && mpsformat then
- ENV["MPXCOMMAND"] = "0" unless mpx
- progname = validprogname([getvariable('progname'),mpsformat,mpsengine])
- mpname.gsub!(/\.mp$/,"") # temp bug in mp
- runcommand([quoted(mpsengine),prognameflag(progname),formatflag(mpsengine,mpsformat),runoptions(mpsengine),mpname,mpsprocextras(mpsformat)])
- true
- else
- false
- end
- end
-
- def runtexmp(filename,filetype='',purge=true)
- checktestversion
- mpname = File.suffixed(filename,filetype,'mp')
- if File.atleast?(mpname,10) then
- # first run needed
- File.silentdelete(File.suffixed(mpname,'mpt'))
- doruntexmp(mpname,nil,true,purge)
- mpgraphics = checkmpgraphics(mpname)
- mplabels = checkmplabels(mpname)
- if mpgraphics || mplabels then
- # second run needed
- doruntexmp(mpname,mplabels,true,purge)
- else
- # no labels
- end
- end
- end
-
- def runtexmpjob(filename,filetype='')
- checktestversion
- mpname = File.suffixed(filename,filetype,'mp')
- if File.atleast?(mpname,25) && (data = File.silentread(mpname)) then
- textranslation = if data =~ /^\%\s+translate.*?\=([\w\d\-]+)/io then $1 else '' end
- mpjobname = if data =~ /collected graphics of job \"(.+?)\"/io then $1 else '' end
- if ! mpjobname.empty? and File.unsuffixed(filename) =~ /#{mpjobname}/ then # don't optimize
- options = Array.new
- options.push("--mptex")
- options.push("--nomp")
- options.push("--mpyforce") if getvariable('forcempy') || getvariable('mpyforce')
- options.push("--translate=#{textranslation}") unless textranslation.empty?
- options.push("--batch") if getvariable('batchmode')
- options.push("--nonstop") if getvariable('nonstopmode')
- options.push("--output=ps") # options.push("--dvi")
- options.push("--nobackend")
- return runtexexec(mpname,options,2)
- end
- end
- return false
- end
-
- def runtexutil(filename=[], options=['--ref','--ij','--high'], old=false)
- [filename].flatten.each do |fname|
- if old then
- Kpse.runscript('texutil',fname,options)
- else
- begin
- logger = Logger.new('TeXUtil')
- if tu = TeXUtil::Converter.new(logger) and tu.loaded(fname) then
- ok = tu.processed && tu.saved && tu.finalized
- end
- rescue
- Kpse.runscript('texutil',fname,options)
- end
- end
- end
- end
-
- # 1=tex 2=mptex 3=mpxtex 4=mpgraphic 5=mpstatic
-
- def runtexexec(filename=[], options=[], mode=nil)
- begin
- if mode and job = TEX.new(@logger) then
- options.each do |option|
- case option
- when /^\-*(.*?)\=(.*)$/o then
- job.setvariable($1,$2)
- when /^\-*(.*?)$/o then
- job.setvariable($1,true)
- end
- end
- job.setvariable("files",filename)
- case mode
- when 1 then job.processtex
- when 2 then job.processmptex
- when 3 then job.processmpxtex
- when 4 then job.processmpgraphic
- when 5 then job.processmpstatic
- end
- job.inspect && Kpse.inspect if getvariable('verbose')
- return true
- else
- Kpse.runscript('texexec',filename,options)
- end
- rescue
- Kpse.runscript('texexec',filename,options)
- end
- end
-
- def fixbackendvars(backend)
- if backend then
- ENV['backend'] = backend ;
- ENV['progname'] = backend unless validtexengine(backend)
- ENV['TEXFONTMAPS'] = ['.',"\$TEXMF/fonts/{data,map}/{#{backend},pdftex,dvips,}//",'./fonts//'].join_path
- report("fixing backend map path for #{backend}: #{ENV['TEXFONTMAPS']}") if getvariable('verbose')
- else
- report("unable to fix backend map path") if getvariable('verbose')
- end
- end
-
- def runbackend(rawname)
- unless getvariable('nobackend') then
- case validbackend(getvariable('backend'))
- when 'dvipdfmx' then
- fixbackendvars('dvipdfm')
- runcommand("dvipdfmx -d 4 -V 5 #{File.unsuffixed(rawname)}")
- when 'xetex' then
- # xetex now runs its own backend
- xdvfile = File.suffixed(rawname,'xdv')
- if FileTest.file?(xdvfile) then
- fixbackendvars('dvipdfm')
- runcommand("xdvipdfmx -q -d 4 -V 5 -E #{xdvfile}")
- end
- when 'xdv2pdf' then
- xdvfile = File.suffixed(rawname,'xdv')
- if FileTest.file?(xdvfile) then
- fixbackendvars('xdv2pdf')
- runcommand("xdv2pdf #{xdvfile}")
- end
- when 'dvips' then
- fixbackendvars('dvips')
- mapfiles = ''
- begin
- if tuifile = File.suffixed(rawname,'tui') and FileTest.file?(tuifile) then
- IO.read(tuifile).scan(/^c \\usedmapfile\{.\}\{(.*?)\}\s*$/o) do
- mapfiles += "-u +#{$1} " ;
- end
- end
- rescue
- mapfiles = ''
- end
- runcommand("dvips #{mapfiles} #{File.unsuffixed(rawname)}")
- when 'pdftex' then
- # no need for postprocessing
- else
- report("no postprocessing needed")
- end
- end
- end
-
- def processfile
-
- takeprecautions
- report("using search method '#{Kpse.searchmethod}'") if getvariable('verbose')
-
- rawname = getvariable('filename')
- jobname = getvariable('filename')
-
- if getvariable('autopath') then
- jobname = File.basename(jobname)
- inppath = File.dirname(jobname)
- else
- inppath = ''
- end
-
- jobname, jobsuffix = File.splitname(jobname,'tex')
-
- jobname = File.unixfied(jobname)
- inppath = File.unixfied(inppath)
-
- orisuffix = jobsuffix # still needed ?
-
- if jobsuffix =~ /^(htm|html|xhtml|xml|fo|fox|rlg|exa)$/io then
- setvariable('forcexml',true)
- end
-
- dummyfile = false
-
- # fuzzy code snippet: (we kunnen kpse: prefix gebruiken)
-
- unless FileTest.file?(File.suffixed(jobname,jobsuffix)) then
- if FileTest.file?(rawname + '.tex') then
- jobname = rawname.dup
- jobsuffix = 'tex'
- end
- end
-
- # we can have funny names, like 2005.10.10 (given without suffix)
-
- rawname = jobname + '.' + jobsuffix
- rawpath = File.dirname(rawname)
- rawbase = File.basename(rawname)
-
- unless FileTest.file?(rawname) then
- inppath.split(',').each do |ip|
- break if dummyfile = FileTest.file?(File.join(ip,rawname))
- end
- end
-
- forcexml = getvariable('forcexml')
-
- if dummyfile || forcexml then # after ctx?
- jobsuffix = makestubfile(rawname,rawbase,forcexml)
- checkxmlfile(rawname)
- end
-
- # preprocess files
-
- unless getvariable('noctx') then
- ctx = CtxRunner.new(rawname,@logger)
- if pth = getvariable('path') then
- pth.split(',').each do |p|
- ctx.register_path(p)
- end
- end
- if getvariable('ctxfile').empty? then
- if rawname == rawbase then
- ctx.manipulate(File.suffixed(rawname,'ctx'),'jobname.ctx')
- else
- ctx.manipulate(File.suffixed(rawname,'ctx'),File.join(rawpath,'jobname.ctx'))
- end
- else
- ctx.manipulate(File.suffixed(getvariable('ctxfile'),'ctx'))
- end
- ctx.savelog(File.suffixed(rawbase,'ctl'))
-
- envs = ctx.environments
- mods = ctx.modules
- flags = ctx.flags
- mdes = ctx.modes
-
- flags.each do |f|
- f.sub!(/^\-+/,'')
- if f =~ /^(.*?)=(.*)$/ then
- setvariable($1,$2)
- else
- setvariable(f,true)
- end
- end
-
- report("using flags #{flags.join(' ')}") if flags.size > 0
-
- # merge environment and module specs
-
- envs << getvariable('environments') unless getvariable('environments').empty?
- mods << getvariable('usemodules') unless getvariable('usemodules') .empty?
- mdes << getvariable('modes') unless getvariable('modes') .empty?
-
- envs = envs.uniq.join(',')
- mods = mods.uniq.join(',')
- mdes = mdes.uniq.join(',')
-
- report("using search method '#{Kpse.searchmethod}'") if getvariable('verbose')
-
- report("using environments #{envs}") if envs.length > 0
- report("using modules #{mods}") if mods.length > 0
- report("using modes #{mdes}") if mdes.length > 0
-
- setvariable('environments', envs)
- setvariable('usemodules', mods)
- setvariable('modes', mdes)
- end
-
- # end of preprocessing and merging
-
- setvariable('nomprun',true) if orisuffix == 'mpx' # else cylic run
- PDFview.setmethod('xpdf') if getvariable('xpdf')
- PDFview.closeall if getvariable('autopdf')
-
- runonce = getvariable('once')
- finalrun = getvariable('final') || (getvariable('arrange') && ! getvariable('noarrange'))
- suffix = getvariable('suffix')
- result = getvariable('result')
- globalfile = getvariable('globalfile')
- forcexml = getvariable('forcexml') # can be set in ctx file
-
-if dummyfile || forcexml then # after ctx?
- jobsuffix = makestubfile(rawname,rawbase,forcexml)
- checkxmlfile(rawname)
-end
-
- result = File.unixfied(result)
-
- if globalfile || FileTest.file?(rawname) then
-
- if not dummyfile and not globalfile and not forcexml then
- scantexpreamble(rawname)
- scantexcontent(rawname) if getvariable('texformats').standard?
- end
- result = File.suffixed(rawname,suffix) unless suffix.empty?
-
- pushresult(rawbase,result)
-
- method = validtexmethod(validtexformat(getvariable('texformats')))
-
- report("tex processing method: #{method}")
-
- case method
-
- when 'context' then
- if getvariable('simplerun') || runonce then
- makeoptionfile(rawbase,jobname,orisuffix,true,true,3,1) unless getvariable('nooptionfile')
- ok = runtex(if dummyfile || forcexml then rawbase else rawname end)
- if ok then
- ok = runtexutil(rawbase) if getvariable('texutil') || getvariable('forcetexutil')
- runbackend(rawbase)
- popresult(rawbase,result)
- end
- if getvariable('keep') then
- ['top','log','run'].each do |suffix|
- File.silentrename(File.suffixed(rawbase,suffix),File.suffixed(rawbase,suffix+'.keep'))
- end
- end
- else
-# goto tmp/jobname when present
- mprundone, ok, stoprunning = false, true, false
- texruns, nofruns = 0, getvariable('runs').to_i
- state = FileState.new
- ['tub','tuo','tuc'].each do |s|
- state.register(File.suffixed(rawbase,s))
- end
- if getvariable('automprun') then # check this
- ['mprun','mpgraph'].each do |s|
- state.register(File.suffixed(rawbase,s,'mp'),'randomseed')
- end
- end
- while ! stoprunning && (texruns < nofruns) && ok do
- texruns += 1
- report("TeX run #{texruns}")
- unless getvariable('nooptionfile') then
- if texruns == nofruns then
- makeoptionfile(rawbase,jobname,orisuffix,false,false,4,texruns) # last
- elsif texruns == 1 then
- makeoptionfile(rawbase,jobname,orisuffix,false,false,1,texruns) # first
- else
- makeoptionfile(rawbase,jobname,orisuffix,false,false,2,texruns) # unknown
- end
- end
-# goto .
-
- ok = runtex(File.suffixed(if dummyfile || forcexml then rawbase else rawname end,jobsuffix))
-
-if getvariable('texengine') == "xetex" then
- ok = true
-end
-
-############################
-
-# goto tmp/jobname when present
- if ok && (nofruns > 1) then
- unless getvariable('nompmode') then
- mprundone = runtexmpjob(rawbase, "mpgraph")
- mprundone = runtexmpjob(rawbase, "mprun")
- end
- ok = runtexutil(rawbase)
- state.update
- stoprunning = state.stable?
- end
- end
- if not ok then
- setvariable('error','error in tex file')
- end
- if (nofruns == 1) && getvariable('texutil') then
- ok = runtexutil(rawbase)
- end
- if ok && finalrun && (nofruns > 1) then
- makeoptionfile(rawbase,jobname,orisuffix,true,finalrun,4,texruns) unless getvariable('nooptionfile')
- report("final TeX run #{texruns}")
-# goto .
- ok = runtex(File.suffixed(if dummyfile || forcexml then rawbase else rawname end,jobsuffix))
-# goto tmp/jobname when present
- end
- if getvariable('keep') then
- ['top','log','run'].each do |suffix|
- File.silentrename(File.suffixed(rawbase,suffix),File.suffixed(rawbase,suffix+'.keep'))
- end
- else
- File.silentrename(File.suffixed(rawbase,'top'),File.suffixed(rawbase,'tmp'))
- end
- # ['tmp','top','log'].each do |s| # previous tuo file / runtime option file / log file
- # File.silentdelete(File.suffixed(rawbase,s))
- # end
- if ok then
-# goto .
- runbackend(rawbase)
- popresult(rawbase,result)
-# goto tmp/jobname when present
-# skip next
- end
- if true then # autopurge
- begin
- File.open(File.suffixed(rawbase, 'tuo'),'rb') do |f|
- ok = 0
- f.each do |line|
- case ok
- when 1 then
- # next line is empty
- ok = 2
- when 2 then
- if line =~ /^\%\s+\>\s+(.*?)\s+(\d+)/moi then
- filename, n = $1, $2
- done = File.delete(filename) rescue false
- if done && getvariable('verbose') then
- report("deleting #{filename} (#{n} times used)")
- end
- else
- break
- end
- else
- if line =~ /^\%\s+temporary files\:\s+(\d+)/moi then
- if $1.to_i == 0 then
- break
- else
- ok = 1
- end
- end
- end
- end
- end
- rescue
- # report("fatal error #{$!}")
- end
- end
- end
-
- Kpse.runscript('ctxtools',rawbase,'--purge') if getvariable('purge')
- Kpse.runscript('ctxtools',rawbase,'--purge --all') if getvariable('purgeall')
-
- # runcommand('mtxrun','--script','ctxtools',rawbase,'--purge') if getvariable('purge')
- # runcommand('mtxrun','--script','ctxtools',rawbase,'--purge --all') if getvariable('purgeall')
-
- when 'latex' then
-
- ok = runtex(rawname)
-
- else
-
- ok = runtex(rawname)
-
- end
-
- if (dummyfile or forcexml) and FileTest.file?(rawbase) then
- begin
- File.delete(File.suffixed(rawbase,'run'))
- rescue
- report("unable to delete stub file")
- end
- end
-
- if ok and getvariable('autopdf') then
- PDFview.open(File.suffixed(if result.empty? then rawbase else result end,'pdf'))
- end
-
- else
- report("nothing to process")
- end
-
- end
-
- # The labels are collected in the mergebe hash. Here we merge the relevant labels
- # into beginfig/endfig. We could as well do this in metafun itself. Maybe some
- # day ... (it may cost a bit of string space but that is cheap nowadays).
-
- def doruntexmp(mpname,mergebe=nil,context=true,purge=true)
- texfound = false
- mpname = File.suffixed(mpname,'mp')
- mpcopy = File.suffixed(mpname,'mp.copy')
- mpkeep = File.suffixed(mpname,'mp.keep')
- setvariable('mp.file',mpname)
- setvariable('mp.line','')
- setvariable('mp.error','')
- if mpdata = File.silentread(mpname) then
- # mpdata.gsub!(/^\%.*\n/o,'')
- File.silentrename(mpname,mpcopy)
- texfound = mergebe || (mpdata =~ /btex .*? etex/mo)
- if mp = openedfile(mpname) then
- if mergebe then
- mpdata.gsub!(/beginfig\s*\((\d+)\)\s*\;(.+?)endfig\s*\;/mo) do
- n, str = $1, $2
- if str =~ /^(.*?)(verbatimtex.*?etex)\s*\;(.*)$/mo then
- "beginfig(#{n})\;\n#{$1}#{$2}\;\n#{mergebe[n]}\n#{$3}\;endfig\;\n"
- else
- "beginfig(#{n})\;\n#{mergebe[n]}\n#{str}\;endfig\;\n"
- end
- end
- unless mpdata =~ /beginfig\s*\(\s*0\s*\)/o then
- mp << mergebe['0'] if mergebe.key?('0')
- end
- end
- # mp << MPTools::splitmplines(mpdata)
- mp << mpdata
- mp << "\n"
- # mp << "end"
- # mp << "\n"
- mp.close
- end
- processmpx(mpname,true,true,purge) if texfound
- if getvariable('batchmode') then
- options = ' --interaction=batch'
- elsif getvariable('nonstopmode') then
- options = ' --interaction=nonstop'
- else
- options = ''
- end
- # todo plain|mpost|metafun
- begin
- ok = runmp(mpname)
- rescue
- end
- if f = File.silentopen(File.suffixed(mpname,'log')) then
- while str = f.gets do
- if str =~ /^l\.(\d+)\s(.*?)\n/o then
- setvariable('mp.line',$1)
- setvariable('mp.error',$2)
- break
- end
- end
- f.close
- end
- File.silentrename(mpname, mpkeep)
- File.silentrename(mpcopy, mpname)
- end
- end
-
- # todo: use internal mptotext function and/or turn all btex/etex into textexts
-
- def processmpx(mpname,force=false,context=true,purge=true)
- unless force then
- mpname = File.suffixed(mpname,'mp')
- if File.atleast?(mpname,10) && (data = File.silentread(mpname)) then
- if data =~ /(btex|etex|verbatimtex|textext)/o then
- force = true
- end
- end
- end
- if force then
- begin
- mptex = File.suffixed(mpname,'temp','tex')
- mpdvi = File.suffixed(mpname,'temp','dvi')
- mplog = File.suffixed(mpname,'temp','log')
- mpmpx = File.suffixed(mpname,'mpx')
- File.silentdelete(mptex)
- if true then
- report("using internal mptotex converter")
- ok = MPTools::mptotex(mpname,mptex,'context')
- else
- command = "mpto #{mpname} > #{mptex}"
- report(command) if getvariable('verbose')
- ok = system(command)
- end
- # not "ok && ..." because of potential problem with return code and redirect (>)
- if FileTest.file?(mptex) && File.appended(mptex, "\\end\n") then
- # to be replaced by runtexexec([filenames],options,1)
- if localjob = TEX.new(@logger) then
- localjob.setvariable('files',mptex)
- localjob.setvariable('backend','dvips')
- localjob.setvariable('engine',getvariable('engine')) unless getvariable('engine').empty?
- localjob.setvariable('once',true)
- localjob.setvariable('nobackend',true)
- if context then
- localjob.setvariable('texformats',[getvariable('interface')]) unless getvariable('interface').empty?
- elsif getvariable('interface').empty? then
- localjob.setvariable('texformats',['plain'])
- else
- localjob.setvariable('texformats',[getvariable('interface')])
- end
- localjob.processtex
- ok = true # todo
- else
- ok = false
- end
- # so far
- command = "dvitomp #{mpdvi} #{mpmpx}"
- report(command) if getvariable('verbose')
- ok = ok && FileTest.file?(mpdvi) && system(command)
- purge_mpx_files(mpname) if purge
- end
- rescue
- # error in processing mpx file
- end
- end
- end
-
- def purge_mpx_files(mpname)
- unless getvariable('keep') then
- ['tex', 'log', 'tui', 'tuo', 'tuc', 'top'].each do |suffix|
- File.silentdelete(File.suffixed(mpname,'temp',suffix))
- end
- end
- end
-
- def checkmpgraphics(mpname)
- # in practice the checksums will differ because of multiple instances
- # ok, we could save the mpy/mpo files by number, but not now
- mpoptions = ''
- if getvariable('makempy') then
- mpoptions += " --makempy "
- end
- mponame = File.suffixed(mpname,'mpo')
- mpyname = File.suffixed(mpname,'mpy')
- pdfname = File.suffixed(mpname,'pdf')
- tmpname = File.suffixed(mpname,'tmp')
- if getvariable('mpyforce') || getvariable('forcempy') then
- mpoptions += " --force "
- else
- return false unless File.atleast?(mponame,32)
- mpochecksum = FileState.new.checksum(mponame)
- return false if mpochecksum.empty?
- # where does the checksum get into the file?
- # maybe let texexec do it?
- # solution: add one if not present or update when different
- begin
- mpydata = IO.read(mpyname)
- if mpydata then
- if mpydata =~ /^\%\s*mpochecksum\s*\:\s*([A-Z0-9]+)$/mo then
- checksum = $1
- if mpochecksum == checksum then
- return false
- end
- end
- end
- rescue
- # no file
- end
- end
- # return Kpse.runscript('makempy',mpname)
- # only pdftex
- flags = ['--noctx','--process','--batch','--once']
- result = runtexexec([mponame], flags, 1)
- runcommand(["pstoedit","-ssp -dt -f mpost", pdfname,tmpname])
- tmpdata = IO.read(tmpname)
- if tmpdata then
- if mpy = openedfile(mpyname) then
- mpy << "% mpochecksum: #{mpochecksum}\n"
- tmpdata.scan(/beginfig(.*?)endfig/mo) do |s|
- mpy << "begingraphictextfig#{s}endgraphictextfig\n"
- end
- mpy.close()
- end
- end
- File.silentdelete(tmpname)
- File.silentdelete(pdfname)
- return true
- end
-
- def checkmplabels(mpname)
- mpname = File.suffixed(mpname,'mpt')
- if File.atleast?(mpname,10) && (mp = File.silentopen(mpname)) then
- labels = Hash.new
- while str = mp.gets do
- t = if str =~ /^%\s*setup\s*:\s*(.*)$/o then $1 else '' end
- if str =~ /^%\s*figure\s*(\d+)\s*:\s*(.*)$/o then
- labels[$1] = labels[$1] || ''
- unless t.empty? then
- labels[$1] += "#{t}\n"
- t = ''
- end
- labels[$1] += "#{$2}\n"
- end
- end
- mp.close
- if labels.size>0 then
- return labels
- else
- return nil
- end
- end
- return nil
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/texutil.rb b/Master/texmf-dist/scripts/context/ruby/base/texutil.rb
deleted file mode 100644
index 868e3ca1625..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/texutil.rb
+++ /dev/null
@@ -1,1097 +0,0 @@
-require "base/file"
-require "base/logger"
-
-class String
-
- # real dirty, but inspect does a pretty good escaping but
- # unfortunately puts quotes around the string so we need
- # to strip these
-
- # def escaped
- # self.inspect[1,self.inspect.size-2]
- # end
-
- def escaped
- str = self.inspect ; str[1,str.size-2]
- end
-
- def splitdata
- if self =~ /^\s*(.*?)\s*\{(.*)\}\s*$/o then
- first, second = $1, $2
- if first.empty? then
- [second.split(/\} \{/o)].flatten
- else
- [first.split(/\s+/o)] + [second.split(/\} \{/o)]
- end
- else
- []
- end
- end
-
-end
-
-class Logger
- def banner(str)
- report(str)
- return "%\n% #{str}\n%\n"
- end
-end
-
-class TeXUtil
-
- class Plugin
-
- # we need to reset module data for each run; persistent data is
- # possible, just don't reinitialize the data structures that need
- # to be persistent; we reset afterwards becausethen we know what
- # plugins are defined
-
- def initialize(logger)
- @plugins = Array.new
- @logger = logger
- end
-
- def report(str)
- @logger.report("fatal error in plugin (#{str}): #{$!}")
- puts("\n")
- $@.each do |line|
- puts(" #{line}")
- end
- puts("\n")
- end
-
- def reset(name)
- if @plugins.include?(name) then
- begin
- eval("#{name}").reset(@logger)
- rescue Exception
- report("resetting")
- end
- else
- @logger.report("no plugin #{name}")
- end
- end
-
- def resets
- @plugins.each do |p|
- reset(p)
- end
- end
-
- def register(name, file=nil) # maybe also priority
- if file then
- begin
- require("#{file.downcase.sub(/\.rb$/,'')}.rb")
- rescue Exception
- @logger.report("no plugin file #{file} for #{name}")
- else
- @plugins.push(name)
- end
- else
- @plugins.push(name)
- end
- return self
- end
-
- def reader(name, data=[])
- if @plugins.include?(name) then
- begin
- eval("#{name}").reader(@logger,data.flatten)
- rescue Exception
- report("reading")
- end
- else
- @logger.report("no plugin #{name}")
- end
- end
-
- def readers(data=[])
- @plugins.each do |p|
- reader(p,data.flatten)
- end
- end
-
- def writers(handle)
- @plugins.each do |p|
- begin
- eval("#{p}").writer(@logger,handle)
- rescue Exception
- report("writing")
- end
- end
- end
-
- def processors
- @plugins.each do |p|
- begin
- eval("#{p}").processor(@logger)
- rescue Exception
- report("processing")
- end
- end
- end
-
- def finalizers
- @plugins.each do |p|
- begin
- eval("#{p}").finalizer(@logger)
- rescue Exception
- report("finalizing")
- end
- end
- end
-
- end
-
- class Sorter
-
- @@downcase = true
-
- def initialize(max=12)
- @rep, @map, @exp, @div = Hash.new, Hash.new, Hash.new, Hash.new
- @max = max
- @rexa, @rexb = nil, nil
- end
-
- def replacer(from,to='') # and expand
- @max = [@max,to.length+1].max if to
- @rep[from.escaped] = to || ''
- end
-
- # sorter.reducer('ch', 'c')
- # sorter.reducer('ij', 'y')
-
- def reducer(from,to='')
- @max = [@max,to.length+1].max if to
- @map[from] = to || ''
- end
-
- # sorter.expander('aeligature', 'ae')
- # sorter.expander('ijligature', 'y')
-
- def expander(from,to=nil)
- to = converted(to) # not from !!!
- @max = [@max,to.length+1].max if to
- @exp[from] = to || from || ''
- end
-
- def division(from,to=nil)
- from, to = converted(from), converted(to)
- @max = [@max,to.length+1].max if to
- @div[from] = to || from || ''
- end
-
- # shortcut("\\ab\\cd\\e\\f", 'iacute')
- # shortcut("\\\'\\i", 'iacute')
- # shortcut("\\\'i", 'iacute')
- # shortcut("\\\"e", 'ediaeresis')
- # shortcut("\\\'o", 'oacute')
-
- def hextoutf(str)
- str.gsub(/^(0x[A-F\d]+)$/) do
- [$1.hex()].pack("U")
- end
- end
-
- def shortcut(from,to)
- from = hextoutf(from)
- replacer(from,to)
- expander(to)
- end
-
- def prepare
- if @rep.size > 0 then
- @rexa = /(#{@rep.keys.join('|')})/ # o
- else
- @rexa = nil
- end
- if @map.size > 0 then
- # watch out, order of match matters
- if @@downcase then
- @rexb = /(\\[a-zA-Z]+|#{@map.keys.join('|')}|.)\s*/i # o
- else
- @rexb = /(\\[a-zA-Z]+|#{@map.keys.join('|')}|.)\s*/ # o
- end
- else
- if @@downcase then
- @rexb = /(\\[a-zA-Z]+|.)\s*/io
- else
- @rexb = /(\\[a-zA-Z]+|.)\s*/o
- end
- end
- if false then
- @exp.keys.each do |e|
- @exp[e].downcase!
- end
- end
- end
-
- def replace(str)
- if @rexa then
- str.gsub(@rexa) do
- @rep[$1.escaped]
- end
- else
- str
- end
- end
-
- def normalize(str)
- # replace(str).gsub(/ +/,' ')
- replace(str).gsub(/\s\s+/," \\space")
- end
-
- def tokenize(str)
- if str then
- str.gsub(/\\strchr\{(.*?)\}/o) do "\\#{$1}" end
- else
- ""
- end
- end
-
- def remap(str)
- s = str.dup
- if true then # numbers are treated special
- s.gsub!(/(\d+)/o) do
- $1.rjust(10,'a') # rest is b .. k
- end
- end
- if @rexa then
- s.gsub!(@rexa) do
- @rep[$1.escaped]
- end
- end
- if @rexb then
- s.gsub!(@rexb) do
- token = $1.sub(/\\/o, '')
- if @@downcase then
- token.downcase!
- end
- if @exp.key?(token) then
- @exp[token].ljust(@max,' ')
- elsif @map.key?(token) then
- @map[token].ljust(@max,' ')
- else
- ''
- end
- end
- end
- s
- end
-
- def preset(shortcuts=[],expansions=[],reductions=[],divisions=[],language='')
- 'a'.upto('z') do |c| expander(c) ; division(c) end
- 'A'.upto('Z') do |c| expander(c) ; division(c) end
- expander('1','b') ; expander('2','c') ; expander('3','e') ; expander('4','f')
- expander('5','g') ; expander('6','h') ; expander('7','i') ; expander('8','i')
- expander('9','j') ; expander('0','a') ; expander('-','-') ;
- shortcuts.each do |s| shortcut(s[1],s[2]) if s[0] == '' || s[0] == language end
- expansions.each do |e| expander(e[1],e[2]) if e[0] == '' || e[0] == language end
- reductions.each do |r| reducer(r[1],r[2]) if r[0] == '' || r[0] == language end
- divisions.each do |d| division(d[1],d[2]) if d[0] == '' || d[0] == language end
- end
-
- def simplify(str)
- s = str.dup
- # ^^
- # s.gsub!(/\^\^([a-f0-9][a-f0-9])/o, $1.hex.chr)
- # \- ||
- s.gsub!(/(\\\-|\|\|)/o) do '-' end
- # {}
- s.gsub!(/\{\}/o) do '' end
- # <*..> (internal xml entity)
- s.gsub!(/<\*(.*?)>/o) do $1 end
- # entities
- s.gsub!(/\\getXMLentity\s*\{(.*?)\}/o) do $1 end
- # elements
- s.gsub!(/\<.*?>/o) do '' end
- # what to do with xml and utf-8
- # \"e etc
- # unknown \cs
- s.gsub!(/\\[a-zA-Z][a-zA-Z]+\s*\{(.*?)\}/o) do $1 end
- return s
- end
-
- def getdivision(str)
- @div[str] || str
- end
-
- def division?(str)
- @div.key?(str)
- end
-
- private
-
- def converted(str)
- if str then
- # puts str
- str.gsub(/([\+\-]*\d+)/o) do
- n = $1.to_i
- if n > 0 then
- 'z'*n
- elsif n < 0 then
- '-'*(-n) # '-' precedes 'a'
- else
- ''
- end
- end
- else
- nil
- end
- end
-
- end
-
- class Plugin
-
- module MyFiles
-
- @@files, @@temps = Hash.new, Hash.new
-
- def MyFiles::reset(logger)
- @@files, @@temps = Hash.new, Hash.new
- end
-
- def MyFiles::reader(logger,data)
- case data[0]
- when 'b', 'e' then
- @@files[data[1]] = (@@files[data[1]] ||0) + 1
- when 't' then # temporary file
- @@temps[data[1]] = (@@temps[data[1]] ||0) + 1
- end
- end
-
- def MyFiles::writer(logger,handle)
- handle << logger.banner("loaded files: #{@@files.size}")
- @@files.keys.sort.each do |k|
- handle << "% > #{k} #{@@files[k]/2}\n"
- end
- handle << logger.banner("temporary files: #{@@temps.size}")
- @@temps.keys.sort.each do |k|
- handle << "% > #{k} #{@@temps[k]}\n"
- end
- end
-
- def MyFiles::processor(logger)
- @@files.keys.sort.each do |k|
- unless (@@files[k] % 2) == 0 then
- logger.report("check loading of file '#{k}', begin/end problem")
- end
- end
- @@temps.keys.sort.each do |k|
- # logger.report("temporary file '#{k}' can be deleted")
- end
- end
-
- def MyFiles::finalizer(logger)
- end
-
- end
-
- end
-
- class Plugin
-
- module MyCommands
-
- @@commands = []
-
- def MyCommands::reset(logger)
- @@commands = []
- end
-
- def MyCommands::reader(logger,data)
- @@commands.push(data.shift+data.collect do |d| "\{#{d}\}" end.join)
- end
-
- def MyCommands::writer(logger,handle)
- handle << logger.banner("commands: #{@@commands.size}")
- @@commands.each do |c|
- handle << "#{c}%\n"
- end
- end
-
- def MyCommands::processor(logger)
- end
-
- def MyCommands::finalizer(logger)
- end
-
- end
-
- end
-
- class Plugin
-
- module MyExtras
-
- @@programs = []
-
- def MyExtras::reset(logger)
- @@programs = []
- end
-
- def MyExtras::reader(logger,data)
- case data[0]
- when 'p' then
- @@programs.push(data[1]) if data[0]
- end
- end
-
- def MyExtras::writer(logger,handle)
- handle << logger.banner("programs: #{@@programs.size}")
- @@programs.each_with_index do |cmd, p|
- handle << "% #{p+1} (#{cmd})\n"
- end
- end
-
- def MyExtras::processor(logger)
- @@programs.each do |p|
- # cmd = @@programs[p.to_i]
- # logger.report("running #{cmd}")
- # system(cmd)
- end
- end
-
- def MyExtras::finalizer(logger)
- unless (ENV["CTX.TEXUTIL.EXTRAS"] =~ /^(no|off|false|0)$/io) || (ENV["CTX_TEXUTIL_EXTRAS"] =~ /^(no|off|false|0)$/io) then
- @@programs.each do |cmd|
- logger.report("running #{cmd}")
- system(cmd)
- end
- end
- end
-
- end
-
- end
-
- class Plugin
-
- module MySynonyms
-
- class Synonym
-
- @@debug = false
-
- def initialize(t, c, k, d)
- @type, @command, @key, @sortkey, @data = t, c, k, c, d
- end
-
- attr_reader :type, :command, :key, :data
- attr_reader :sortkey
- attr_writer :sortkey
-
- # def build(sorter)
- # if @key then
- # @sortkey = sorter.normalize(sorter.tokenize(@sortkey))
- # @sortkey = sorter.remap(sorter.simplify(@key.downcase)) # ??
- # if @sortkey.empty? then
- # @sortkey = sorter.remap(@command.downcase)
- # end
- # else
- # @key = ""
- # @sortkey = ""
- # end
- # end
-
- def build(sorter)
- if @sortkey and not @sortkey.empty? then
- @sortkey = sorter.normalize(sorter.tokenize(@sortkey))
- @sortkey = sorter.remap(sorter.simplify(@sortkey.downcase)) # ??
- end
- if not @sortkey or @sortkey.empty? then
- @sortkey = sorter.normalize(sorter.tokenize(@key))
- @sortkey = sorter.remap(sorter.simplify(@sortkey.downcase)) # ??
- end
- if not @sortkey or @sortkey.empty? then
- @sortkey = @key.dup
- end
- end
-
- def <=> (other)
- @sortkey <=> other.sortkey
- end
-
- def Synonym.flush(list,handle)
- if @@debug then
- list.each do |entry|
- handle << "% [#{entry.sortkey}]\n"
- end
- end
- list.each do |entry|
- handle << "\\synonymentry{#{entry.type}}{#{entry.command}}{#{entry.key}}{#{entry.data}}%\n"
- end
- end
-
- end
-
- @@synonyms = Hash.new
- @@sorter = Hash.new
- @@languages = Hash.new
-
- def MySynonyms::reset(logger)
- @@synonyms = Hash.new
- @@sorter = Hash.new
- @@languages = Hash.new
- end
-
- def MySynonyms::reader(logger,data)
- case data[0]
- when 'e' then
- @@synonyms[data[1]] = Array.new unless @@synonyms.key?(data[1])
- @@synonyms[data[1]].push(Synonym.new(data[1],data[2],data[3],data[4]))
- when 'l' then
- @@languages[data[1]] = data[2] || ''
- end
- end
-
- def MySynonyms::writer(logger,handle)
- if @@synonyms.size > 0 then
- @@synonyms.keys.sort.each do |s|
- handle << logger.banner("synonyms: #{s} #{@@synonyms[s].size}")
- Synonym.flush(@@synonyms[s],handle)
- end
- end
- end
-
- def MySynonyms::processor(logger)
- @@synonyms.keys.each do |s|
- @@sorter[s] = Sorter.new
- @@sorter[s].preset(
- eval("MyKeys").shortcuts,
- eval("MyKeys").expansions,
- eval("MyKeys").reductions,
- eval("MyKeys").divisions,
- @@languages[s] || '')
- @@sorter[s].prepare
- @@synonyms[s].each_index do |i|
- @@synonyms[s][i].build(@@sorter[s])
- end
- @@synonyms[s] = @@synonyms[s].sort
- end
- end
-
- def MySynonyms::finalizer(logger)
- end
-
- end
-
- end
-
- class Plugin
-
- module MyRegisters
-
- class Register
-
- @@specialsymbol = "\000"
- @@specialbanner = "" # \\relax"
-
- @@debug = false
-
- @@howto = /^(.*?)\:\:(.*)$/o
- @@split = ' && '
-
- def initialize(state, t, l, k, e, s, p, r)
- @state, @type, @location, @key, @entry, @seetoo, @page, @realpage = state, t, l, k, e, s, p, r
- if @key =~ @@howto then @pagehowto, @key = $1, $2 else @pagehowto = '' end
- if @entry =~ @@howto then @texthowto, @entry = $1, $2 else @texthowto = '' end
- @key = @entry.dup if @key.empty?
- @sortkey = @key.dup
- @nofentries, @nofpages = 0, 0
- @normalizeentry = false
- end
-
- attr_reader :state, :type, :location, :key, :entry, :seetoo, :page, :realpage, :texthowto, :pagehowto
- attr_reader :sortkey
- attr_writer :sortkey
-
- def build(sorter)
- # @entry, @key = sorter.normalize(@entry), sorter.normalize(sorter.tokenize(@key))
- @entry = sorter.normalize(sorter.tokenize(@entry)) if @normalizeentry
- @key = sorter.normalize(sorter.tokenize(@key))
- if false then
- @entry, @key = [@entry, @key].collect do |target|
- # +a+b+c &a&b&c a+b+c a&b&c
- case target[0,1]
- when '&' then target = target.sub(/^./o,'').gsub(/([^\\])\&/o) do "#{$1}#{@@split}" end
- when '+' then target = target.sub(/^./o,'').gsub(/([^\\])\+/o) do "#{$1}#{@@split}" end
- else target = target .gsub(/([^\\])[\&\+]/o) do "#{$1}#{@@split}" end
- end
- # {a}{b}{c}
- # if target =~ /^\{(.*)\}$/o then
- # $1.split(/\} \{/o).join(@@split) # space between } { is mandate
- # else
- target
- # end
- end
- else
- # @entry, @key = cleanupsplit(@entry), cleanupsplit(@key)
- @entry, @key = cleanupsplit(@entry), xcleanupsplit(@key)
- end
- @sortkey = sorter.simplify(@key)
- # special = @sortkey =~ /^([^a-zA-Z\\])/o
- special = @sortkey =~ /^([\`\~\!\@\#\$\%\^\&\*\(\)\_\-\+\=\{\}\[\]\:\;\"\'\|\<\,\>\.\?\/\d])/o
- @sortkey = @sortkey.split(@@split).collect do |c| sorter.remap(c) end.join(@@split)
- if special then
- @sortkey = "#{@@specialsymbol}#{@sortkey}"
- end
- if @realpage == 0 then
- @realpage = 999999
- end
- @sortkey = [
- @sortkey.downcase,
- @sortkey,
- @entry,
- @texthowto.ljust(10,' '),
- # @state, # no, messes up things
- (@realpage.to_s || '').rjust(6,' ').gsub(/0/,' '),
- # (@realpage ||'').rjust(6,' '),
- @pagehowto
- ].join(@@split)
- end
-
- def cleanupsplit(target)
- # +a+b+c &a&b&c a+b+c a&b&c
- case target[0,1]
- when '&' then target.sub(/^./o,'').gsub(/([^\\])\&/o) do "#{$1}#{@@split}" end
- when '+' then target.sub(/^./o,'').gsub(/([^\\])\+/o) do "#{$1}#{@@split}" end
- else target .gsub(/([^\\])[\&\+]/o) do "#{$1}#{@@split}" end
- end
- end
-
- def xcleanupsplit(target) # +a+b+c &a&b&c a+b+c a&b&c
- t = Array.new
- case target[0,1]
- when '&' then
- t = target.sub(/^./o,'').split(/([^\\])\&/o)
- when '+' then
- t = target.sub(/^./o,'').split(/([^\\])\+/o)
- else
- # t = target.split(/([^\\])[\&\+]/o)
- # t = target.split(/[\&\+]/o)
- t = target.split(/(?!\\)[\&\+]/o) # lookahead
- end
- if not t[1] then t[1] = " " end # we need some entry else we get subentries first
- if not t[2] then t[2] = " " end # we need some entry else we get subentries first
- if not t[3] then t[3] = " " end # we need some entry else we get subentries first
- return t.join(@@split)
- end
- def <=> (other)
- @sortkey <=> other.sortkey
- end
-
- # more module like
-
- @@savedhowto, @@savedfrom, @@savedto, @@savedentry = '', '', '', '', ''
- @@collapse = false
-
- def Register.flushsavedline(handle)
- if @@collapse && ! @@savedfrom.empty? then
- if ! @@savedto.empty? then
- handle << "\\registerfrom#{@@savedfrom}%"
- handle << "\\registerto#{@@savedto}%"
- else
- handle << "\\registerpage#{@@savedfrom}%"
- end
- end
- @@savedhowto, @@savedfrom, @@savedto, @@savedentry = '', '', '', ''
- end
-
- def Register.flush(list,handle,sorter)
- # a bit messy, quite old mechanism, maybe some day ...
- # alphaclass can go, now flushed per class
- if list.size > 0 then
- @nofentries, @nofpages = 0, 0
- current, previous, howto = Array.new, Array.new, Array.new
- lastpage, lastrealpage = '', ''
- alphaclass, alpha = '', ''
- @@savedhowto, @@savedfrom, @@savedto, @@savedentry = '', '', '', ''
- if @@debug then
- list.each do |entry|
- handle << "% [#{entry.sortkey.gsub(/#{@@split}/o,'] [')}]\n"
- end
- end
- list.each do |entry|
-# puts(entry.sortkey.gsub(/\s+/,""))
- if entry.sortkey =~ /^(\S+)/o then
- if sorter.division?($1) then
- testalpha = sorter.getdivision($1)
- else
- testalpha = entry.sortkey[0,1].downcase
- end
- else
- testalpha = entry.sortkey[0,1].downcase
- end
- if (testalpha != alpha.downcase) || (alphaclass != entry.class) then
- alpha = testalpha
- alphaclass = entry.class
- if alpha != ' ' then
- flushsavedline(handle)
- if alpha =~ /^[a-zA-Z]$/o then
- character = alpha.dup
- elsif alpha == @@specialsymbol then
- character = @@specialbanner
- elsif alpha.length > 1 then
- # character = "\\getvalue\{#{alpha}\}"
- character = "\\#{alpha}"
- else
- character = "\\unknown"
- end
- handle << "\\registerentry{#{entry.type}}{#{character}}%\n"
- end
- end
- current = [entry.entry.split(@@split),'','','',''].flatten
- howto = current.collect do |e|
- e + '::' + entry.texthowto
- end
- if howto[0] == previous[0] then
- current[0] = ''
- else
- previous[0] = howto[0].dup
- previous[1] = ''
- previous[2] = ''
- previous[3] = ''
- end
- if howto[1] == previous[1] then
- current[1] = ''
- else
- previous[1] = howto[1].dup
- previous[2] = ''
- previous[3] = ''
- end
- if howto[2] == previous[2] then
- current[2] = ''
- else
- previous[2] = howto[2].dup
- previous[3] = ''
- end
- if howto[3] == previous[3] then
- current[3] = ''
- else
- previous[3] = howto[3].dup
- end
- copied = false
- unless current[0].empty? then
- Register.flushsavedline(handle)
- handle << "\\registerentrya{#{entry.type}}{#{current[0]}}%\n"
- copied = true
- end
- unless current[1].empty? then
- Register.flushsavedline(handle)
- handle << "\\registerentryb{#{entry.type}}{#{current[1]}}%\n"
- copied = true
- end
- unless current[2].empty? then
- Register.flushsavedline(handle)
- handle << "\\registerentryc{#{entry.type}}{#{current[2]}}%\n"
- copied = true
- end
- unless current[3].empty? then
- Register.flushsavedline(handle)
- handle << "\\registerentryd{#{entry.type}}{#{current[3]}}%\n"
- copied = true
- end
- @nofentries += 1 if copied
- # if entry.realpage.to_i == 0 then
- if entry.realpage.to_i == 999999 then
- Register.flushsavedline(handle)
- handle << "\\registersee{#{entry.type}}{#{entry.pagehowto},#{entry.texthowto}}{#{entry.seetoo}}{#{entry.page}}%\n" ;
- lastpage, lastrealpage = entry.page, entry.realpage
- copied = false # no page !
- elsif @@savedhowto != entry.pagehowto and ! entry.pagehowto.empty? then
- @@savedhowto = entry.pagehowto
- end
- # beware, we keep multiple page entries per realpage because of possible prefix usage
- if copied || ! ((lastpage == entry.page) && (lastrealpage == entry.realpage)) then
- nextentry = "{#{entry.type}}{#{previous[0]}}{#{previous[1]}}{#{previous[2]}}{#{previous[3]}}{#{entry.pagehowto},#{entry.texthowto}}"
- savedline = "{#{entry.type}}{#{@@savedhowto},#{entry.texthowto}}{#{entry.location}}{#{entry.page}}{#{entry.realpage}}"
- if entry.state == 1 then # from
- Register.flushsavedline(handle)
- handle << "\\registerfrom#{savedline}%\n"
- elsif entry.state == 3 then # to
- Register.flushsavedline(handle)
- handle << "\\registerto#{savedline}%\n"
- @@savedhowto = '' # test
- elsif @@collapse then
- if savedentry != nextentry then
- savedFrom = savedline
- else
- savedTo, savedentry = savedline, nextentry
- end
- else
- handle << "\\registerpage#{savedline}%\n"
- @@savedhowto = '' # test
- end
- @nofpages += 1
- lastpage, lastrealpage = entry.page, entry.realpage
- end
- end
- Register.flushsavedline(handle)
- end
- end
-
- end
-
- @@registers = Hash.new
- @@sorter = Hash.new
- @@languages = Hash.new
-
- def MyRegisters::reset(logger)
- @@registers = Hash.new
- @@sorter = Hash.new
- @@languages = Hash.new
- end
-
- def MyRegisters::reader(logger,data)
- case data[0]
- when 'f' then
- @@registers[data[1]] = Array.new unless @@registers.key?(data[1])
- @@registers[data[1]].push(Register.new(1,data[1],data[2],data[3],data[4],nil,data[5],data[6]))
- when 'e' then
- @@registers[data[1]] = Array.new unless @@registers.key?(data[1])
- @@registers[data[1]].push(Register.new(2,data[1],data[2],data[3],data[4],nil,data[5],data[6]))
- when 't' then
- @@registers[data[1]] = Array.new unless @@registers.key?(data[1])
- @@registers[data[1]].push(Register.new(3,data[1],data[2],data[3],data[4],nil,data[5],data[6]))
- when 's' then
- @@registers[data[1]] = Array.new unless @@registers.key?(data[1])
- # was this but wrong sort order (4,data[1],data[2],data[3],data[4],data[5],data[6],nil))
- @@registers[data[1]].push(Register.new(4,data[1],data[2],data[3],data[4],data[5],data[6],0))
- when 'l' then
- @@languages[data[1]] = data[2] || ''
- end
- end
-
- def MyRegisters::writer(logger,handle)
- if @@registers.size > 0 then
- @@registers.keys.sort.each do |s|
- handle << logger.banner("registers: #{s} #{@@registers[s].size}")
- Register.flush(@@registers[s],handle,@@sorter[s])
- # report("register #{@@registers[s].class}: #{@@registers[s].@nofentries} entries and #{@@registers[s].@nofpages} pages")
- end
- end
- end
-
- def MyRegisters::processor(logger)
- @@registers.keys.each do |s|
- @@sorter[s] = Sorter.new
- @@sorter[s].preset(
- eval("MyKeys").shortcuts,
- eval("MyKeys").expansions,
- eval("MyKeys").reductions,
- eval("MyKeys").divisions,
- @@languages[s] || '')
- @@sorter[s].prepare
- @@registers[s].each_index do |i|
- @@registers[s][i].build(@@sorter[s])
- end
- # @@registers[s].uniq!
- @@registers[s] = @@registers[s].sort
- end
- end
-
- def MyRegisters::finalizer(logger)
- end
-
- end
-
- end
-
- class Plugin
-
- module MyPlugins
-
- @@plugins = nil
-
- def MyPlugins::reset(logger)
- @@plugins = nil
- end
-
- def MyPlugins::reader(logger,data)
- @@plugins = Plugin.new(logger) unless @@plugins
- case data[0]
- when 'r' then
- logger.report("registering plugin #{data[1]}")
- @@plugins.register(data[1],data[2])
- when 'd' then
- begin
- @@plugins.reader(data[1],data[2,data.length-1])
- rescue
- @@plugins.reader(data[1],['error'])
- end
- end
- end
-
- def MyPlugins::writer(logger,handle)
- @@plugins.writers(handle) if @@plugins
- end
-
- def MyPlugins::processor(logger)
- @@plugins.processors if @@plugins
- end
-
- def MyPlugins::finalizer(logger)
- @@plugins.finalizers if @@plugins
- end
-
- end
-
- end
-
- class Plugin
-
- module MyKeys
-
- @@shortcuts = Array.new
- @@expansions = Array.new
- @@reductions = Array.new
- @@divisions = Array.new
-
- def MyKeys::shortcuts
- @@shortcuts
- end
- def MyKeys::expansions
- @@expansions
- end
- def MyKeys::reductions
- @@reductions
- end
- def MyKeys::divisions
- @@divisions
- end
-
- def MyKeys::reset(logger)
- @@shortcuts = Array.new
- @@expansions = Array.new
- @@reductions = Array.new
- end
-
- def MyKeys::reader(logger,data)
- key = data.shift
- # grp = data.shift # language code, todo
- case key
- when 's' then @@shortcuts.push(data)
- when 'e' then @@expansions.push(data)
- when 'r' then @@reductions.push(data)
- when 'd' then @@divisions.push(data)
- end
- end
-
- def MyKeys::writer(logger,handle)
- end
-
- def MyKeys::processor(logger)
- logger.report("shortcuts : #{@@shortcuts.size}") # logger.report(@@shortcuts.inspect)
- logger.report("expansions: #{@@expansions.size}") # logger.report(@@expansions.inspect)
- logger.report("reductions: #{@@reductions.size}") # logger.report(@@reductions.inspect)
- logger.report("divisions : #{@@divisions.size}") # logger.report(@@divisions.inspect)
- end
-
- def MyKeys::finalizer(logger)
- end
-
- end
-
- end
-
- class Converter
-
- def initialize(logger=nil)
- if @logger = logger then
- def report(str)
- @logger.report(str)
- end
- def banner(str)
- @logger.banner(str)
- end
- else
- @logger = self
- def report(str)
- puts(str)
- end
- def banner(str)
- puts(str)
- end
- end
- @filename = 'texutil'
- @fatalerror = false
- @plugins = Plugin.new(@logger)
- ['MyFiles', 'MyCommands', 'MySynonyms', 'MyRegisters', 'MyExtras', 'MyPlugins', 'MyKeys'].each do |p|
- @plugins.register(p)
- end
- end
-
- def loaded(filename)
- begin
- tuifile = File.suffixed(filename,'tui')
- if FileTest.file?(tuifile) then
- report("parsing file #{tuifile}")
- if f = File.open(tuifile,'rb') then
- f.each do |line|
- case line.chomp
- when /^f (.*)$/o then @plugins.reader('MyFiles', $1.splitdata)
- when /^c (.*)$/o then @plugins.reader('MyCommands', [$1])
- when /^e (.*)$/o then @plugins.reader('MyExtras', $1.splitdata)
- when /^s (.*)$/o then @plugins.reader('MySynonyms', $1.splitdata)
- when /^r (.*)$/o then @plugins.reader('MyRegisters',$1.splitdata)
- when /^p (.*)$/o then @plugins.reader('MyPlugins', $1.splitdata)
- when /^x (.*)$/o then @plugins.reader('MyKeys', $1.splitdata)
- when /^r (.*)$/o then # nothing, not handled here
- else
- # report("unknown entry #{line[0,1]} in line #{line.chomp}")
- end
- end
- f.close
- end
- else
- report("unable to locate #{tuifile}")
- end
- rescue
- report("fatal error in parsing #{tuifile}")
- @filename = 'texutil'
- else
- @filename = filename
- end
- end
-
- def processed
- @plugins.processors
- return true # for the moment
- end
-
- def saved(filename=@filename)
- if @fatalerror then
- report("fatal error, no tuo file saved")
- return false
- else
- begin
- if f = File.open(File.suffixed(filename,'tuo'),'w') then
- @plugins.writers(f)
- f << "\\endinput\n"
- f.close
- end
- rescue
- report("fatal error when saving file (#{$!})")
- return false
- else
- report("tuo file saved")
- return true
- end
- end
- end
-
- def finalized
- @plugins.finalizers
- @plugins.resets
- return true # for the moment
- end
-
- def reset
- @plugins.resets
- end
-
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/tool.rb b/Master/texmf-dist/scripts/context/ruby/base/tool.rb
deleted file mode 100644
index 1f10c955654..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/tool.rb
+++ /dev/null
@@ -1,291 +0,0 @@
-# module : base/tool
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-require 'timeout'
-require 'socket'
-require 'rbconfig'
-
-module Tool
-
- $constructedtempdir = ''
-
- def Tool.constructtempdir(create,mainpath='',fallback='')
- begin
- mainpath += '/' unless mainpath.empty?
- timeout(5) do
- begin
- t = Time.now
- u = t.usec.to_s % [1..2] [0..3]
- pth = t.strftime("#{mainpath}%Y%m%d-%H%M%S-#{u}-#{Process.pid}")
- #
- # problems with 1.9
- #
- # if pth == $constructedtempdir
- # # sleep(0.01)
- # retry
- # end
- pth == $constructedtempdir
- #
- Dir.mkdir(pth) if create
- $constructedtempdir = pth
- return pth
- rescue
- # sleep(0.01)
- retry
- end
- end
- rescue TimeoutError
- # ok
- rescue
- # ok
- end
- unless fallback.empty?
- begin
- pth = "#{mainpath}#{fallback}"
- mkdir(pth) if create
- $constructedtempdir = path
- return pth
- rescue
- return '.'
- end
- else
- return '.'
- end
-
- end
-
- def Tool.findtempdir(*vars)
- constructtempdir(false,*vars)
- end
-
- def Tool.maketempdir(*vars)
- constructtempdir(true,*vars)
- end
-
- # print maketempdir + "\n"
- # print maketempdir + "\n"
- # print maketempdir + "\n"
- # print maketempdir + "\n"
- # print maketempdir + "\n"
-
-
- def Tool.ruby_platform
- case RUBY_PLATFORM
- when /(mswin|bccwin|mingw|cygwin)/i then 'mswin'
- when /(linux)/i then 'linux'
- when /(netbsd|unix)/i then 'unix'
- when /(darwin|rhapsody|nextstep)/i then 'macosx'
- else 'unix'
- end
- end
-
- $defaultlineseparator = $/ # $RS in require 'English'
-
- def Tool.file_platform(filename)
-
- begin
- if f = open(filename,'rb') then
- str = f.read(4000)
- str.gsub!(/(.*?)\%\!PS/mo, "%!PS") # don't look into preamble crap
- f.close
- nn = str.count("\n")
- nr = str.count("\r")
- if nn>nr then
- return 2
- elsif nn<nr then
- return 3
- else
- return 1
- end
- else
- return 0
- end
- rescue
- return 0
- end
-
- end
-
- def Tool.path_separator
- return File::PATH_SEPARATOR
- end
-
- def Tool.line_separator(filename)
-
- case file_platform(filename)
- when 1 then return $defaultlineseparator
- when 2 then return "\n"
- when 3 then return "\r"
- else return $defaultlineseparator
- end
-
- end
-
- def Tool.default_line_separator
- $defaultlineseparator
- end
-
- def Tool.simplefilename(old)
-
- return old # too fragile
-
- return old if not FileTest.file?(old)
-
- new = old.downcase
- new.gsub!(/[^A-Za-z0-9\_\-\.\\\/]/o) do # funny chars
- '-'
- end
- if old =~ /[a-zA-Z]\:/o
- # seems like we have a dos/windows drive prefix, so roll back
- new.sub!(/^(.)\-/) do
- $1 + ':'
- end
- end
- # fragile for a.b.c.d.bla-bla.e.eps
- # new.gsub!(/(.+?)\.(.+?)(\..+)$/o) do # duplicate .
- # $1 + '-' + $2 + $3
- # end
- new.gsub!(/\-+/o) do # duplicate -
- '-'
- end
- new
-
- end
-
- if RbConfig::CONFIG['host_os'] =~ /mswin/ then
-
- require 'Win32API'
-
- GetShortPathName = Win32API.new('kernel32', 'GetShortPathName', ['P','P','N'], 'N')
- GetLongPathName = Win32API.new('kernel32', 'GetLongPathName', ['P','P','N'], 'N')
-
- def Tool.dowith_pathname (filename,filemethod)
- filename.gsub!(/\\/o,'/')
- case filename
- when /\;/o then
- # could be a path spec
- return filename
- when /\s+/o then
- # danger lurking
- buffer = ' ' * 260
- length = filemethod.call(filename,buffer,buffer.size)
- if length>0 then
- return buffer.slice(0..length-1)
- else
- # when the path or file does not exist, nothing is returned
- # so we try to handle the path separately from the basename
- basename = File.basename(filename)
- pathname = File.dirname(filename)
- length = filemethod.call(pathname,buffer,260)
- if length>0 then
- return buffer.slice(0..length-1) + '/' + basename
- else
- return filename
- end
- end
- else
- # no danger
- return filename
- end
- end
-
- def Tool.shortpathname(filename)
- dowith_pathname(filename,GetShortPathName)
- end
-
- def Tool.longpathname(filename)
- dowith_pathname(filename,GetLongPathName)
- end
-
- else
-
- def Tool.shortpathname(filename)
- filename
- end
-
- def Tool.longpathname(filename)
- filename
- end
-
- end
-
- # print shortpathname("C:/Program Files/ABBYY FineReader 6.0/matrix.str")+ "!\n"
- # print shortpathname("C:/Program Files/ABBYY FineReader 6.0/matrix.strx")+ "!\n"
-
- def Tool.checksuffix(old)
-
- return old unless FileTest.file?(old)
-
- new = old
-
- unless new =~ /\./io # no suffix
- f = open(filename,'rb')
- if str = f.gets
- case str
- when /^\%\!PS/io
- # logging.report(filename, 'analyzed as EPS')
- new = new + '.eps'
- when /^\%PDF/io
- # logging.report(filename, 'analyzed as PDF')
- new = new + '.pdf'
- else
- # logging.report(filename, 'fallback as TIF')
- new = new + '.tif'
- end
- end
- f.close
- end
-
- new.sub!(/\.jpeg$/io) do
- '.jpg'
- end
- new.sub!(/\.tiff$/io) do
- '.tif'
- end
- new.sub!(/\.ai$/io) do
- '.eps'
- end
- new.sub!(/\.ai([a-z0-9]*)$/io) do
- '-' + $1 + '.eps'
- end
- new
-
- end
-
- def Tool.cleanfilename(old,logging=nil)
-
- return old if not FileTest.file?(old)
-
- new = checksuffix(simplefilename(old))
- unless new == old
- begin # bugged, should only be name, not path
- File.rename(old,new)
- logging.report("renaming fuzzy name #{old} to #{new}") unless logging
- return old
- rescue
- logging.report("unable to rename fuzzy name #{old} to #{new}") unless logging
- end
- end
- return new
-
- end
-
- def Tool.servername
- host = Socket::gethostname
- begin
- Socket::gethostbyname(host)[0]
- rescue
- host
- end
- end
-
- # print file_platform(ARGV[0])
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/base/variables.rb b/Master/texmf-dist/scripts/context/ruby/base/variables.rb
deleted file mode 100644
index 403b57716f4..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/base/variables.rb
+++ /dev/null
@@ -1,132 +0,0 @@
-# module : base/variables
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# ['base/tool','tool'].each do |r| begin require r ; rescue Exception ; else break ; end ; end
-
-require 'base/tool'
-
-class Hash
-
- def nothing?(id)
- ! self[id] || self[id].empty?
- end
-
- def subset(pattern)
- h = Hash.new
- p = pattern.gsub(/([\.\:\-])/) do "\\#{$1}" end
- r = /^#{p}/
- self.keys.each do |k|
- h[k] = self[k].dup if k =~ r
- end
- return h
- end
-
-end
-
-class ExtendedHash < Hash
-
- @@re_var_a = /\%(.*?)\%/
- @@re_var_b = /\$\((.*?)\)/
-
- def set(key,value='',resolve=true)
- if value then
- self[key] = if resolve then resolved(value.to_s) else value.to_s end
- else
- self[key] = ''
- end
- end
-
- def replace(key,value='')
- self[key] = value if self?(key)
- end
-
- def get(key,default='')
- if self.key?(key) then self[key] else default end
- end
-
- def true?(key)
- self[key] =~ /^(yes|on|true|enable|enabled|y|start)$/io rescue false
- end
-
- def resolved(str)
- begin
- str.to_s.gsub(@@re_var_a) do
- self[$1] || ''
- end.gsub(@@re_var_b) do
- self[$1] || ''
- end
- rescue
- str.to_s rescue ''
- end
- end
-
- def check(key,default='')
- if self.key?(key) then
- if self[key].empty? then self[key] = (default || '') end
- else
- self[key] = (default || '')
- end
- end
-
- def checked(key,default='')
- if self.key?(key) then
- if self[key].empty? then default else self[key] end
- else
- default
- end
- end
-
- def empty?(key)
- self[key].empty?
- end
-
- # def downcase(key)
- # self[key].downcase!
- # end
-
-end
-
-# the next one is obsolete so we need to replace things
-
-module Variables
-
- def setvariable(key,value='')
- @variables[key] = value
- end
-
- def replacevariable(key,value='')
- @variables[key] = value if @variables.key?(key)
- end
-
- def getvariable(key,default='')
- if @variables.key?(key) then @variables[key] else default end
- end
-
- def truevariable(key)
- @variables[key] =~ /^(yes|on|true)$/io rescue false
- end
-
- def checkedvariable(str,default='')
- if @variables.key?(key) then
- if @variables[key].empty? then default else @variables[key] end
- else
- default
- end
- end
-
- def report(*str)
- @logger.report(*str)
- end
-
- def debug(*str)
- @logger.debug(str)
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/concheck.rb b/Master/texmf-dist/scripts/context/ruby/concheck.rb
deleted file mode 100644
index 3db3e5148bf..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/concheck.rb
+++ /dev/null
@@ -1,471 +0,0 @@
-# Program : concheck (tex & context syntax checker)
-# Copyright : PRAGMA ADE / Hasselt NL / www.pragma-ade.com
-# Author : Hans Hagen
-# Version : 1.1 / 2003.08.18
-
-# remarks:
-#
-# - the error messages are formatted like tex's messages so that scite can see them
-# - begin and end tags are only tested on a per line basis because we assume clean sources
-# - maybe i'll add begin{something} ... end{something} checking
-
-# # example validation file
-#
-# begin interface en
-#
-# 1 text
-# 4 Question
-# 0 endinput
-# 0 setupsomething
-# 0 chapter
-#
-# end interface en
-
-# nicer
-
-# class Interface
-
- # def initialize (language = 'unknown')
- # @valid = Array.new
- # @language = language
- # end
-
- # def register (left, right)
- # @valid.push([left,right])
- # end
-
-# end
-
-# $interfaces = Hash.new
-
-# $interfaces['en'] = Interface.new('english')
-# $interfaces['nl'] = Interface.new('dutch')
-
-# $interfaces['en'].add('\\\\start','\\\\stop')
-# $interfaces['en'].add('\\\\begin','\\\\end')
-# $interfaces['en'].add('\\\\Start','\\\\Stop')
-# $interfaces['en'].add('\\\\Begin','\\\\End')
-
-# $interfaces['nl'].add('\\\\start','\\\\stop')
-# $interfaces['nl'].add('\\\\beginvan','\\\\eindvan')
-# $interfaces['nl'].add('\\\\Start','\\\\Stop')
-# $interfaces['nl'].add('\\\\BeginVan','\\\\Eindvan')
-
-# rest todo
-
-$valid = Hash.new
-
-$valid['en'] = Array.new
-$valid['nl'] = Array.new
-
-#$valid['en'].push(['',''])
-$valid['en'].push(['\\\\start','\\\\stop'])
-$valid['en'].push(['\\\\begin','\\\\end'])
-$valid['en'].push(['\\\\Start','\\\\Stop'])
-$valid['en'].push(['\\\\Begin','\\\\End'])
-
-#$valid['nl'].push(['',''])
-$valid['nl'].push(['\\\\start','\\\\stop'])
-$valid['nl'].push(['\\\\beginvan','\\\\eindvan'])
-$valid['nl'].push(['\\\\Start','\\\\Stop'])
-$valid['nl'].push(['\\\\BeginVan','\\\\Eindvan'])
-
-$valid_tex = "\\\\end\(input|insert|csname|linechar|graf|buffer|strut\)"
-$valid_mp = "(enddef||end||endinput)"
-
-$start_verbatim = Hash.new
-$stop_verbatim = Hash.new
-
-$start_verbatim['en'] = '\\\\starttyping'
-$start_verbatim['nl'] = '\\\\starttypen'
-
-$stop_verbatim['en'] = '\\\\stoptyping'
-$stop_verbatim['nl'] = '\\\\stoptypen'
-
-def message(str, filename=nil, line=nil, column=nil)
- if filename then
- if line then
- if column then
- puts("error in file #{filename} at line #{line} in column #{column}: #{str}\n")
- else
- puts("error in file #{filename} at line #{line}: #{str}\n")
- end
- else
- puts("file #{filename}: #{str}\n")
- end
- else
- puts(str+"\n")
- end
-end
-
-def load_file (filename='')
- begin
- data = IO.readlines(filename)
- data.collect! do |d|
- if d =~ /^\s*%/o then
- ''
- elsif d =~ /(.*?[^\\])%.*$/o then
- $1
- else
- d
- end
- end
- rescue
- message("provide proper filename")
- return nil
- end
- # print data.to_s + "\n"
- return data
-end
-
-def guess_interface(data)
- if data.first =~ /^%.*interface\=(.*)\s*/ then
- return $1
- else
- data.each do |line|
- case line
- when /\\(starttekst|stoptekst|startonderdeel|startdocument|startoverzicht)/o then return 'nl'
- when /\\(stelle|verwende|umgebung|benutze)/o then return 'de'
- when /\\(stel|gebruik|omgeving)/ then return 'nl'
- when /\\(use|setup|environment)/ then return 'en'
- when /\\(usa|imposta|ambiente)/ then return 'it'
- when /(height|width|style)=/ then return 'en'
- when /(hoehe|breite|schrift)=/ then return 'de'
- when /(hoogte|breedte|letter)=/ then return 'nl'
- when /(altezza|ampiezza|stile)=/ then return 'it'
- when /externfiguur/ then return 'nl'
- when /externalfigure/ then return 'en'
- when /externeabbildung/ then return 'de'
- when /figuraesterna/ then return 'it'
- end
- end
- return 'en'
- end
-end
-
-def cleanup_data(data, interface='en')
- verbatim = 0
- re_start = /^\s*#{$start_verbatim[interface]}/
- re_stop = /^\s*#{$stop_verbatim[interface]}/
- data.collect! do |d|
- if d =~ re_start then
- verbatim += 1
- if verbatim>1 then
- ''
- else
- d
- end
- elsif d =~ re_stop then
- verbatim -= 1
- if verbatim>0 then
- ''
- else
- d
- end
- elsif verbatim > 0 then
- ''
- else
- d
- end
- end
- return data
-end
-
-def load_valid(data, interface=nil)
- if data && (data.first =~ /^%.*valid\=(.*)\s*/)
- filename = $1
- filename = '../' + filename unless test(?f,filename)
- filename = '../' + filename unless test(?f,filename)
- if test(?f,filename) then
- interface = guess_interface(data) unless interface
- if $valid.has_key?(interface) then
- interface = $valid[interface]
- else
- interface = $valid['en']
- end
- begin
- message("loading validation file",filename)
- validkeys = Hash.new
- line = 1
- IO.readlines(filename).each do |l|
- if l =~ /\s+[\#\%]/io then
- # ignore line
- elsif l =~ /^\s*(begin|end)\s+interface\s+([a-z][a-z])/o then
- # not yet supported
- elsif l =~ /^\s*(\d+)\s+([a-zA-Z]*)$/o then
- type, key = $1.to_i, $2.strip
- if interface[type] then
- validkeys[interface[type].first+key] = true
- validkeys[interface[type].last+key] = true
- else
- error_message(filename,line,nil,'wrong definition')
- end
- end
- line += 1
- end
- if validkeys then
- message("#{validkeys.length} validation keys loaded",filename)
- end
- return validkeys
- rescue
- message("invalid validation file",filename)
- end
- else
- message("unknown validation file", filename)
- end
- else
- message("no extra validation file specified")
- end
- return nil
-end
-
-def some_chr_error(data, filename, left, right)
- levels = Array.new
- for line in 0..data.length-1 do
- str = data[line]
- # str = data[line].gsub(/\\[\#{left}\#{right}]/,'')
- column = 0
- while column<str.length do
- case str[column].chr
- when "\%" then
- break
- when "\\" then
- column += 2
- when left then
- levels.push([line,column])
- column += 1
- when right then
- if levels.pop
- column += 1
- else
- message("missing #{left} for #{right}",filename,line+1,column+1)
- return true
- end
- else
- column += 1
- end
- end
- end
- if levels && levels.length>0 then
- levels.each do |l|
- column = l.pop
- line = l.pop
- message("missing #{right} for #{left}",filename,line+1,column+1)
- end
- return true
- else
- return false
- end
-end
-
-def some_wrd_error(data, filename, start, stop, ignore)
- levels = Array.new
- len = 0
- re_start = /[^\%]*(#{start})([a-zA-Z]*)/
- re_stop = /[^\%]*(#{stop})([a-zA-Z]*)/
- re_ignore = /#{ignore}.*/
- str_start = start.gsub(/\\+/,'\\')
- str_stop = stop.gsub(/\\+/,'\\')
- line = 0
- while line<data.length do
- dataline = data[line].split(/[^\\A-Za-z]/)
- if dataline.length>0 then
- # todo: more on one line
- dataline.each do |dataword|
- case dataword
- when re_ignore then
- # just go on
- when re_start then
- levels.push([line,$2])
- # print ' '*levels.length + '>' + $2 + "\n"
- when re_stop then
- # print ' '*levels.length + '<' + $2 + "\n"
- if levels && levels.last && (levels.last[1] == $2) then
- levels.pop
- elsif levels && levels.last then
- message("#{str_stop}#{levels.last[1]} expected instead of #{str_stop}#{$2}",filename,line+1)
- return true
- else
- message("missing #{str_start}#{$2} for #{str_stop}#{$2}",filename,line+1)
- return true
- end
- else
- # just go on
- end
- end
- end
- line += 1
- end
- if levels && levels.length>0 then
- levels.each do |l|
- text = l.pop
- line = l.pop
- message("missing #{str_stop}#{text} for #{str_start}#{text}",filename,line+1)
- end
- return true
- else
- return false
- end
-end
-
-def some_sym_error (data, filename, symbol, template=false)
- saved = Array.new
- inside = false
- level = 0
- for line in 0..data.length-1 do
- str = data[line]
- column = 0
- while column<str.length do
- case str[column].chr
- when "[" then
- level += 1 if template
- when "]" then
- level -= 1 if template && level > 0
- when "\%" then
- break
- when "\\" then
- column += 1
- when symbol then
- if level == 0 then
- inside = ! inside
- saved = [line,column]
- else
- # we're in some kind of template or so
- end
- else
- # go on
- end
- column += 1
- end
- end
- if inside && saved && level == 0 then
- column = saved.pop
- line = saved.pop
- message("missing #{symbol} for #{symbol}",filename,line+1)
- return true
- else
- return false
- end
-end
-
-def some_key_error(data, filename, valid)
- return if (! valid) || (valid.length == 0)
- error = false
- # data.foreach do |line| ... end
- for line in 0..data.length-1 do
- data[line].scan(/\\([a-zA-Z]+)/io) do
- unless valid.has_key?($1) then
- message("unknown command \\#{$1}",filename,line+1)
- error = true
- end
- end
- end
- return error
-end
-
-# todo : language dependent
-
-def check_file_tex (filename)
- error = false
- if data = load_file(filename) then
- message("checking tex file", filename)
- interface = guess_interface(data)
- valid = load_valid(data,interface)
- data = cleanup_data(data,interface)
- # data.each do |d| print d end
- $valid[interface].each do |v|
- if some_wrd_error(data, filename, v[0], v[1] ,$valid_tex) then
- error = true
- break
- end
- end
- # return false if some_wrd_error(data, filename, '\\\\start' , '\\\\stop' , $valid_tex)
- # return false if some_wrd_error(data, filename, '\\\\Start' , '\\\\Stop' , $valid_tex)
- # return false if some_wrd_error(data, filename, '\\\\beginvan', '\\\\eindvan', $valid_tex)
- # return false if some_wrd_error(data, filename, '\\\\begin' , '\\\\end|\\\\eind', $valid_tex)
- error = true if some_sym_error(data, filename, '$', false)
- error = true if some_sym_error(data, filename, '|', true)
- error = true if some_chr_error(data, filename, '{', '}')
- error = true if some_chr_error(data, filename, '[', ']')
- error = true if some_chr_error(data, filename, '(', ')')
- error = true if some_key_error(data, filename, valid)
- message("no errors in tex code", filename) unless error
- return error
- else
- return false
- end
-end
-
-def check_file_mp (filename)
- error = false
- if data = load_file(filename) then
- message("checking metapost file", filename)
- interface = guess_interface(data)
- valid = load_valid(data,interface)
- $valid[interface].each do |v|
- if some_wrd_error(data, filename, v[0], v[1] ,$valid_tex) then
- error = true
- break
- end
- end
- # return false if some_wrd_error(data, filename, '', 'begin', 'end', $valid_mp)
- error = true if some_chr_error(data, filename, '{', '}')
- error = true if some_chr_error(data, filename, '[', ']')
- error = true if some_chr_error(data, filename, '(', ')')
- error = true if some_key_error(data, filename, valid)
- message("no errors in metapost code", filename) unless error
- return error
- else
- return false
- end
-end
-
-def check_file_text(filename='')
- if data = load_file(filename) then
- for line in 0..data.length-1 do
- # case data[line]
- # when /\s([\:\;\,\.\?\!])/ then
- # message("space before #{$1}",filename,line+1)
- # when /\D([\:\;\,\.\?\!])\S/ then
- # message("no space after #{$1}",filename,line+1)
- # end
- if data[line] =~ /\s([\:\;\,\.\?\!])/ then
- message("space before #{$1}",filename,line+1)
- else
- data[line].gsub!(/\[.*?\]/o, '')
- data[line].gsub!(/\(.*?\)/o, '')
- data[line].gsub!(/\[.*?$/o, '')
- data[line].gsub!(/^.*?\]/o, '')
- if data[line] =~ /\D([\:\;\,\.\?\!])\S/ then
- message("no space after #{$1}",filename,line+1)
- end
- end
- end
- end
-end
-
-def check_file(filename='')
- case filename
- when '' then
- message("provide filename")
- return false
- when /\.(tex|mk.+)$/i then
- return check_file_tex(filename) # && check_file_text(filename)
- when /\.mp$/i then
- return check_file_mp(filename)
- else
- message("only tex and metapost files are checked")
- return false
- end
-end
-
-if ARGV.size > 0 then
- someerror = false
- ARGV.each do |filename|
- somerror = true if check_file(filename)
- end
- exit (if someerror then 1 else 0 end)
-else
- exit 1
-end
-
diff --git a/Master/texmf-dist/scripts/context/ruby/ctxtools.rb b/Master/texmf-dist/scripts/context/ruby/ctxtools.rb
deleted file mode 100644
index f6493a3fcd3..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/ctxtools.rb
+++ /dev/null
@@ -1,2779 +0,0 @@
-#!/usr/bin/env ruby
-#encoding: ASCII-8BIT
-
-# program : ctxtools
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2004-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# This script will harbor some handy manipulations on context
-# related files.
-
-# todo: move scite here
-#
-# todo: move kpse call to kpse class/module, faster and better
-
-# Taco Hoekwater on patterns and lig building (see 'agr'):
-#
-# Any direct use of a ligature (as accessed by \char or through active
-# characters) is wrong and will create faulty hyphenation. Normally,
-# when TeX sees "office", it has six tokens, and it knows from the
-# patterns that it can hyphenate between the "ff". It will build an
-# internal list of four nodes, like this:
-#
-# [char, o , ffi ]
-# [lig , ffi, c ,[f,f,i]]
-# [char, c , e ]
-# [char, e , NULL]
-#
-# as you can see from the ffi line, it has remembered the original
-# characters. While hyphenating, it temporarily changes back to
-# that, then re-instates the ligature afterwards.
-#
-# If you feed it the ligature directly, like so:
-#
-# [char, o , ffi ]
-# [char, ffi , c ]
-# [char, c , e ]
-# [char, e , NULL]
-#
-# it cannot do that (it tries to hyphenate as if the "ffi" was a
-# character), and the result is wrong hyphenation.
-
-banner = ['CtxTools', 'version 1.3.5', '2004/2008', 'PRAGMA ADE']
-
-$: << File.expand_path(File.dirname($0)) ; $: << File.join($:.last,'lib') ; $:.uniq!
-
-require 'base/switch'
-require 'base/logger'
-require 'base/system'
-require 'base/kpse'
-require 'base/file'
-
-require 'rexml/document'
-require 'net/http'
-require 'fileutils'
-# require 'ftools'
-require 'kconv'
-
-exit if defined?(REQUIRE2LIB)
-
-class String
-
- def i_translate(element, attribute, category)
- self.gsub!(/(<#{element}.*?#{attribute}=)([\"\'])(.*?)\2/) do
- if category.key?($3) then
- # puts "#{element} #{$3} -> #{category[$3]}\n" if element == 'cd:inherit'
- # puts "#{element} #{$3} => #{category[$3]}\n" if element == 'cd:command'
- "#{$1}#{$2}#{category[$3]}#{$2}"
- else
- # puts "#{element} #{$3} -> ?\n" if element == 'cd:inherit'
- # puts "#{element} #{$3} => ?\n" if element == 'cd:command'
- "#{$1}#{$2}#{$3}#{$2}" # unchanged
- end
- end
- end
-
- def i_load(element, category)
- self.scan(/<#{element}.*?name=([\"\'])(.*?)\1.*?value=\1(.*?)\1/) do
- category[$2] = $3
- end
- end
-
- def nosuffix(suffix)
- self.sub(/\.#{suffix}/,'') # no /o
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- public
-
- def touchcontextfile
- dowithcontextfile(1)
- end
-
- def contextversion
- dowithcontextfile(2)
- end
-
- private
-
- def dowithcontextfile(action)
- maincontextfile = 'context.tex'
- unless FileTest.file?(maincontextfile) then
- begin
- maincontextfile = Kpse.found(maincontextfile,'context')
- rescue
- maincontextfile = ''
- end
- end
- unless maincontextfile.empty? then
- nextcontextfile = maincontextfile.sub(/context\.tex$/,"cont-new.tex")
- case action
- when 1 then
- touchfile(maincontextfile)
- touchfile(nextcontextfile,@@newcontextversion)
- when 2 then
- reportversion(maincontextfile)
- reportversion(nextcontextfile,@@newcontextversion)
- end
- end
-
- end
-
- @@contextversion = "\\\\contextversion"
- @@newcontextversion = "\\\\newcontextversion"
-
- def touchfile(filename,command=@@contextversion)
-
- if FileTest.file?(filename) then
- if data = IO.read(filename) then
- timestamp = Time.now.strftime('%Y.%m.%d %H:%M')
- prevstamp = ''
- begin
- data.gsub!(/#{command}\{(\d+\.\d+\.\d+.*?)\}/) do
- prevstamp = $1
- "#{command.sub(/(\\)+/,"\\")}{#{timestamp}}"
- end
- rescue
- else
- begin
- File.delete(filename+'.old')
- rescue
- end
- begin
- File.copy(filename,filename+'.old')
- rescue
- end
- begin
- if f = File.open(filename,'w') then
- f.puts(data)
- f.close
- end
- rescue
- end
- end
- if prevstamp.empty? then
- report("#{filename} is not updated, no timestamp found")
- else
- report("#{filename} is updated from #{prevstamp} to #{timestamp}")
- end
- end
- else
- report("#{filename} is not found")
- end
-
- end
-
- def reportversion(filename,command=@@contextversion)
-
- version = 'unknown'
- begin
- if FileTest.file?(filename) && IO.read(filename).match(/#{command}\{(\d+\.\d+\.\d+.*?)\}/) then
- version = $1
- end
- rescue
- end
- if @commandline.option("pipe") then
- print version
- else
- report("context version: #{version} (#{filename})")
- end
-
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- public
-
- def jeditinterface
- editinterface('jedit')
- end
-
- def bbeditinterface
- editinterface('bbedit')
- end
-
- def sciteinterface
- editinterface('scite')
- end
-
- def rawinterface
- editinterface('raw')
- end
-
- private
-
- def editinterface(type='raw')
-
- return unless FileTest.file?("cont-en.xml")
-
- interfaces = @commandline.arguments
-
- if interfaces.empty? then
- interfaces = ['en','cs','de','it','nl','ro','fr']
- end
-
- interfaces.each do |interface|
- begin
- collection = Hash.new
- mappings = Hash.new
- if f = open("keys-#{interface}.xml") then
- while str = f.gets do
- if str =~ /\<cd\:command\s+name=\"(.*?)\"\s+value=\"(.*?)\".*?\>/o then
- mappings[$1] = $2
- end
- end
- f.close
- if f = open("cont-en.xml") then
- while str = f.gets do
- if str =~ /\<cd\:command\s+name=\"(.*?)\"\s+type=\"environment\".*?\>/o then
- collection["start#{mappings[$1]}"] = ''
- collection["stop#{mappings[$1]}"] = ''
- elsif str =~ /\<cd\:command\s+name=\"(.*?)\".*?\>/o then
- collection["#{mappings[$1]}"] = ''
- end
- end
- f.close
- case type
- when 'jedit' then
- if f = open("context-jedit-#{interface}.xml", 'w') then
- f.puts("<?xml version='1.0'?>\n\n")
- f.puts("<!DOCTYPE MODE SYSTEM 'xmode.dtd'>\n\n")
- f.puts("<MODE>\n")
- f.puts(" <RULES>\n")
- f.puts(" <KEYWORDS>\n")
- collection.keys.sort.each do |name|
- f.puts(" <KEYWORD2>\\#{name}</KEYWORD2>\n") unless name.empty?
- end
- f.puts(" </KEYWORDS>\n")
- f.puts(" </RULES>\n")
- f.puts("</MODE>\n")
- f.close
- end
- when 'bbedit' then
- if f = open("context-bbedit-#{interface}.xml", 'w') then
- f.puts("<?xml version='1.0'?>\n\n")
- f.puts("<key>BBLMKeywordList</key>\n")
- f.puts("<array>\n")
- collection.keys.sort.each do |name|
- f.puts(" <string>\\#{name}</string>\n") unless name.empty?
- end
- f.puts("</array>\n")
- f.close
- end
- when 'scite' then
- if f = open("cont-#{interface}-scite.properties", 'w') then
- i = 0
- f.write("keywordclass.macros.context.#{interface}=")
- collection.keys.sort.each do |name|
- unless name.empty? then
- if i==0 then
- f.write("\\\n ")
- i = 5
- else
- i = i - 1
- end
- f.write("#{name} ")
- end
- end
- f.write("\n")
- f.close
- end
- else # raw
- collection.keys.sort.each do |name|
- puts("\\#{name}\n") unless name.empty?
- end
- end
- end
- end
- end
- end
-
- end
-
-end
-
-# class Commands
-#
-# include CommandBase
-#
-# public
-#
-# def translateinterface
-#
-# # since we know what kind of file we're dealing with,
-# # we do it quick and dirty instead of using rexml or
-# # xslt
-#
-# interfaces = @commandline.arguments
-#
-# if interfaces.empty? then
-# interfaces = ['cs','de','it','nl','ro','fr']
-# else
-# interfaces.delete('en')
-# end
-#
-# interfaces.flatten.each do |interface|
-#
-# variables, constants, strings, list, data = Hash.new, Hash.new, Hash.new, '', ''
-#
-# keyfile, intfile, outfile = "keys-#{interface}.xml", "cont-en.xml", "cont-#{interface}.xml"
-#
-# report("generating #{keyfile}")
-#
-# begin
-# one = "texexec --make --all #{interface}"
-# two = "texexec --batch --silent --interface=#{interface} x-set-01"
-# if @commandline.option("force") then
-# system(one)
-# system(two)
-# elsif not system(two) then
-# system(one)
-# system(two)
-# end
-# rescue
-# end
-#
-# unless File.file?(keyfile) then
-# report("no #{keyfile} generated")
-# next
-# end
-#
-# report("loading #{keyfile}")
-#
-# begin
-# list = IO.read(keyfile)
-# rescue
-# list = empty
-# end
-#
-# if list.empty? then
-# report("error in loading #{keyfile}")
-# next
-# end
-#
-# list.i_load('cd:variable', variables)
-# list.i_load('cd:constant', constants)
-# list.i_load('cd:command' , strings)
-# # list.i_load('cd:element' , strings)
-#
-# report("loading #{intfile}")
-#
-# begin
-# data = IO.read(intfile)
-# rescue
-# data = empty
-# end
-#
-# if data.empty? then
-# report("error in loading #{intfile}")
-# next
-# end
-#
-# report("translating interface en to #{interface}")
-#
-# data.i_translate('cd:string' , 'value', strings)
-# data.i_translate('cd:variable' , 'value', variables)
-# data.i_translate('cd:parameter', 'name' , constants)
-# data.i_translate('cd:constant' , 'type' , variables)
-# data.i_translate('cd:variable' , 'type' , variables)
-# data.i_translate('cd:inherit' , 'name' , strings)
-# # data.i_translate('cd:command' , 'name' , strings)
-#
-# data.gsub!(/(\<cd\:interface[^\>]*?language=")en(")/) do
-# $1 + interface + $2
-# end
-#
-# report("saving #{outfile}")
-#
-# begin
-# if f = File.open(outfile, 'w') then
-# f.write(data)
-# f.close
-# end
-# rescue
-# end
-#
-# end
-#
-# end
-#
-# end
-
-class Commands
-
- include CommandBase
-
- public
-
- # faster is to glob the whole dir and regexp over that list
-
- def purgefiles
-
- pattern = @commandline.arguments
- purgeall = @commandline.option("all")
- recurse = @commandline.option("recurse")
-
- $dontaskprefixes.push(Dir.glob("mpx-*"))
-
- if purgeall then
- $dontaskprefixes.push(Dir.glob("*.tex.prep"))
- $dontaskprefixes.push(Dir.glob("*.xml.prep"))
- end
-
- $dontaskprefixes.flatten!
- $dontaskprefixes.sort!
-
- if purgeall then
- $forsuresuffixes.push($texnonesuffixes)
- $texnonesuffixes = []
- $forsuresuffixes.flatten!
- end
-
- if ! pattern || pattern.empty? then
- globbed = if recurse then "**/*.*" else "*.*" end
- files = Dir.glob(globbed)
- report("purging#{if purgeall then ' all' end} temporary files : #{globbed}")
- else
- report("purging#{if purgeall then ' all' end} temporary files : #{pattern.join(' ')}")
- pattern.each do |pat|
- nosuf = File.unsuffixed(pat)
- globbed = if recurse then "**/#{nosuf}-*.*" else "#{nosuf}-*.*" end
- report("checking files that match '#{globbed}'")
- files = Dir.glob(globbed)
- globbed = if recurse then "**/#{nosuf}.*" else "#{nosuf}.*" end
- report("checking files that match '#{globbed}'")
- files.push(Dir.glob(globbed))
- end
- end
- files.flatten!
- files.sort!
-
- $dontaskprefixes.each do |file|
- removecontextfile(file)
- end
- $dontasksuffixes.each do |suffix|
- files.each do |file|
- removecontextfile(file) if file =~ /#{suffix}$/i
- end
- end
- $forsuresuffixes.each do |suffix|
- files.each do |file|
- removecontextfile(file) if file =~ /\.#{suffix}$/i
- end
- end
- files.each do |file|
- if file =~ /(.*?)\.\d+$/o then
- basename = $1
- if file =~ /mp(graph|run)/o || FileTest.file?("#{basename}.mp") then
- removecontextfile($file)
- end
- end
- end
- $dummyfiles.each do |file|
- (File.delete(file) if (FileTest.size?(file) rescue 10) < 10) rescue false
- end
- $texnonesuffixes.each do |suffix|
- files.each do |file|
- if file =~ /(.*)\.#{suffix}$/i then
- if FileTest.file?("#{$1}.tex") || FileTest.file?("#{$1}.xml") || FileTest.file?("#{$1}.fo") then
- keepcontextfile(file)
- else
- strippedname = $1.gsub(/\-[a-z]$/io, '')
- if FileTest.file?("#{strippedname}.tex") || FileTest.file?("#{strippedname}.xml") then
- keepcontextfile("#{file} (potential result file)")
- else
- removecontextfile(file)
- end
- end
- end
- end
- end
-
- files = Dir.glob("*.*")
- $dontasksuffixes.each do |suffix|
- files.each do |file|
- removecontextfile(file) if file =~ /^#{suffix}$/i
- end
- end
-
- if $removedfiles || $keptfiles || $persistentfiles then
- report("removed files : #{$removedfiles}")
- report("kept files : #{$keptfiles}")
- report("persistent files : #{$persistentfiles}")
- report("reclaimed bytes : #{$reclaimedbytes}")
- end
-
- end
-
- private
-
- $removedfiles = 0
- $keptfiles = 0
- $persistentfiles = 0
- $reclaimedbytes = 0
-
- $dontaskprefixes = [
- # "tex-form.tex", "tex-edit.tex", "tex-temp.tex",
- "texexec.tex", "texexec.tui", "texexec.tuo",
- "texexec.tuc", "texexec.tua",
- "texexec.ps", "texexec.pdf", "texexec.dvi",
- "cont-opt.tex", "cont-opt.bak"
- ]
- $dontasksuffixes = [
- "mp(graph|run)\\.mp", "mp(graph|run)\\.mpd", "mp(graph|run)\\.mpo", "mp(graph|run)\\.mpy",
- "mp(graph|run)\\.\\d+", "mp(graph|run)\\.mp.keep",
- "xlscript\\.xsl"
- ]
- $forsuresuffixes = [
- "tui", "tua", "tup", "ted", "tes", "top",
- "log", "tmp", "run", "bck", "rlg",
- "mpt", "mpx", "mpd", "mpo", "mpb",
- "ctl",
- "pgf", "synctex.gz",
- "tmp.md5", "tmp.out"
- ]
- $texonlysuffixes = [
- "dvi", "ps", "pdf"
- ]
- $texnonesuffixes = [
- "tuo", "tub", "top", "tuc"
- ]
- $dummyfiles = [
- # "mpgraph"
- ]
-
- def removecontextfile (filename)
- if filename && FileTest.file?(filename) then
- begin
- filesize = FileTest.size(filename)
- File.delete(filename)
- rescue
- report("problematic : #{filename}")
- else
- if FileTest.file?(filename) then
- $persistentfiles += 1
- report("persistent : #{filename}")
- else
- $removedfiles += 1
- $reclaimedbytes += filesize
- report("removed : #{filename}")
- end
- end
- end
- end
-
- def keepcontextfile (filename)
- if filename && FileTest.file?(filename) then
- $keptfiles += 1
- report("not removed : #{filename}")
- end
- end
-
-end
-
-#D Documentation can be woven into a source file. The next
-#D routine generates a new, \TEX\ ready file with the
-#D documentation and source fragments properly tagged. The
-#D documentation is included as comment:
-#D
-#D \starttypen
-#D %D ...... some kind of documentation
-#D %M ...... macros needed for documenation
-#D %S B begin skipping
-#D %S E end skipping
-#D \stoptypen
-#D
-#D The most important tag is \type {%D}. Both \TEX\ and \METAPOST\
-#D files use \type{%} as a comment chacacter, while \PERL, \RUBY\
-#D and alike use \type{#}. Therefore \type{#D} is also handled.
-#D
-#D The generated file gets the suffix \type{ted} and is
-#D structured as:
-#D
-#D \starttypen
-#D \startmoduledocumentation[type=suffix]
-#D \startdocumentation
-#D \stopdocumentation
-#D \startdefinition
-#D \stopdefinition
-#D \stopmoduledocumentation
-#D \stoptypen
-#D
-#D Macro definitions specific to the documentation are not
-#D surrounded by start||stop commands. The suffix specifaction
-#D can be overruled at runtime, but defaults to the file
-#D extension. This specification can be used for language
-#D depended verbatim typesetting.
-
-class Commands
-
- include CommandBase
-
- public
-
- def documentation
- files = @commandline.arguments
- processtype = @commandline.option("type")
- files.each do |fullname|
- if fullname =~ /(.*)\.(.+?)$/o then
- filename, filesuffix = $1, $2
- else
- filename, filesuffix = fullname, 'tex'
- end
- filesuffix = 'tex' if filesuffix.empty?
- fullname, resultname = "#{filename}.#{filesuffix}", "#{filename}.ted"
- if ! FileTest.file?(fullname)
- report("empty input file #{fullname}")
- elsif ! tex = File.open(fullname)
- report("invalid input file #{fullname}")
- elsif ! ted = File.open(resultname,'w') then
- report("unable to openresult file #{resultname}")
- else
- report("input file : #{fullname}")
- report("output file : #{resultname}")
- nofdocuments, nofdefinitions, nofskips = 0, 0, 0
- skiplevel, indocument, indefinition, skippingbang = 0, false, false, false
- if processtype.empty? then
- filetype = filesuffix.downcase.sub(/^mk.+$/,'tex') # make sure that mkii and mkiv files are handled
- else
- filetype = processtype.downcase
- end
- report("filetype : #{filetype}")
- # we need to signal to texexec what interface to use
- firstline = tex.gets
- if firstline =~ /^\%.*interface\=/ then
- ted.puts(firstline)
- else
- tex.rewind # seek(0)
- end
- ted.puts("\\startmoduledocumentation[type=#{filetype}]\n")
- while str = tex.gets do
- if skippingbang then
- skippingbang = false
- else
- str.chomp!
- str.sub!(/\s*$/o, '')
- case str
- when /^[%\#]D($| )/io then
- if skiplevel == 0 then
- someline = if str.length < 3 then "" else str[3,str.length-1] end
- if indocument then
- ted.puts("#{someline}\n")
- else
- if indefinition then
- ted.puts("\\stopdefinition\n")
- indefinition = false
- end
- unless indocument then
- ted.puts("\n\\startdocumentation\n")
- end
- ted.puts("#{someline}\n")
- indocument = true
- nofdocuments += 1
- end
- end
- when /^[%\#]M($| )/io then
- if skiplevel == 0 then
- someline = if str.length < 3 then "" else str[3,str.length-1] end
- ted.puts("#{someline}\n")
- end
- when /^[%\%]S B/io then
- skiplevel += 1
- nofskips += 1
- when /^[%\%]S E/io then
- skiplevel -= 1
- when /^[%\#]/io then
- #nothing
- when /^eval \'\(exit \$\?0\)\' \&\& eval \'exec perl/o then
- skippingbang = true
- else
- if skiplevel == 0 then
- inlocaldocument = indocument
- inlocaldocument = false # else first line skipped when not empty
- someline = str
- if indocument then
- ted.puts("\\stopdocumentation\n")
- indocument = false
- end
- if indefinition then
- if someline.empty? then
- ted.puts("\\stopdefinition\n")
- indefinition = false
- else
- ted.puts("#{someline}\n")
- end
- elsif ! someline.empty? then
- ted.puts("\n\\startdefinition\n")
- indefinition = true
- if inlocaldocument then
- # nothing
- else
- nofdefinitions += 1
- ted.puts("#{someline}\n")
- end
- end
- end
- end
- end
- end
- if indocument then
- ted.puts("\\stopdocumentation\n")
- end
- if indefinition then
- ted.puts("\\stopdefinition\n")
- end
- ted.puts("\\stopmoduledocumentation\n")
- ted.close
-
- if nofdocuments == 0 && nofdefinitions == 0 then
- begin
- File.delete(resultname)
- rescue
- end
- end
- report("documentation sections : #{nofdocuments}")
- report("definition sections : #{nofdefinitions}")
- report("skipped sections : #{nofskips}")
- end
- end
- end
-
-end
-
-#D This feature was needed when \PDFTEX\ could not yet access page object
-#D numbers (versions prior to 1.11).
-
-class Commands
-
- include CommandBase
-
- public
-
- def filterpages # temp feature / no reporting
- filename = @commandline.argument('first')
- filename.sub!(/\.([a-z]+?)$/io,'')
- pdffile = "#{filename}.pdf"
- tuofile = "#{filename}.tuo"
- if FileTest.file?(pdffile) then
- begin
- prevline, n = '', 0
- if (pdf = File.open(pdffile)) && (tuo = File.open(tuofile,'a')) then
- report('filtering page object numbers')
- pdf.binmode
- while line = pdf.gets do
- line.chomp
- # typical pdftex search
- if (line =~ /\/Type \/Page/o) && (prevline =~ /^(\d+)\s+0\s+obj/o) then
- p = $1
- n += 1
- tuo.puts("\\objectreference{PDFP}{#{n}}{#{p}}{#{n}}\n")
- else
- prevline = line
- end
- end
- end
- pdf.close
- tuo.close
- report("number of pages : #{n}")
- rescue
- report("fatal error in filtering pages")
- end
- end
- end
-
-end
-
-# This script is used to generate hyphenation pattern files
-# that suit ConTeXt. One reason for independent files is that
-# over the years too many uncommunicated changes took place
-# as well that inconsistency in content, naming, and location
-# in the texmf tree takes more time than I'm willing to spend
-# on it. Pattern files are normally shipped for LaTeX (and
-# partially plain). A side effect of independent files is that
-# we can make them encoding independent.
-#
-# Maybe I'll make this hyptools.tex
-
-class String
-
- def markbraces
- level = 0
- self.gsub(/([\{\}])/o) do |chr|
- if chr == '{' then
- level = level + 1
- chr = "((+#{level}))"
- elsif chr == '}' then
- chr = "((-#{level}))"
- level = level - 1
- end
- chr
- end
- end
-
- def unmarkbraces
- self.gsub(/\(\(\+\d+?\)\)/o) do
- "{"
- end .gsub(/\(\(\-\d+?\)\)/o) do
- "}"
- end
- end
-
- def getargument(pattern)
- if self =~ /(#{pattern})\s*\(\(\+(\d+)\)\)(.*?)\(\(\-\2\)\)/m then # no /o
- return $3
- else
- return ""
- end
- end
-
- def withargument(pattern, &block)
- if self.markbraces =~ /^(.*)(#{pattern}\s*)\(\(\+(\d+)\)\)(.*?)\(\(\-\3\)\)(.*)$/m then # no /o
- "#{$1.unmarkbraces}#{$2}{#{yield($4.unmarkbraces)}}#{$5.unmarkbraces}"
- else
- self
- end
- end
-
- def filterargument(pattern, &block)
- if self.markbraces =~ /^(.*)(#{pattern}\s*)\(\(\+(\d+)\)\)(.*?)\(\(\-\3\)\)(.*)$/m then # no /o
- yield($4.unmarkbraces)
- else
- self
- end
- end
-
-end
-
-class Language
-
- include CommandBase
-
- def initialize(commandline=nil, language='en', filenames=nil, encoding='ec')
- @commandline= commandline
- @language = language
- @filenames = filenames
- @remapping = Array.new
- @demapping = Array.new
- @cloning = Array.new
- @unicode = Hash.new
- @encoding = encoding
- @data = ''
- @read = ''
- preload_accents()
- preload_unicode() if @commandline.option('utf8')
- case @encoding.downcase
- when 't1', 'ec', 'cork' then preload_vector('ec', 'enco-ec.tex')
- when 'y', 'texnansi' then preload_vector('texnansi', 'enco-ans.tex')
- when 'agr', 'agreek' then preload_vector('agr', 'enco-agr.tex')
- when 't2a' then preload_vector('t2a', 'enco-cyr.tex')
- when 'cyr' then preload_vector() # somehow loading t2a does not work out well
- end
- end
-
- def report(str)
- if @commandline then
- @commandline.report(str)
- else
- puts("#{str}\n")
- end
- end
-
- def remap(from, to)
- @remapping.push([from,to])
- end
- def demap(from, to)
- @demapping.push([from,to])
- end
- def clone(from, to)
- @cloning.push([from,to])
- end
-
- def load(filenames=@filenames)
- found = false
- begin
- if filenames then
- @filenames.each do |fileset|
- [fileset].flatten.each do |filename|
- begin
- if fname = located(filename) then
- data = IO.read(fname)
- @data += data.gsub(/\%.*$/, '').gsub(/\\message\{.*?\}/, '')
- data.gsub!(/(\\patterns|\\hyphenation)\s*\{.*/mo) do '' end
- @read += "\n% preamble of file #{fname}\n\n#{data}\n"
- @data.gsub!(/^[\s\n]+$/moi, '')
- report("file #{fname} is loaded")
- found = true
- break # next fileset
- end
- rescue
- report("file #{filename} is not readable")
- end
- end
- end
- end
- rescue
- end
- return found
- end
-
- def valid?
- ! @data.empty?
- end
-
- def convert
- if @data then
- n = 0
- if true then
- report("")
- ["\\patterns","\\hyphenation"].each do |what|
- @data = @data.withargument(what) do |content|
- report("converting #{what}")
- report("")
- @demapping.each_index do |i|
- content.gsub!(@demapping[i][0], @demapping[i][1])
- end
- content.gsub!(/\\delete\{.*?\}/o) do '' end
- content.gsub!(/\\keep\{(.*?)\}/o) do $1 end
- done = false
- @remapping.each_index do |i|
- from, to, m = @remapping[i][0], @remapping[i][1], 0
- content.gsub!(from) do
- done = true
- m += 1
- "[#{i}]"
- end
- report("#{m.to_s.rjust(5)} entries remapped to #{to}") unless m == 0
- n += m
- end
- content.gsub!(/\[(\d+)\]/o) do
- @remapping[$1.to_i][1]
- end
- report(" nothing remapped") unless done
- @cloning.each_index do |i|
- c = 0
- f, s = @cloning[i][0], @cloning[i][1]
- str = "#{f}|#{s}"
- str.gsub!(/([\[\]])/) do "\\" + "#{$1}" end
- reg = /(#{str})/
- content.gsub!(/(\S*(#{str})\S*)/) do
- a, b = $1, $1
- a.gsub!(reg, f)
- b.gsub!(reg, s)
- c = c + 1
- "#{a} #{b}"
- end
- report("#{c.to_s.rjust(5)} times #{f} cloned to #{s}")
- n += c
- end
- report("")
- content.to_s
- end
- end
- else
- @remapping.each do |k|
- from, to, m = k[0], k[1], 0
- @data.gsub!(from) do
- m += 1
- to
- end
- report("#{m.to_s.rjust(5)} entries remapped to #{to}") unless m == 0
- n += m
- end
- end
- report("#{n} changes in patterns and exceptions")
- if @commandline.option('utf8') then
- n = 0
- @data.gsub!(/\[(.*?)\]/o) do
- n += 1
- @unicode[$1] || $1
- end
- report("#{n} unicode utf8 entries")
- end
- return true
- else
- return false
- end
- end
-
- def comment(str)
- str.gsub!(/^\n/o, '')
- str.chomp!
- if @commandline.option('xml') then
- "<!-- #{str.strip} -->\n\n"
- else
- "% #{str.strip}\n\n"
- end
- end
-
- def content(tag, str)
- lst = str.split(/\s+/)
- lst.collect! do |l|
- l.strip
- end
- if lst.length>0 then
- lst = "\n#{lst.join("\n")}\n"
- else
- lst = ""
- end
- if @commandline.option('xml') then
- lst.gsub!(/\[(.*?)\]/o) do
- "&#{$1};"
- end
- "<#{tag}>#{lst}</#{tag}>\n\n"
- else
- "\\#{tag} \{#{lst}\}\n\n"
- end
- end
-
- def banner
- if @commandline.option('xml') then
- "<?xml version='1.0' standalone='yes' ?>\n\n"
- end
- end
-
- def triggerunicode
- return
- if @commandline.option('utf8') then
- "% xetex needs utf8 encoded patterns and for patterns\n" +
- "% coded as such we need to enable this regime when\n" +
- "% not in xetex; this code will be moved into context\n" +
- "% as soon as we've spread the generic patterns\n" +
- "\n" +
- "\\ifx\\XeTeXversion\\undefined \\else\n" +
- " \\ifx\\enableregime\\undefined \\else\n" +
- " \\enableregime[utf]\n" +
- " \\fi\n" +
- "\\fi\n" +
- "\n"
- end
- end
-
- def save
- xml = @commandline.option("xml")
-
- patname = "lang-#{@language}.pat"
- hypname = "lang-#{@language}.hyp"
- rmename = "lang-#{@language}.rme"
- logname = "lang-#{@language}.log"
-
- desname = "lang-all.xml"
-
- @data.gsub!(/\\[nc]\{(.+?)\}/) do $1 end
- @data.gsub!(/\{\}/) do '' end
- @data.gsub!(/\n+/mo) do "\n" end
- @read.gsub!(/\n+/mo) do "\n" end
-
- description = ''
- commentfile = rmename.dup
-
- begin
- desfile = Kpse.found(desname,'context')
- if f = File.new(desfile) then
- if doc = REXML::Document.new(f) then
- if e = REXML::XPath.first(doc.root,"/descriptions/description[@language='#{@language}']") then
- description = e.to_s
- end
- end
- end
- rescue
- description = ''
- else
- unless description.empty? then
- commentfile = desname.dup
- str = "<!-- copied from lang-all.xml\n\n"
- str << "<?xml version='1.0' standalone='yes'?>\n\n"
- str << description.chomp
- str << "\n\nend of copy -->\n"
- str.gsub!(/^/io, "% ") unless @commandline.option('xml')
- description = comment("begin description data")
- description << str + "\n"
- description << comment("end description data")
- report("description found for language #{@language}")
- end
- end
-
- begin
- if description.empty? || @commandline.option('log') then
- if f = File.open(logname,'w') then
- report("saving #{@remapping.length} remap patterns in #{logname}")
- @remapping.each do |m|
- f.puts("#{m[0].inspect} => #{m[1]}\n")
- end
- f.close
- end
- else
- File.delete(logname) if FileTest.file?(logname)
- end
- rescue
- end
-
- begin
- if description.empty? || @commandline.option('log') then
- if f = File.open(rmename,'w') then
- data = @read.dup
- data.gsub!(/(\s*\n\s*)+/mo, "\n")
- f << comment("comment copied from public hyphenation files}")
- f << comment("source of data: #{@filenames.join(' ')}")
- f << comment("begin original comment")
- f << "#{data}\n"
- f << comment("end original comment")
- f.close
- report("comment saved in file #{rmename}")
- else
- report("file #{rmename} is not writable")
- end
- else
- File.delete(rmename) if FileTest.file?(rmename)
- end
- rescue
- end
-
- begin
- if f = File.open(patname,'w') then
- data = ''
- @data.filterargument('\\patterns') do |content|
- report("merging patterns")
- data += content.strip
- end
- data.gsub!(/(\s*\n\s*)+/mo, "\n")
-
- f << banner
- f << comment("context pattern file, see #{commentfile} for original comment")
- f << comment("source of data: #{@filenames.join(' ')}")
- f << description
- f << comment("begin pattern data")
- f << triggerunicode
- f << content('patterns', data)
- f << comment("end pattern data")
- f.close
- report("patterns saved in file #{patname}")
- else
- report("file #{patname} is not writable")
- end
- rescue
- report("problems with file #{patname}")
- end
-
- begin
- if f = File.open(hypname,'w') then
- data = ''
- @data.filterargument('\\hyphenation') do |content|
- report("merging exceptions")
- data += content.strip
- end
- data.gsub!(/(\s*\n\s*)+/mo, "\n")
- f << banner
- f << comment("context hyphenation file, see #{commentfile} for original comment")
- f << comment("source of data: #{@filenames.join(' ')}")
- f << description
- f << comment("begin hyphenation data")
- f << triggerunicode
- f << content('hyphenation', data)
- f << comment("end hyphenation data")
- f.close
- report("exceptions saved in file #{hypname}")
- else
- report("file #{hypname} is not writable")
- end
- rescue
- report("problems with file #{hypname}")
- end
- end
-
- def process
- load
- if valid? then
- convert
- save
- else
- report("aborted due to missing files")
- end
- end
-
- def Language::generate(commandline, language='', filenames='', encoding='ec')
- if ! language.empty? && ! filenames.empty? then
- commandline.report("processing language #{language}")
- commandline.report("")
- language = Language.new(commandline,language,filenames,encoding)
- if language.load then
- language.convert
- language.save
- commandline.report("")
- end
- end
- end
-
- private
-
- def located(filename)
- begin
- ["context","plain","latex"].each do |name| # fallbacks needed for czech patterns
- fname = Kpse.found(filename, name)
- if FileTest.file?(fname) then
- report("using file #{fname}")
- return fname
- end
- end
- report("file #{filename} is not present")
- return nil
- rescue
- report("file #{filename} cannot be located using kpsewhich")
- return nil
- end
- end
-
- def preload_accents
-
- begin
- if filename = located("enco-acc.tex") then
- if data = IO.read(filename) then
- report("preloading accent conversions")
- data.scan(/\\defineaccent\s*\\*(.+?)\s*\{*(.+?)\}*\s*\{\\(.+?)\}/o) do
- one, two, three = $1, $2, $3
- one.gsub!(/[\`\~\!\^\*\_\-\+\=\:\;\"\'\,\.\?]/o) do
- "\\#{one}"
- end
- remap(/\\#{one} #{two}/, "[#{three}]")
- remap(/\\#{one}#{two}/, "[#{three}]") unless one =~ /[a-zA-Z]/o
- remap(/\\#{one}\{#{two}\}/, "[#{three}]")
- end
- end
- end
- rescue
- end
-
- end
-
- def preload_unicode
-
- # \definecharacter Agrave {\uchar0{192}}
-
- begin
- if filename = located("enco-uc.tex") then
- if data = IO.read(filename) then
- report("preloading unicode conversions")
- data.scan(/\\definecharacter\s*(.+?)\s*\{\\uchar\{*(\d+)\}*\s*\{(\d+)\}/o) do
- one, two, three = $1, $2.to_i, $3.to_i
- @unicode[one] = [(two*256 + three)].pack("U")
- end
- end
- end
- rescue
- report("error in loading unicode mapping (#{$!})")
- end
-
- end
-
- def preload_vector(encoding='', filename='')
-
- # funny polish
-
- case @language
- when 'pl' then
- remap(/\/a/, "[aogonek]") ; remap(/\/A/, "[Aogonek]")
- remap(/\/c/, "[cacute]") ; remap(/\/C/, "[Cacute]")
- remap(/\/e/, "[eogonek]") ; remap(/\/E/, "[Eogonek]")
- remap(/\/l/, "[lstroke]") ; remap(/\/L/, "[Lstroke]")
- remap(/\/n/, "[nacute]") ; remap(/\/N/, "[Nacute]")
- remap(/\/o/, "[oacute]") ; remap(/\/O/, "[Oacute]")
- remap(/\/s/, "[sacute]") ; remap(/\/S/, "[Sacute]")
- remap(/\/x/, "[zacute]") ; remap(/\/X/, "[Zacute]")
- remap(/\/z/, "[zdotaccent]") ; remap(/\/Z/, "[Zdotaccent]")
- when 'sl' then
- remap(/\"c/,"[ccaron]") ; remap(/\"C/,"[Ccaron]")
- remap(/\"s/,"[scaron]") ; remap(/\"S/,"[Scaron]")
- remap(/\"z/,"[zcaron]") ; remap(/\"Z/,"[Zcaron]")
- when 'da' then
- remap(/X/, "[aeligature]")
- remap(/Y/, "[ostroke]")
- remap(/Z/, "[aring]")
- when 'hu' then
- # nothing
- when 'ca' then
- demap(/\\c\{/, "\\delete{")
- when 'de', 'deo' then
- demap(/\\c\{/, "\\delete{")
- demap(/\\n\{/, "\\keep{")
- remap(/\\3/, "[ssharp]")
- remap(/\\9/, "[ssharp]")
- remap(/\"a/, "[adiaeresis]")
- remap(/\"o/, "[odiaeresis]")
- remap(/\"u/, "[udiaeresis]")
- when 'fr' then
- demap(/\\n\{/, "\\delete{")
- remap(/\\ae/, "[aeligature]")
- remap(/\\oe/, "[oeligature]")
- when 'la' then
- # \lccode`'=`' somewhere else, todo
- demap(/\\c\{/, "\\delete{")
- remap(/\\a\s*/, "[aeligature]")
- remap(/\\o\s*/, "[oeligature]")
- when 'agr' then
- # bug fix
- remap("a2|", "[greekalphaiotasub]")
- remap("h2|", "[greeketaiotasub]")
- remap("w2|", "[greekomegaiotasub]")
- remap(">2r1<2r", "[2ῤ1ῥ]")
- remap(">a2n1wdu'", "[ἀ2ν1ωδύ]")
- remap(">e3s2ou'", "[ἐ3σ2ού]")
- # main conversion
- remap(/\<\'a\|/, "[greekalphaiotasubdasiatonos]")
- # remap(/\<\'a\|/, "[greekdasiatonos][greekAlpha][greekiota]")
- remap(/\>\'a\|/, "[greekalphaiotasubpsilitonos]")
- remap(/\<\`a\|/, "[greekalphaiotasubdasiavaria]")
- remap(/\>\`a\|/, "[greekalphaiotasubpsilivaria]")
- remap(/\<\~a\|/, "[greekalphaiotasubdasiaperispomeni]")
- remap(/\>\~a\|/, "[greekalphaiotasubpsiliperispomeni]")
- remap(/\'a\|/, "[greekalphaiotasubtonos]")
- remap(/\`a\|/, "[greekalphaiotasubvaria]")
- remap(/\~a\|/, "[greekalphaiotasubperispomeni]")
- remap(/\<a\|/, "[greekalphaiotasubdasia]")
- remap(/\>a\|/, "[greekalphaiotasubpsili]")
- remap(/a\|/, "[greekalphaiotasub]")
- remap(/\<\'h\|/, "[greeketaiotasubdasiatonos]")
- remap(/\>\'h\|/, "[greeketaiotasubpsilitonos]")
- remap(/\<\`h\|/, "[greeketaiotasubdasiavaria]")
- remap(/\>\`h\|/, "[greeketaiotasubpsilivaria]")
- remap(/\<\~h\|/, "[greeketaiotasubdasiaperispomeni]")
- remap(/\>\~h\|/, "[greeketaiotasubpsiliperispomeni]")
- remap(/\'h\|/, "[greeketaiotasubtonos]")
- remap(/\`h\|/, "[greeketaiotasubvaria]")
- remap(/\~h\|/, "[greeketaiotasubperispomeni]")
- remap(/\<h\|/, "[greeketaiotasubdasia]")
- remap(/\>h\|/, "[greeketaiotasubpsili]")
- remap(/h\|/, "[greeketaiotasub]")
- remap(/\<'w\|/, "[greekomegaiotasubdasiatonos]")
- remap(/\>'w\|/, "[greekomegaiotasubpsilitonos]")
- remap(/\<`w\|/, "[greekomegaiotasubdasiavaria]")
- remap(/\>`w\|/, "[greekomegaiotasubpsilivaria]")
- remap(/\<~w\|/, "[greekomegaiotasubdasiaperispomeni]")
- remap(/\>~w\|/, "[greekomegaiotasubpsiliperispomeni]")
- remap(/\<w\|/, "[greekomegaiotasubdasia]")
- remap(/\>w\|/, "[greekomegaiotasubpsili]")
- remap(/\'w\|/, "[greekomegaiotasubtonos]")
- remap(/\`w\|/, "[greekomegaiotasubvaria]")
- remap(/\~w\|/, "[greekomegaiotasubperispomeni]")
- remap(/w\|/, "[greekomegaiotasub]")
- remap(/\<\'i/, "[greekiotadasiatonos]")
- remap(/\>\'i/, "[greekiotapsilitonos]")
- remap(/\<\`i/, "[greekiotadasiavaria]")
- remap(/\>\`i/, "[greekiotapsilivaria]")
- remap(/\<\~i/, "[greekiotadasiaperispomeni]")
- remap(/\>\~i/, "[greekiotapsiliperispomeni]")
- remap(/\"\'i/, "[greekiotadialytikatonos]")
- remap(/\"\`i/, "[greekiotadialytikavaria]")
- remap(/\"\~i/, "[greekiotadialytikaperispomeni]")
- remap(/\<i/, "[greekiotadasia]")
- remap(/\>i/, "[greekiotapsili]")
- remap(/\'i/, "[greekiotaoxia]")
- remap(/\`i/, "[greekiotavaria]")
- remap(/\~i/, "[greekiotaperispomeni]")
- remap(/\"i/, "[greekiotadialytika]")
- remap(/\>\~e/, "[greekepsilonpsiliperispomeni]")
- remap(/\<\~e/, "[greekepsilondasiaperispomeni]")
- remap(/\<\'e/, "[greekepsilondasiatonos]")
- remap(/\>\'e/, "[greekepsilonpsilitonos]")
- remap(/\<\`e/, "[greekepsilondasiavaria]")
- remap(/\>\`e/, "[greekepsilonpsilivaria]")
- remap(/\<e/, "[greekepsilondasia]")
- remap(/\>e/, "[greekepsilonpsili]")
- remap(/\'e/, "[greekepsilonoxia]")
- remap(/\`e/, "[greekepsilonvaria]")
- remap(/\~e/, "[greekepsilonperispomeni]")
- remap(/\<\'a/, "[greekalphadasiatonos]")
- remap(/\>\'a/, "[greekalphapsilitonos]")
- remap(/\<\`a/, "[greekalphadasiavaria]")
- remap(/\>\`a/, "[greekalphapsilivaria]")
- remap(/\<\~a/, "[greekalphadasiaperispomeni]")
- remap(/\>\~a/, "[greekalphapsiliperispomeni]")
- remap(/\<a/, "[greekalphadasia]")
- remap(/\>a/, "[greekalphapsili]")
- remap(/\'a/, "[greekalphaoxia]")
- remap(/\`a/, "[greekalphavaria]")
- remap(/\~a/, "[greekalphaperispomeni]")
- remap(/\<\'h/, "[greeketadasiatonos]")
- remap(/\>\'h/, "[greeketapsilitonos]")
- remap(/\<\`h/, "[greeketadasiavaria]")
- remap(/\>\`h/, "[greeketapsilivaria]")
- remap(/\<\~h/, "[greeketadasiaperispomeni]")
- remap(/\>\~h/, "[greeketapsiliperispomeni]")
- remap(/\<h/, "[greeketadasia]")
- remap(/\>h/, "[greeketapsili]")
- remap(/\'h/, "[greeketaoxia]")
- remap(/\`h/, "[greeketavaria]")
- remap(/\~h/, "[greeketaperispomeni]")
- remap(/\<\~o/, "[greekomicrondasiaperispomeni]")
- remap(/\>\~o/, "[greekomicronpsiliperispomeni]")
- remap(/\<\'o/, "[greekomicrondasiatonos]")
- remap(/\>\'o/, "[greekomicronpsilitonos]")
- remap(/\<\`o/, "[greekomicrondasiavaria]")
- remap(/\>\`o/, "[greekomicronpsilivaria]")
- remap(/\<o/, "[greekomicrondasia]")
- remap(/\>o/, "[greekomicronpsili]")
- remap(/\'o/, "[greekomicronoxia]")
- remap(/\`o/, "[greekomicronvaria]")
- remap(/\~o/, "[greekomicronperispomeni]")
- remap(/\<\'u/, "[greekupsilondasiatonos]")
- remap(/\>\'u/, "[greekupsilonpsilitonos]")
- remap(/\<\`u/, "[greekupsilondasiavaria]")
- remap(/\>\`u/, "[greekupsilonpsilivaria]")
- remap(/\<\~u/, "[greekupsilondasiaperispomeni]")
- remap(/\>\~u/, "[greekupsilonpsiliperispomeni]")
- remap(/\"\'u/, "[greekupsilondialytikatonos]")
- remap(/\"\`u/, "[greekupsilondialytikavaria]")
- remap(/\"\~u/, "[greekupsilondialytikaperispomeni]")
- remap(/\<u/, "[greekupsilondasia]")
- remap(/\>u/, "[greekupsilonpsili]")
- remap(/\'u/, "[greekupsilonoxia]")
- remap(/\`u/, "[greekupsilonvaria]")
- remap(/\~u/, "[greekupsilonperispomeni]")
- remap(/\"u/, "[greekupsilondiaeresis]")
- remap(/\<\'w/, "[greekomegadasiatonos]")
- remap(/\>\'w/, "[greekomegapsilitonos]")
- remap(/\<\`w/, "[greekomegadasiavaria]")
- remap(/\>\`w/, "[greekomegapsilivaria]")
- remap(/\<\~w/, "[greekomegadasiaperispomeni]")
- remap(/\>\~w/, "[greekomegapsiliperispomeni]")
- remap(/\<w/, "[greekomegadasia]")
- remap(/\>w/, "[greekomegapsili]")
- remap(/\'w/, "[greekomegaoxia]")
- remap(/\`w/, "[greekomegavaria]")
- remap(/\~w/, "[greekomegaperispomeni]")
- remap(/\<r/, "[greekrhodasia]")
- remap(/\>r/, "[greekrhopsili]")
- remap(/\<\~/, "[greekdasiaperispomeni]")
- remap(/\>\~/, "[greekpsiliperispomeni]")
- remap(/\<\'/, "[greekdasiatonos]")
- remap(/\>\'/, "[greekpsilitonos]")
- remap(/\<\`/, "[greekdasiavaria]")
- remap(/\>\`/, "[greekpsilivaria]")
- remap(/\"\'/, "[greekdialytikatonos]")
- remap(/\"\`/, "[greekdialytikavaria]")
- remap(/\"\~/, "[greekdialytikaperispomeni]")
- remap(/\</, "[greekdasia]")
- remap(/\>/, "[greekpsili]")
- remap(/\d.{0,2}''/, "")
- remap(/\'/, "[greekoxia]")
- remap(/\`/, "[greekvaria]")
- remap(/\~/, "[perispomeni]")
- remap(/\"/, "[greekdialytika]")
- # unknown
- # remap(/\|/, "[greekIotadialytika]")
- # next
- remap(/A/, "[greekAlpha]")
- remap(/B/, "[greekBeta]")
- remap(/D/, "[greekDelta]")
- remap(/E/, "[greekEpsilon]")
- remap(/F/, "[greekPhi]")
- remap(/G/, "[greekGamma]")
- remap(/H/, "[greekEta]")
- remap(/I/, "[greekIota]")
- remap(/J/, "[greekTheta]")
- remap(/K/, "[greekKappa]")
- remap(/L/, "[greekLambda]")
- remap(/M/, "[greekMu]")
- remap(/N/, "[greekNu]")
- remap(/O/, "[greekOmicron]")
- remap(/P/, "[greekPi]")
- remap(/Q/, "[greekChi]")
- remap(/R/, "[greekRho]")
- remap(/S/, "[greekSigma]")
- remap(/T/, "[greekTau]")
- remap(/U/, "[greekUpsilon]")
- remap(/W/, "[greekOmega]")
- remap(/X/, "[greekXi]")
- remap(/Y/, "[greekPsi]")
- remap(/Z/, "[greekZeta]")
- remap(/a/, "[greekalpha]")
- remap(/b/, "[greekbeta]")
- remap(/c/, "[greekfinalsigma]")
- remap(/d/, "[greekdelta]")
- remap(/e/, "[greekepsilon]")
- remap(/f/, "[greekphi]")
- remap(/g/, "[greekgamma]")
- remap(/h/, "[greeketa]")
- remap(/i/, "[greekiota]")
- remap(/j/, "[greektheta]")
- remap(/k/, "[greekkappa]")
- remap(/l/, "[greeklambda]")
- remap(/m/, "[greekmu]")
- remap(/n/, "[greeknu]")
- remap(/o/, "[greekomicron]")
- remap(/p/, "[greekpi]")
- remap(/q/, "[greekchi]")
- remap(/r/, "[greekrho]")
- remap(/s/, "[greeksigma]")
- remap(/t/, "[greektau]")
- remap(/u/, "[greekupsilon]")
- remap(/w/, "[greekomega]")
- remap(/x/, "[greekxi]")
- remap(/y/, "[greekpsi]")
- remap(/z/, "[greekzeta]")
- clone("[greekalphatonos]", "[greekalphaoxia]")
- clone("[greekepsilontonos]", "[greekepsilonoxia]")
- clone("[greeketatonos]", "[greeketaoxia]")
- clone("[greekiotatonos]", "[greekiotaoxia]")
- clone("[greekomicrontonos]", "[greekomicronoxia]")
- clone("[greekupsilontonos]", "[greekupsilonoxia]")
- clone("[greekomegatonos]", "[greekomegaoxia]")
- when 'ru' then
- remap(/\xC1/, "[cyrillica]")
- remap(/\xC2/, "[cyrillicb]")
- remap(/\xD7/, "[cyrillicv]")
- remap(/\xC7/, "[cyrillicg]")
- remap(/\xC4/, "[cyrillicd]")
- remap(/\xC5/, "[cyrillice]")
- remap(/\xD6/, "[cyrilliczh]")
- remap(/\xDA/, "[cyrillicz]")
- remap(/\xC9/, "[cyrillici]")
- remap(/\xCA/, "[cyrillicishrt]")
- remap(/\xCB/, "[cyrillick]")
- remap(/\xCC/, "[cyrillicl]")
- remap(/\xCD/, "[cyrillicm]")
- remap(/\xCE/, "[cyrillicn]")
- remap(/\xCF/, "[cyrillico]")
- remap(/\xD0/, "[cyrillicp]")
- remap(/\xD2/, "[cyrillicr]")
- remap(/\xD3/, "[cyrillics]")
- remap(/\xD4/, "[cyrillict]")
- remap(/\xD5/, "[cyrillicu]")
- remap(/\xC6/, "[cyrillicf]")
- remap(/\xC8/, "[cyrillich]")
- remap(/\xC3/, "[cyrillicc]")
- remap(/\xDE/, "[cyrillicch]")
- remap(/\xDB/, "[cyrillicsh]")
- remap(/\xDD/, "[cyrillicshch]")
- remap(/\xDF/, "[cyrillichrdsn]")
- remap(/\xD9/, "[cyrillicery]")
- remap(/\xD8/, "[cyrillicsftsn]")
- remap(/\xDC/, "[cyrillicerev]")
- remap(/\xC0/, "[cyrillicyu]")
- remap(/\xD1/, "[cyrillicya]")
- remap(/\xA3/, "[cyrillicyo]")
- when 'tr' then
- remap(/\^\^11/, "[dotlessi]")
- else
- end
-
- if ! encoding.empty? then
- begin
- filename = Kpse.found(filename, 'context')
- if data = IO.readlines(filename.chomp) then
- report("preloading #{encoding} character mappings")
- accept = false
- data.each do |line|
- case line.chomp
- when /\\start(en|)coding\s*\[(.*?)\]/io then
- enc = $2
- if accept = (enc == encoding) then
- report("accepting vector #{enc}")
- else
- report("skipping vector #{enc}")
- end
- when /\\stop(en|)coding/io then
- accept = false
- when accept && /\\definecharacter\s*([a-zA-Z]+)\s*(\d+)\s*/o then
- name, number = $1, $2
- remap(/\^\^#{sprintf("%02x",number)}/, "[#{name}]")
- if number.to_i > 127 then
- remap(/#{sprintf("\\%03o",number)}/, "[#{name}]")
- end
- end
- end
- end
- rescue
- end
- end
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- public
-
- @@languagedata = Hash.new
-
- def patternfiles
- language = @commandline.argument('first')
- if (language == 'all') || language.empty? then
- languages = @@languagedata.keys.sort
- elsif @@languagedata.key?(language) then
- languages = [language]
- else
- languages = []
- end
- languages.each do |language|
- encoding = @@languagedata[language][0] || ''
- files = @@languagedata[language][1] || []
- Language::generate(self,language,files,encoding)
- end
- end
-
- private
-
- # todo: filter the fallback list from context
-
- # The first entry in the array is the encoding which will be used
- # when interpreting the raw patterns. The second entry is a list of
- # filesets (string|aray), each first match of a set is taken.
-
- @@languagedata['ba' ] = [ 'ec' , ['bahyph.tex'] ]
- @@languagedata['ca' ] = [ 'ec' , ['cahyph.tex'] ]
- @@languagedata['cy' ] = [ 'ec' , ['cyhyph.tex'] ]
- @@languagedata['cs' ] = [ 'ec' , ['czhyphen.tex','czhyphen.ex'] ]
- @@languagedata['de' ] = [ 'ec' , ['dehyphn.tex'] ]
- @@languagedata['deo'] = [ 'ec' , ['dehypht.tex'] ]
- @@languagedata['da' ] = [ 'ec' , ['dkspecial.tex','dkcommon.tex'] ]
- # elhyph.tex
- @@languagedata['es' ] = [ 'ec' , ['eshyph.tex'] ]
- @@languagedata['et' ] = [ 'ec' , ['ethyph.tex'] ]
- @@languagedata['fi' ] = [ 'ec' , ['fihyph.tex'] ]
- @@languagedata['fr' ] = [ 'ec' , ['frhyph.tex'] ]
- # ghyphen.readme ghyph31.readme grphyph
- @@languagedata['hr' ] = [ 'ec' , ['hrhyph.tex'] ]
- @@languagedata['hu' ] = [ 'ec' , ['huhyphn.tex'] ]
- @@languagedata['us' ] = [ 'default' , [['ushyphmax.tex'],['ushyph.tex'],['hyphen.tex']] ]
- @@languagedata['us' ] = [ 'default' , [['ushyphmax.tex'],['ushyph.tex'],['hyphen.tex']] ]
- # inhyph.tex
- @@languagedata['is' ] = [ 'ec' , ['ishyph.tex'] ]
- @@languagedata['it' ] = [ 'ec' , ['ithyph.tex'] ]
- @@languagedata['la' ] = [ 'ec' , ['lahyph.tex'] ]
- # mnhyph
- @@languagedata['nl' ] = [ 'ec' , ['nehyph96.tex'] ]
- # @@languagedata['no' ] = [ 'ec' , ['nohyphbx.tex'],['nohyphb.tex'],['nohyph2.tex'],['nohyph1.tex'],['nohyph.tex'] ]
- @@languagedata['no' ] = [ 'ec' , [['asxsx.tex','nohyphbx.tex'],['nohyphb.tex'],['nohyph2.tex'],['nohyph1.tex'],['nohyph.tex']] ]
- @@languagedata['agr'] = [ 'agr' , [['grahyph4.tex'], ['oldgrhyph.tex']] ] # new, todo
- @@languagedata['pl' ] = [ 'ec' , ['plhyph.tex'] ]
- @@languagedata['pt' ] = [ 'ec' , ['pthyph.tex'] ]
- @@languagedata['ro' ] = [ 'ec' , ['rohyph.tex'] ]
- @@languagedata['sl' ] = [ 'ec' , [['slhyph.tex'], ['sihyph.tex']] ]
- @@languagedata['sk' ] = [ 'ec' , ['skhyphen.tex','skhyphen.ex'] ]
- # sorhyph.tex / upper sorbian
- # srhyphc.tex / cyrillic
- @@languagedata['sv' ] = [ 'ec' , ['svhyph.tex'] ]
- @@languagedata['tr' ] = [ 'ec' , ['tkhyph.tex'] ]
- @@languagedata['gb' ] = [ 'default' , [['ukhyphen.tex'],['ukhyph.tex']] ]
- # @@languagedata['ru' ] = [ 't2a' , ['ruhyphal.tex'] ] # t2a does not work
- @@languagedata['ru' ] = [ 'cyr' , ['ruhyphal.tex'] ]
-end
-
-class Commands
-
- include CommandBase
-
- def dpxmapfiles
-
- force = @commandline.option("force")
-
- texmfroot = @commandline.argument('first')
- texmfroot = '.' if texmfroot.empty?
- if @commandline.option('maproot') != "" then
- maproot = @commandline.option('maproot')
- else
- maproot = "#{texmfroot.gsub(/\\/,'/')}/fonts/map/pdftex/context"
- end
- if File.directory?(maproot) then
- files = Dir.glob("#{maproot}/*.map")
- if files.size > 0 then
- files.each do |pdffile|
- next if File.basename(pdffile) == 'pdftex.map'
- pdffile = File.expand_path(pdffile)
- dpxfile = File.expand_path(pdffile.sub(/(dvips|pdftex)/i,'dvipdfm'))
- unless pdffile == dpxfile then
- begin
- if data = File.read(pdffile) then
- report("< #{File.basename(pdffile)} - pdf(e)tex")
- n = 0
- data = data.collect do |line|
- if line =~ /^[\%\#]+/mo then
- ''
- else
- encoding = if line =~ /([a-z0-9\-]+)\.enc/io then $1 else '' end
- fontfile = if line =~ /([a-z0-9\-]+)\.(pfb|ttf)/io then $1 else nil end
- metrics = if line =~ /^([a-z0-9\-]+)[\s\<]+/io then $1 else nil end
- slant = if line =~ /\"([\d\.]+)\s+SlantFont\"/io then "-s #{$1}" else '' end
- if metrics && encoding && fontfile then
- n += 1
- "#{metrics} #{encoding} #{fontfile} #{slant}"
- else
- ''
- end
- end
- end
- data.delete_if do |line|
- line.gsub(/\s+/,'').empty?
- end
- data.collect! do |line|
- # remove line with "name name" lines
- line.gsub(/^(\S+)\s+\1\s*$/) do
- $1
- end
- end
- begin
- if force then
- if n > 0 then
- File.makedirs(File.dirname(dpxfile))
- if f = File.open(dpxfile,'w') then
- report("> #{File.basename(dpxfile)} - dvipdfm(x) - #{n}")
- f.puts(data)
- f.close
- else
- report("? #{File.basename(dpxfile)} - dvipdfm(x)")
- end
- else
- report("- #{File.basename(dpxfile)} - dvipdfm(x) - no entries")
- # begin File.delete(dpxname) ; rescue ; end
- if f = File.open(dpxfile,'w') then
- f.puts("% no map entries")
- f.close
- end
- end
- else
- report(". #{File.basename(dpxfile)} - dvipdfm(x) - #{n}")
- end
- rescue
- report("error in saving dvipdfm file")
- end
- else
- report("error in loading pdftex file")
- end
- rescue
- report("error in processing pdftex file")
- end
- end
- end
- if force then
- begin
- report("regenerating database for #{texmfroot}")
- system("mktexlsr #{texmfroot}")
- rescue
- end
- end
- else
- report("no mapfiles found in #{maproot}")
- end
- else
- report("provide proper texmfroot")
- end
-
- end
-
-end
-
-class Array
-
- def add_shebang(filename,program)
- unless self[0] =~ /^\#/ then
- self.insert(0,"\#!/usr/bin/env #{program}")
- end
- unless self[2] =~ /^\#.*?copyright\=/ then
- self.insert(1,"\#")
- self.insert(2,"\# copyright=pragma-ade readme=readme.pdf licence=cc-gpl")
- self.insert(3,"") unless self[3].chomp.strip.empty?
- self[2].gsub!(/ +/, ' ')
- return true
- else
- return false
- end
- end
-
- def add_directive(filename,program)
- unless self[0] =~ /^\%/ then
- self.insert(0,"\% content=#{program}")
- end
- unless self[2] =~ /^\%.*?copyright\=/ then
- self.insert(1,"\%")
- if File.expand_path(filename) =~ /[\\\/](doc|manuals)[\\\/]/ then
- self.insert(2,"\% copyright=pragma-ade readme=readme.pdf licence=cc-by-nc-sa")
- else
- self.insert(2,"\% copyright=pragma-ade readme=readme.pdf licence=cc-gpl")
- end
- self.insert(3,"") unless self[3].chomp.strip.empty?
- self[0].gsub!(/ +/, ' ')
- return true
- else
- return false
- end
- end
-
- def add_comment(filename)
- if self[0] =~ /<\?xml.*?\?>/ && self[2] !~ /^<\!\-\-.*?copyright\=.*?\-\->/ then
- self.insert(1,"")
- if File.expand_path(filename) =~ /[\\\/](doc|manuals)[\\\/]/ then
- self.insert(2,"<!-- copyright='pragma-ade' readme='readme.pdf' licence='cc-by-nc-sa' -->")
- else
- self.insert(2,"<!-- copyright='pragma-ade' readme='readme.pdf' licence='cc-gpl' -->")
- end
- self.insert(3,"") unless self[3].chomp.strip.empty?
- return true
- else
- return false
- end
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- def brandfiles
-
- force = @commandline.option("force")
- files = @commandline.arguments # Dir.glob("**/*.*")
- done = false
-
- files.each do |filename|
- if FileTest.file?(filename) then
- ok = false
- begin
- data = IO.readlines(filename)
- case filename
- when /\.rb$/ then
- ok = data.add_shebang(filename,'ruby')
- when /\.pl$/ then
- ok = data.add_shebang(filename,'perl')
- when /\.py$/ then
- ok = data.add_shebang(filename,'python')
- when /\.tex$/ then
- ok = data.add_directive(filename,'tex')
- when /\.mp$/ then
- ok = data.add_directive(filename,'metapost')
- when /\.mf$/ then
- ok = data.add_directive(filename,'metafont')
- when /\.(xml|xsl|fo|fx|rlx|rng|exa)$/ then
- ok = data.add_comment(filename)
- end
- rescue
- report("fatal error in processing #{filename}") # maybe this catches the mac problem taco reported
- else
- if ok then
- report()
- report(filename)
- report()
- for i in 0..4 do
- report(' ' + data[i].chomp)
- end
- if force && f = File.open(filename,'w') then
- f.puts data
- f.close
- end
- done = true
- end
- end
- else
- report("no file named #{filename}")
- end
- end
- report() if done
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- # usage : ctxtools --listentities entities.xml
- # document: <!DOCTYPE something SYSTEM "entities.xml">
-
- def flushentities(handle,entities,doctype=nil) # 'stylesheet'
- if doctype then
- tab = "\t"
- handle << "<?xml version='1.0' encoding='utf-8'?>\n\n"
- handle << "<!-- !DOCTYPE entities SYSTEM 'entities.xml' -->\n\n"
- handle << "<!DOCTYPE #{doctype} [\n"
- else
- tab = ""
- end
- entities.keys.sort.each do |k|
- handle << "#{tab}<!ENTITY #{k} \"\&\#x#{entities[k]};\">\n"
- end
- if doctype then
- handle << "]>\n"
- end
- end
-
- def listentities
-
- filenames = ['enco-uc.tex','contextnames.txt']
- outputname = @commandline.argument('first')
- doctype = @commandline.option('doctype')
- entities = Hash.new
-
- filenames.each do |filename|
- filename = Kpse.found(filename, 'context')
- if filename and not filename.empty? and FileTest.file?(filename) then
- report("loading #{filename.gsub(/\\/,'/')}") unless outputname.empty?
- IO.readlines(filename).each do |line|
- case line
- when /^[\#\%]/io then
- # skip comment line
- when /\\definecharacter\s+([a-z]+)\s+\{\\uchar\{*(\d+)\}*\{(\d+)\}\}/io then
- name, code = $1, sprintf("%04X",$2.to_i*256 + $3.to_i)
- entities[name] = code.rjust(4,'0') unless entities.key?(name)
- when /^([A-F0-9]+)\;([a-z][a-z]+)\;(.*?)\;(.*?)\s*$/io then
- code, name, adobe, comment = $1, $2, $3, $4
- entities[name] = code.rjust(4,'0') unless entities.key?(name)
- end
- end
- end
- end
- if outputname and not outputname.empty? then
- if f = File.open(outputname,'w') then
- report("saving #{entities.size} entities in #{outputname}")
- flushentities(f,entities,doctype)
- f.close
- else
- flushentities($stdout,entities,doctype)
- end
- else
- flushentities($stdout,entities,doctype)
- end
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- def platformize
-
- pattern = if @commandline.arguments.empty? then "*.{rb,pl,py}" else @commandline.arguments end
- recurse = @commandline.option("recurse")
- force = @commandline.option("force")
- pattern = "#{if recurse then '**/' else '' end}#{pattern}"
- Dir.glob(pattern).each do |file|
- if File.file?(file) then
- size = File.size(file)
- data = IO.readlines(file)
- if force then
- if f = File.open(file,'w')
- data.each do |line|
- f.puts(line.chomp)
- end
- f.close
- end
- if File.size(file) == size then # not robust
- report("file '#{file}' is unchanged")
- else
- report("file '#{file}' is platformized")
- end
- else
- report("file '#{file}' is a candidate")
- end
- end
- end
- end
-
-end
-
-class TexDeps
-
- @@cs_tex = %q/
- above abovedisplayshortskip abovedisplayskip
- abovewithdelims accent adjdemerits advance afterassignment
- aftergroup atop atopwithdelims
- badness baselineskip batchmode begingroup
- belowdisplayshortskip belowdisplayskip binoppenalty botmark
- box boxmaxdepth brokenpenalty
- catcode char chardef cleaders closein closeout clubpenalty
- copy count countdef cr crcr csname
- day deadcycles def defaulthyphenchar defaultskewchar
- delcode delimiter delimiterfactor delimeters
- delimitershortfall delimeters dimen dimendef discretionary
- displayindent displaylimits displaystyle
- displaywidowpenalty displaywidth divide
- doublehyphendemerits dp dump
- edef else emergencystretch end endcsname endgroup endinput
- endlinechar eqno errhelp errmessage errorcontextlines
- errorstopmode escapechar everycr everydisplay everyhbox
- everyjob everymath everypar everyvbox exhyphenpenalty
- expandafter
- fam fi finalhyphendemerits firstmark floatingpenalty font
- fontdimen fontname futurelet
- gdef global group globaldefs
- halign hangafter hangindent hbadness hbox hfil horizontal
- hfill horizontal hfilneg hfuzz hoffset holdinginserts hrule
- hsize hskip hss horizontal ht hyphenation hyphenchar
- hyphenpenalty hyphen
- if ifcase ifcat ifdim ifeof iffalse ifhbox ifhmode ifinner
- ifmmode ifnum ifodd iftrue ifvbox ifvmode ifvoid ifx
- ignorespaces immediate indent input inputlineno input
- insert insertpenalties interlinepenalty
- jobname
- kern
- language lastbox lastkern lastpenalty lastskip lccode
- leaders left lefthyphenmin leftskip leqno let limits
- linepenalty line lineskip lineskiplimit long looseness
- lower lowercase
- mag mark mathaccent mathbin mathchar mathchardef mathchoice
- mathclose mathcode mathinner mathop mathopen mathord
- mathpunct mathrel mathsurround maxdeadcycles maxdepth
- meaning medmuskip message mkern month moveleft moveright
- mskip multiply muskip muskipdef
- newlinechar noalign noboundary noexpand noindent nolimits
- nonscript scriptscript nonstopmode nulldelimiterspace
- nullfont number
- omit openin openout or outer output outputpenalty over
- overfullrule overline overwithdelims
- pagedepth pagefilllstretch pagefillstretch pagefilstretch
- pagegoal pageshrink pagestretch pagetotal par parfillskip
- parindent parshape parskip patterns pausing penalty
- postdisplaypenalty predisplaypenalty predisplaysize
- pretolerance prevdepth prevgraf
- radical raise read relax relpenalty right righthyphenmin
- rightskip romannumeral
- scriptfont scriptscriptfont scriptscriptstyle scriptspace
- scriptstyle scrollmode setbox setlanguage sfcode shipout
- show showbox showboxbreadth showboxdepth showlists showthe
- skewchar skip skipdef spacefactor spaceskip span special
- splitbotmark splitfirstmark splitmaxdepth splittopskip
- string
- tabskip textfont textstyle the thickmuskip thinmuskip time
- toks toksdef tolerance topmark topskip tracingcommands
- tracinglostchars tracingmacros tracingonline tracingoutput
- tracingpages tracingparagraphs tracingrestores tracingstats
- uccode uchyph underline unhbox unhcopy unkern unpenalty
- unskip unvbox unvcopy uppercase
- vadjust valign vbadness vbox vcenter vfil vfill vfilneg
- vfuzz voffset vrule vsize vskip vsplit vss vtop
- wd widowpenalty write
- xdef xleaders xspaceskip
- year
- /.split
-
- @@cs_etex = %q/
- beginL beginR botmarks
- clubpenalties currentgrouplevel currentgrouptype
- currentifbranch currentiflevel currentiftype
- detokenize dimexpr displaywidowpenalties
- endL endR eTeXrevision eTeXversion everyeof
- firstmarks fontchardp fontcharht fontcharic fontcharwd
- glueexpr glueshrink glueshrinkorder gluestretch
- gluestretchorder gluetomu
- ifcsname ifdefined iffontchar interactionmode
- interactionmode interlinepenalties
- lastlinefit lastnodetype
- marks topmarks middle muexpr mutoglue
- numexpr
- pagediscards parshapedimen parshapeindent parshapelength
- predisplaydirection
- savinghyphcodes savingvdiscards scantokens showgroups
- showifs showtokens splitdiscards splitfirstmarks
- TeXXeTstate tracingassigns tracinggroups tracingifs
- tracingnesting tracingscantokens
- unexpanded unless
- widowpenalties
- /.split
-
- @@cs_pdftex = %q/
- pdfadjustspacing pdfannot pdfavoidoverfull
- pdfcatalog pdfcompresslevel
- pdfdecimaldigits pdfdest pdfdestmargin
- pdfendlink pdfendthread
- pdffontattr pdffontexpand pdffontname pdffontobjnum pdffontsize
- pdfhorigin
- pdfimageresolution pdfincludechars pdfinfo
- pdflastannot pdflastdemerits pdflastobj
- pdflastvbreakpenalty pdflastxform pdflastximage
- pdflastximagepages pdflastxpos pdflastypos
- pdflinesnapx pdflinesnapy pdflinkmargin pdfliteral
- pdfmapfile pdfmaxpenalty pdfminpenalty pdfmovechars
- pdfnames
- pdfobj pdfoptionpdfminorversion pdfoutline pdfoutput
- pdfpageattr pdfpageheight pdfpageresources pdfpagesattr
- pdfpagewidth pdfpkresolution pdfprotrudechars
- pdfrefobj pdfrefxform pdfrefximage
- pdfsavepos pdfsnaprefpoint pdfsnapx pdfsnapy pdfstartlink
- pdfstartthread
- pdftexrevision pdftexversion pdfthread pdfthreadmargin
- pdfuniqueresname
- pdfvorigin
- pdfxform pdfximage
- /.split
-
- @@cs_omega = %q/
- odelimiter omathaccent omathchar oradical omathchardef omathcode odelcode
- leftghost rightghost
- charwd charht chardp charit
- localleftbox localrightbox
- localinterlinepenalty localbrokenpenalty
- pagedir bodydir pardir textdir mathdir
- boxdir nextfakemath
- pagewidth pageheight pagerightoffset pagebottomoffset
- nullocp nullocplist ocp externalocp ocplist pushocplist popocplist clearocplists ocptracelevel
- addbeforeocplist addafterocplist removebeforeocplist removeafterocplist
- OmegaVersion
- InputTranslation OutputTranslation DefaultInputTranslation DefaultOutputTranslation
- noInputTranslation noOutputTranslation
- InputMode OutputMode DefaultInputMode DefaultOutputMode
- noInputMode noOutputMode noDefaultInputMode noDefaultOutputMode
- /.split
-
- @@cs_metatex = %q/
- /.split
-
- @@cs_xetex = %q/
- /.split
-
- @@cs_skip = %q/
- v\! c\! s\! e\! m\! f\!
- \!tf \!tt \!tq \!ta \?\?
- csname endcsname relax
- \!\!string[a-f] \!\!dimen[a-k] \!\!count[a-f] \!\!toks[a-e] \!\!box[a-e]
- \!\!width[a-c] \!\!height[a-c] \!\!depth[a-c]
- \!\!done[a-f] if\!\!done[a-f] if\:\!\!done[a-f]
- scratch globalscratch
- ascii[a-d] globalascii
- @@expanded @@globalexpanded @EA @EAEA @EAEAEA
- bgroup egroup par next nextnext docommand dodocommand dododocommand
- \!\!width \!\!height \!\!depth \!\!plus \!\!minus \!\!to
- /.split
-
- @@cs_skip = %q/
- [vcsemf]\! \?\?
- \!t[ftqa]
- csname endcsname relax
- \!\!string[a-f] \!\!dimen[a-k] \!\!count[a-f] \!\!toks[a-e] \!\!box[a-e]
- \!\!width[a-c] \!\!height[a-c] \!\!depth[a-c]
- \!\!done[a-f] if\!\!done[a-f] if\:\!\!done[a-f]
- scratch globalscratch
- ascii[a-d] globalascii
- @@expanded @@globalexpanded @(EA)+
- [be]group par next nextnext (do)+command
- \!\!(width|height|depth|plus|minus|to)
- /.split
-
- # let's ignore \dimendef etc
-
- @@primitives_def = %q/
- def edef xdef gdef let
- newcount newdimen newskip newbox newtoks newmarks newif newinsert newmuskip
- chardef mathchardef dimendef countdef toksdef
- newconditional definecomplexorsimple definecomplexorsimpleempty
- newcounter newpersistentmark
- installinsertion installspecial\s*\\[* installoutput\s*\\[*
- /.split
-
- @@types = [['invalid','*'],['okay','='],['forward','>'],['backward','<'],['unknown','?']]
-
- @@skips = /^(#{@@cs_skip.join('|')})/o
-
- def initialize(logger=nil,compact=false)
- @defined = Hash.new
- @definitive = Hash.new
- @used_before = Hash.new
- @used_after = Hash.new
- @dependencies = Hash.new
- @fineorder = Hash.new
- @forward = Hash.new
- @backward = Hash.new
- @disorder = Hash.new
- @disordercs = Hash.new
- @type = Hash.new
- @filename = 'context.tex'
- @files = Array.new # keep load order !
- @order = Hash.new
- @logger = logger
- @filefilter = nil
- @namefilter = nil
- @compact = compact
- #
- @@cs_tex.each do |cs| @defined[cs] = ['-tex--------'] end
- @@cs_etex.each do |cs| @defined[cs] = ['-etex-------'] end
- @@cs_pdftex.each do |cs| @defined[cs] = ['-pdftex-----'] end
- @@cs_omega.each do |cs| @defined[cs] = ['-omega------'] end
- @@cs_xetex.each do |cs| @defined[cs] = ['-xetex------'] end
- @@cs_metatex.each do |cs| @defined[cs] = ['-metatex----'] end
- end
-
- def report(str)
- @logger.report(str) rescue false
- end
-
- def setfilter(data)
- data.split(/\s*\,\s*/).each do |d|
- if d =~ /\.tex$/ then
- @filefilter = Array.new unless @filefilter
- @filefilter << d
- else
- @namefilter = Array.new unless @namefilter
- @namefilter << d
- end
- end
- end
-
- def load(filename='context.tex')
- begin
- @filename = filename
- n = 0
- File.open(filename) do |f|
- f.each do |line|
- if line =~ /^(\\input\s+|\\load[a-z]+\{)([a-z\-\.]+)(\}*)/ then
- ante, name, post = $1, $2, $3
- @files.push(name)
- @order[name] = n += 1
- end
- end
- end
- rescue
- @files = Array.new
- @order = Hash.new
- end
- end
-
- def save(filename='context.tex')
- unless @filefilter || @namefilter then
- begin
- data = IO.readlines(filename).each do |line|
- line.gsub!(/^(\\input\s+|\\load[a-z]+\{)([a-z\-\.]+)(\}*)\s*$/) do
- ante, name, post = $1, $2, $3
- fin = (@fineorder[name] || [])-[name]
- dep = (@dependencies[name] || [])-[name]
- dis = (@disorder[name] || [])-[name]
- fin = if fin.size > 0 then " B[#{fin.join(' ')}]" else "" end
- dep = if dep.size > 0 then " A[#{dep.join(' ')}]" else "" end
- dis = if dis.size > 0 then " D[#{dis.join(' ')}]" else "" end
- "#{ante}#{name}#{post} %#{fin}#{dep}#{dis}\n"
- end
- end
- rescue
- report("error: #{$!}")
- else
- begin
- newname = filename.sub(/\..*$/,'.log')
- report("")
- report("writing to #{newname}")
- report("")
- File.open(newname,'w') do |f|
- f << data
- end
- rescue
- report("error: #{$!}")
- end
- end
- end
- end
-
- def analyze
- report('')
- report("loading files")
- report('')
- n = 0
-# try tex and mkiv
- @files.each do |filename|
- if File.file?(filename) and f = File.open(filename) then
- defs, uses, l = 0, 0, 0
- n += 1
- report("#{n.to_s.rjust(5,' ')} #{filename}")
- f.each do |line|
- l += 1
- line.chomp!
-
-
- line.sub!(/\%.*$/, '')
- line.gsub!(/\\(unexpanded|unprotected|global|protected|long)\s*(\\)/, "\\")
- # the superseded, overloaded, forwarded, and predefined macros
- # are at the outer level anyway, so there we may ignore leading
- # spaces (could be inside an \if); other definitions are only
- # accepted when they start at the beginning of a line
- case line
- when /^\\ifx\s*\\[a-zA-Z\@\!\?]+\s*\\undefined\s*(\\else)*(.*?)$/ then
- if $2 =~ /^\s*\\(#{@@primitives_def.join('|')})\s*\\([a-zA-Z\@\?\!]{3,})/o then
- pushdef(filename,l,$2,5) # kind of auto-predefined
- end
- when /^\s*\\superseded\s*\\(#{@@primitives_def.join('|')})\s*\\([a-zA-Z\@\?\!]{3,})(.*)$/o
- name, rest = $2, $3
- pushdef(filename,l,name,1)
- moreuse(filename,l,rest)
- when /^\s*\\overloaded\s*\\(#{@@primitives_def.join('|')})\s*\\([a-zA-Z\@\?\!]{3,})(.*)$/o
- name, rest = $2, $3
- pushdef(filename,l,name,2)
- moreuse(filename,l,rest)
- when /^\s*\\forwarded\s*\\(#{@@primitives_def.join('|')})\s*\\([a-zA-Z\@\?\!]{3,})(.*)$/o
- name, rest = $2, $3
- pushdef(filename,l,name,3)
- moreuse(filename,l,rest)
- when /^\s*\\predefined\s*\\(#{@@primitives_def.join('|')})\s*\\([a-zA-Z\@\?\!]{3,})(.*)$/o
- name, rest = $2, $3
- pushdef(filename,l,name,4)
- moreuse(filename,l,rest)
- when /^\\(#{@@primitives_def.join('|')})[\=\s]*\\([a-zA-Z\@\?\!]{3,})(.*)$/o
- name, rest = $2, $3 # \=* catches the \let \a = \b
- pushdef(filename,l,name,0)
- moreuse(filename,l,rest)
- when /\\newevery\s*\\([a-zA-Z\@\?\!]+)\s*\\([a-zA-Z\@\?\!]+)/ then
- a, b = $1, $2
- pushdef(filename,l,a,0)
- pushdef(filename,l,b,0)
- else
- moreuse(filename,l,line)
- end
- end
- f.close
- end
- end
- @used_after.each do |cs,files|
- (@defined[cs] || []).each do |name|
- @dependencies[name] = Array.new unless @dependencies[name]
- files.each do |file|
- @dependencies[name] << file unless @dependencies[name].include?(file)
- end
- end
- end
- @used_before.each do |cs,files|
- (@defined[cs] || []).each do |name|
- @disorder[name] = Array.new unless @disorder[name]
- @disordercs[name] = Array.new unless @disordercs[name]
- @fineorder[name] = Array.new unless @fineorder[name]
- files.each do |file|
- unless @disorder[name].include?(file) || name == file then
- unless @defined[cs].include?(file) then
- if @order[name] > @order[file] then
- @disorder[name] << file
- @disordercs[name] << "#{file}:#{cs}"
- end
- end
- end
- @fineorder[name] << file unless @fineorder[name].include?(file) || name == file
- end
- end
- end
- end
-
- def moreuse(filename,l,line)
- line.scan(/\\if([a-zA-Z@\?\!]{3,})/) do |name, rest| # rest, else array
- pushuse(filename,l,"if#{name}") unless name =~ /^(true|false)$/
- end
- line.scan(/\\([a-zA-Z@\?\!]{3,})/) do |name, rest| # rest, else array
- if name =~ /(true|false)$/ then
- pushuse(filename,l,"if#{name}") unless name =~ /^(if|set)$/
- else
- pushuse(filename,l,name)
- end
- end
- end
-
- def feedback
- begin
- # get max length
- l = 0
- list = @defined.keys.sort
- list.each do |cs|
- l = cs.length if cs.length > l
- end
- if ! @compact then
- n = 0
- report('')
- report("defined: #{@defined.size}")
- report('')
- @defined.keys.sort.each do |cs|
- next if @namefilter && ! @namefilter.include?(cs)
- next if @filefilter && ! @defined[cs].include?(cs)
- if @defined[cs].size > 1 then
- dlist = @defined[cs].collect do |d|
- if d == @definitive[cs] then d else "[#{d}]" end
- end
- else
- dlist = @defined[cs]
- end
- report("#{(n += 1).to_s.rjust(5,' ')} #{cs.ljust(l,' ')} == #{dlist.join(' ')}")
- end
- end
- if true then
- n = 0
- report('')
- report("used before defined: #{@used_before.size}")
- report('')
- @used_before.keys.sort.each do |cs|
- next if @namefilter && ! @namefilter.include?(cs)
- next if @filefilter && (@used_before[cs] & @filefilter).size == 0
- used = @used_before[cs] - (@defined[cs] || [])
- defined = (@defined[cs] || []).join(' ')
- defined = "[ ? ]" if defined.empty?
- if used.size > 0 then
- report("#{(n += 1).to_s.rjust(5,' ')} #{cs.ljust(l,' ')} == #{defined} -> #{used.join(' ')}")
- else
- report("#{(n += 1).to_s.rjust(5,' ')} #{cs.ljust(l,' ')} == #{defined}")
- end
- end
- report(' none') if n == 0
- end
- if ! @compact then
- n = 0
- report('')
- report("used after defined: #{@used_after.size}")
- report('')
- @used_after.keys.sort.each do |cs|
- next if @namefilter && ! @namefilter.include?(cs)
- next if @filefilter && (@used_after[cs] & @filefilter).size == 0
- used = @used_after[cs] - (@defined[cs] || [])
- defined = (@defined[cs] || []).join(' ')
- if used.size > 0 then
- report("#{(n += 1).to_s.rjust(5,' ')} #{cs.ljust(l,' ')} == #{defined} <- #{used.join(' ')}")
- else
- report("#{(n += 1).to_s.rjust(5,' ')} #{cs.ljust(l,' ')} == #{defined}")
- end
- end
- report(' none') if n == 0
- end
- if ! @compact then
- unless @filefilter || @namefilter then
- [false,true].each do |mode|
- n = 0
- report("")
- report("file dependecies #{if mode then '(critical)' end}")
- [@dependencies].each do |dependencies|
- report("")
- dependencies.keys.sort.each do |f|
- if dependencies[f].size > 0 then
- dependencies[f].delete(f)
- end
- if mode then
- dep = dependencies[f].delete_if do |d|
- f[0..3] == d[0..3] # same xxxx- prefix
- end
- else
- dep = dependencies[f]
- end
- if dep.size > 0 then
- name = f.nosuffix('tex').ljust(8,' ')
- list = dep.sort.collect do |k| k.nosuffix('tex') end
- report("#{(n += 1).to_s.rjust(5,' ')} #{name} !! #{list.join(' ')}")
- end
- end
- end
- report(' none') if n == 0
- end
- end
- end
- if true then
- unless @filefilter || @namefilter then
- [false,true].each do |mode|
- [@disorder,@disordercs].each do |disorder|
- n = 0
- report("")
- report("file disorder #{if mode then '(critical)' end}")
- report("")
- disorder.keys.sort.each do |f|
- if disorder[f].size > 0 then
- disorder[f].delete(f)
- end
- if mode then
- dis = disorder[f].delete_if do |d|
- f[0..3] == d[0..3] # same xxxx- prefix
- end
- else
- dis = disorder[f]
- end
- if dis.size > 0 then
- name = f.nosuffix('tex').ljust(8,' ')
- list = dis.sort.collect do |k| k.nosuffix('tex') end
- report("#{(n += 1).to_s.rjust(3,' ')} #{name} ?? #{list.join(' ')}")
- end
- end
- end
- report(' none') if n == 0
- end
- end
- end
- rescue
- puts("fatal error: #{$!} #{$@.join("\n")}")
- end
- end
-
- private
-
- def csdefined?(cs,filename)
- @defined[cs] && @defined[cs].include?(filename)
- end
- def csbefore?(cs,filename)
- @used_before[cs] && @used_before[cs].include?(filename)
- end
- def csafter?(cs,filename)
- @used_after[cs] && @used_after[cs].include?(filename)
- end
-
- def csignored?(cs)
- cs.to_s =~ @@skips
- end
-
- def pushdef(filename,n,cs,type)
- if csignored?(cs) then
- # nothing
- elsif @defined[cs] then
- case type
- when 5 then
- # if test, no definition done
- else
- @definitive[cs] = filename
- unless @filefilter || @namefilter then
- report("#{cs} is redefined") unless csdefined?(cs,filename) || @compact
- end
- end
- @defined[cs] << filename unless @defined[cs].include?(filename)
- else
- @defined[cs] = Array.new
- @defined[cs] << filename
- @definitive[cs] = filename
- @type[cs] = type
- end
- end
-
- def pushuse(filename,n,cs)
- if csignored?(cs) then
- # nothing
- elsif @defined[cs] then
- @used_after[cs] = Array.new unless @used_after[cs]
- @used_after[cs] << filename unless csafter?(cs,filename)
- else
- @used_before[cs] = Array.new unless @used_before[cs]
- @used_before[cs] << filename unless csbefore?(cs,filename)
- end
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- def dependencies
-
- filename = if @commandline.arguments.empty? then 'context.tex' else @commandline.arguments.first end
- compact = @commandline.option('compact')
-
- ['context',''].each do |progname|
- unless FileTest.file?(filename) then
- name = Kpse.found(filename, progname)
- if FileTest.file?(name) then
- filename = name
- break
- end
- end
- end
-
- if FileTest.file?(filename) && deps = TexDeps.new(logger,compact) then
- deps.setfilter(@commandline.option('filter'))
- deps.load
- deps.analyze
- deps.feedback
- deps.save if @commandline.option('save')
- else
- report("unknown file #{filename}")
- end
-
- end
-
-end
-
-class Commands
-
- @@re_utf_bom = /^\357\273\277/o # just utf-8
-
- def disarmutfbom
-
- if @commandline.arguments.empty? then
- report("provide filename")
- else
- @commandline.arguments.each do |filename|
- report("checking '#{filename}'")
- if FileTest.file?(filename) then
- begin
- data = IO.read(filename)
- if data.sub!(@@re_utf_bom,'') then
- if @commandline.option('force') then
- if f = File.open(filename,'wb') then
- f << data
- f.close
- report("bom found and removed")
- else
- report("bom found and removed, but saving file fails")
- end
- else
- report("bom found, use '--force' to remove it")
- end
- else
- report("no bom found")
- end
- rescue
- report("bom found, but removing it fails")
- end
- else
- report("provide valid filename")
- end
- end
- end
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- def updatecontext
-
- def fetchfile(site, name, target=nil)
- begin
- proxy = @commandline.option('proxy')
- if proxy && ! proxy.empty? then
- address, port = proxy.split(":")
- if address && port then
- http = Net::HTTP::Proxy(address, port).new(site)
- else
- http = Net::HTTP::Proxy(proxy, 80).new(site)
- end
- else
- http = Net::HTTP.new(site)
- end
- resp, data = http.get(name.gsub(/^\/*/, '/'))
- rescue
- return false
- else
- begin
- if data then
- name = File.basename(name)
- File.open(target || name, 'wb') do |f|
- f << data
- end
- else
- return false
- end
- rescue
- return false
- else
- return true
- end
- end
- end
-
- def locatedlocaltree
- tree = Kpse.used_path('TEXMFLOCAL')
- unless tree && FileTest.directory?(tree) then
- tree = Kpse.used_path('TEXMF')
- end
- return tree
- end
-
- def extractarchive(archive)
- unless FileTest.file?(archive) then
- report("fatal error, '#{archive}' has not been downloaded")
- return false
- end
- # unless system("unzip -uo #{archive}") then
- unless system("unzip -o #{archive}") then
- report("fatal error, make sure that you have 'unzip' in your path")
- return false
- end
- stubs = "scripts/context/stubs/unix/*"
- if System.unix? and not system("chmod +x #{stubs}") then
- report("change x-permissions of '#{stubs}' manually")
- end
- return true
- end
-
- def remakeformats
- system("mktexlsr")
- system("texmfstart texexec --make --all --fast --pdftex")
- system("texmfstart texexec --make --all --fast --xetex")
- return true
- end
-
- if localtree = locatedlocaltree then
- report("updating #{localtree}")
- begin
- Dir.chdir(localtree)
- rescue
- report("unable to change to #{localtree}")
- else
- archive = 'cont-tmf.zip'
- report("fetching #{archive}")
- unless fetchfile("www.pragma-ade.com","/context/latest/#{archive}") then
- report("unable to fetch #{archive}")
- return
- end
- report("extracting #{archive}")
- unless extractarchive(archive) then
- report("unable to extract #{archive}")
- return
- end
- report("remaking formats")
- unless remakeformats then
- report("unable to remak formats")
- end
- end
- else
- report("unable to locate local tree")
- end
-
- end
-
-end
-
-logger = Logger.new(banner.shift)
-commandline = CommandLine.new
-
-commandline.registeraction('touchcontextfile' , 'update context version')
-commandline.registeraction('contextversion' , 'report context version')
-commandline.registeraction('jeditinterface' , 'generate jedit syntax files [--pipe]')
-commandline.registeraction('bbeditinterface' , 'generate bbedit syntax files [--pipe]')
-commandline.registeraction('sciteinterface' , 'generate scite syntax files [--pipe]')
-commandline.registeraction('rawinterface' , 'generate raw syntax files [--pipe]')
-# commandline.registeraction('translateinterface', 'generate interface files (xml) [nl de ..]')
-commandline.registeraction('purgefiles' , 'remove temporary files [--all --recurse] [basename]')
-commandline.registeraction('documentation' , 'generate documentation [--type=] [filename]')
-commandline.registeraction('filterpages' ) # no help, hidden temporary feature
-commandline.registeraction('patternfiles' , 'generate pattern files [--all --xml --utf8] [languagecode]')
-commandline.registeraction('dpxmapfiles' , 'convert pdftex mapfiles to dvipdfmx [--force] [texmfroot]')
-commandline.registeraction('listentities' , 'create doctype entity definition from enco-uc.tex')
-commandline.registeraction('brandfiles' , 'add context copyright notice [--force]')
-commandline.registeraction('platformize' , 'replace line-endings [--recurse --force] [pattern]')
-commandline.registeraction('dependencies' , 'analyze depedencies within context [--save --compact --filter=[macros|filenames]] [filename]')
-commandline.registeraction('updatecontext' , 'download latest version and remake formats [--proxy]')
-commandline.registeraction('disarmutfbom' , 'remove utf bom [--force]')
-
-commandline.registervalue('type','')
-commandline.registervalue('filter','')
-commandline.registervalue('maproot','')
-commandline.registervalue('proxy','')
-
-commandline.registerflag('recurse')
-commandline.registerflag('force')
-commandline.registerflag('compact')
-commandline.registerflag('pipe')
-commandline.registerflag('save')
-commandline.registerflag('all')
-commandline.registerflag('xml')
-commandline.registerflag('log')
-commandline.registerflag('utf8')
-commandline.registerflag('doctype')
-
-# general
-
-commandline.registeraction('help')
-commandline.registeraction('version')
-
-commandline.expand
-
-Commands.new(commandline,logger,banner).send(commandline.action || 'help')
diff --git a/Master/texmf-dist/scripts/context/ruby/graphics/gs.rb b/Master/texmf-dist/scripts/context/ruby/graphics/gs.rb
deleted file mode 100644
index 6143c881232..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/graphics/gs.rb
+++ /dev/null
@@ -1,684 +0,0 @@
-# module : graphics/gs
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# ['base/variables','../variables','variables'].each do |r| begin require r ; rescue Exception ; else break ; end ; end
-# ['base/system', '../system', 'system' ].each do |r| begin require r ; rescue Exception ; else break ; end ; end
-
-require 'base/variables'
-require 'base/system'
-require 'fileutils'
-# Require 'ftools'
-
-class GhostScript
-
- include Variables
-
- @@pdftrimwhite = 'pdftrimwhite.pl'
-
- @@pstopdfoptions = [
- 'AntiAliasColorImages',
- 'AntiAliasGrayImages',
- 'AntiAliasMonoImages',
- 'ASCII85EncodePages',
- 'AutoFilterColorImages',
- 'AutoFilterGrayImages',
- 'AutoPositionEPSFiles',
- 'AutoRotatePages',
- 'Binding',
- 'ColorConversionStrategy',
- 'ColorImageDepth',
- 'ColorImageDownsampleThreshold',
- 'ColorImageDownsampleType',
- 'ColorImageFilter',
- 'ColorImageResolution',
- 'CompatibilityLevel',
- 'CompressPages',
- #'ConvertCMYKImagesToRGB', # buggy
- #'ConvertImagesToIndexed', # buggy
- 'CreateJobTicket',
- 'DetectBlends',
- 'DoThumbnails',
- 'DownsampleColorImages',
- 'DownsampleGrayImages',
- 'DownsampleMonoImages',
- 'EmbedAllFonts',
- 'EncodeColorImages',
- 'EncodeGrayImages',
- 'EncodeMonoImages',
- 'EndPage',
- 'FirstPage',
- 'GrayImageDepth',
- 'GrayImageDownsampleThreshold',
- 'GrayImageDownsampleType',
- 'GrayImageFilter',
- 'GrayImageResolution',
- 'MaxSubsetPct',
- 'MonoImageDepth',
- 'MonoImageDownsampleThreshold',
- 'MonoImageDownsampleType',
- 'MonoImageFilter',
- 'MonoImageResolution',
- 'Optimize',
- 'ParseDCSComments',
- 'ParseDCSCommentsForDocInfo',
- 'PreserveCopyPage',
- 'PreserveEPSInfo',
- 'PreserveHalftoneInfo',
- 'PreserveOPIComments',
- 'PreserveOverprintSettings',
- 'SubsetFonts',
- 'UseFlateCompression'
- ]
-
- @@methods = Hash.new
-
- @@methods['raw'] = '1'
- @@methods['bound'] = '2'
- @@methods['bounded'] = '2'
- @@methods['crop'] = '3'
- @@methods['cropped'] = '3'
- @@methods['down'] = '4'
- @@methods['downsample'] = '4'
- @@methods['downsampled'] = '4'
- @@methods['simplify'] = '5'
- @@methods['simplified'] = '5'
-
- @@tempfile = 'gstemp'
- @@pstempfile = @@tempfile + '.ps'
- @@pdftempfile = @@tempfile + '.pdf'
-
- @@bboxspec = '\s*([\-\d\.]+)' + '\s+([\-\d\.]+)'*3
-
- def initialize(logger=nil)
-
- unless logger then
- puts('gs class needs a logger')
- exit
- end
-
- @variables = Hash.new
- @psoptions = Hash.new
- @logger = logger
-
- setvariable('profile', 'gsprofile.ini')
- setvariable('pipe', true)
- setvariable('method', 2)
- setvariable('force', false)
- setvariable('colormodel', 'cmyk')
- setvariable('inputfile', '')
- setvariable('outputfile', '')
-
- @@pstopdfoptions.each do |key|
- @psoptions[key] = ''
- end
-
- reset
-
- end
-
- def reset
- @llx = @lly = @ulx = @uly = 0
- @oldbbox = [@llx,@lly,@urx,@ury]
- @width = @height = @xoffset = @yoffset = @offset = 0
- @rs = Tool.default_line_separator
- end
-
- def supported?(filename)
- psfile?(filename) || pdffile?(filename)
- end
-
- def psfile?(filename)
- filename =~ /\.(eps|epsf|ps|ai\d*)$/io
- end
-
- def pdffile?(filename)
- filename =~ /\.(pdf)$/io
- end
-
- def setpsoption(key,value)
- @psoptions[key] = value unless value.empty?
- end
-
- def setdimensions (llx,lly,urx,ury)
- @oldbbox = [llx,lly,urx,ury]
- @llx, @lly = llx.to_f-@offset, lly.to_f-@offset
- @urx, @ury = urx.to_f+@offset, ury.to_f+@offset
- @width, @height = @urx - @llx, @ury - @lly
- @xoffset, @yoffset = 0 - @llx, 0 - @lly
- end
-
- def setoffset (offset=0)
- @offset = offset.to_f
- setdimensions(@llx,@lly,@urx,@ury) if dimensions?
- end
-
- def resetdimensions
- setdimensions(0,0,0,0)
- end
-
- def dimensions?
- (@width>0) && (@height>0)
- end
-
- def convert
-
- inpfile = getvariable('inputfile')
-
- if inpfile.empty? then
- report('no inputfile specified')
- return false
- end
-
- unless FileTest.file?(inpfile) then
- report("unknown input file #{inpfile}")
- return false
- end
-
- outfile = getvariable('outputfile')
-
- if outfile.empty? then
- outfile = inpfile
- outfile = outfile.sub(/^.*[\\\/]/,'')
- end
-
- outfile = outfile.sub(/\.(pdf|eps|ps|ai)/i, "")
- resultfile = outfile + '.pdf'
- setvariable('outputfile', resultfile)
-
- # flags
-
- saveprofile(getvariable('profile'))
-
- begin
- gsmethod = method(getvariable('method')).to_i
- report("conversion method #{gsmethod}")
- rescue
- gsmethod = 1
- report("fallback conversion method #{gsmethod}")
- end
-
- debug('piping data') if getvariable('pipe')
-
- ok = false
- begin
- case gsmethod
- when 0, 1 then ok = convertasis(inpfile,resultfile)
- when 2 then ok = convertbounded(inpfile,resultfile)
- when 3 then ok = convertcropped(inpfile,resultfile)
- when 4 then ok = downsample(inpfile,resultfile,'screen')
- when 5 then ok = downsample(inpfile,resultfile,'prepress')
- else report("invalid conversion method #{gsmethod}")
- end
- rescue
- report("job aborted due to some error: #{$!}")
- begin
- File.delete(resultfile) if FileTest.file?(resultfile)
- rescue
- report("unable to delete faulty #{resultfile}")
- end
- ok = false
- ensure
- deleteprofile(getvariable('profile'))
- File.delete(@@pstempfile) if FileTest.file?(@@pstempfile)
- File.delete(@@pdftempfile) if FileTest.file?(@@pdftempfile)
- end
- return ok
- end
-
- # private
-
- def method (str)
- if @@methods.key?(str) then
- @@methods[str]
- else
- str
- end
- end
-
- def pdfmethod? (str)
- case method(str).to_i
- when 1, 3, 4, 5 then return true
- end
- return false
- end
-
- def pdfprefix (str)
- case method(str).to_i
- when 1 then return 'raw-'
- when 4 then return 'lowres-'
- when 5 then return 'normal-'
- end
- return ''
- end
-
- def psmethod? (str)
- ! pdfmethod?(str)
- end
-
- def insertprofile (flags)
- for key in flags.keys do
- replacevariable("flag.#{key}", flags[key])
- end
- end
-
- def deleteprofile (filename)
- begin
- File.delete(filename) if FileTest.file?(filename)
- rescue
- end
- end
-
- def saveprofile (filename)
- return if filename.empty? || ! (ini = open(filename,"w"))
- @@pstopdfoptions.each do |k|
- str = @psoptions[k]
- # beware, booleans are translated, but so are yes/no which is dangerous
- if str.class == String then
- if ! str.empty? && (str != 'empty') then
- str.sub!(/(.+)\-/io, '')
- str = "/" + str unless str =~ /^(true|false|none|[\d\.\-\+]+)$/
- ini.puts("-d#{k}=#{str}\n")
- end
- end
- end
- ini.close
- debug("gs profile #{filename} saved")
- end
-
- def gsstream # private
- if getvariable('pipe') then '-' else @@pstempfile end
- end
-
- def gscolorswitch
- case getvariable('colormodel')
- when 'cmyk' then '-dProcessColorModel=/DeviceCMYK -dColorConversionStrategy=/CMYK '
- when 'rgb' then '-dProcessColorModel=/DeviceRGB -dColorConversionStrategy=/RGB '
- when 'gray' then '-dProcessColorModel=/DeviceGRAY -dColorConversionStrategy=/GRAY '
- else
- ''
- end
- end
-
- def gsdefaults
- defaults = ''
- begin
- defaults << '-dAutoRotatePages=/None ' if @psoptions['AutoRotatePages'].empty?
- rescue
- defaults << '-dAutoRotatePages=/None '
- end
- return defaults
- end
-
- def convertasis (inpfile, outfile)
-
- report("converting #{inpfile} as-is")
-
- @rs = Tool.line_separator(inpfile)
- debug("platform mac") if @rs == "\r"
-
- arguments = ''
- arguments << "\@gsprofile.ini "
- arguments << "-q -sDEVICE=pdfwrite -dNOPAUSE -dNOCACHE -dBATCH "
- arguments << "#{gsdefaults} "
- arguments << "#{gscolorswitch} "
- arguments << "-sOutputFile=#{outfile} #{inpfile} -c quit "
-
- debug("ghostscript: #{arguments}")
- unless ok = System.run('ghostscript',arguments) then
- begin
- report("removing file #{outfile}")
- File.delete(outfile) if FileTest.file?(outfile)
- rescue
- debug("file #{outfile} may be invalid")
- end
- end
- return ok
-
- end
-
- def convertbounded(inpfile, outfile)
- report("converting #{inpfile} bounded")
- do_convertbounded(inpfile, outfile)
- end
-
- def do_convertbounded(inpfile, outfile)
-
- begin
- return false if FileTest.file?(outfile) && (! File.delete(outfile))
- rescue
- return false
- end
-
- arguments = ''
- arguments << "\@gsprofile.ini "
- arguments << "-q -sDEVICE=pdfwrite -dNOPAUSE -dNOCACHE -dBATCH -dSAFER "
- arguments << "#{gscolorswitch} "
- arguments << "#{gsdefaults} "
- arguments << "-sOutputFile=#{outfile} #{gsstream} -c quit "
-
- debug("ghostscript: #{arguments}")
- debug('opening input file')
-
- @rs = Tool.line_separator(inpfile)
- debug("platform mac") if @rs == "\r"
-
- if FileTest.file?(outfile) and not File.writable?(outfile) then
- report("output file cannot be written")
- return false
- elsif not tmp = open(inpfile, 'rb') then
- report("input file cannot be opened")
- return false
- end
-
- debug('opening pipe/file')
-
- if getvariable('pipe') then
-
- return false unless eps = IO.popen(System.command('ghostscript',arguments),'wb')
- debug('piping data')
- unless pipebounded(tmp,eps) then
- debug('something went wrong in the pipe')
- File.delete(outfile) if FileTest.file?(outfile)
- end
- debug('closing pipe')
- eps.close_write
-
- else
-
- return false unless eps = File.open(@@pstempfile, 'wb')
-
- debug('copying data')
-
- if pipebounded(tmp,eps) then
- eps.close
- debug('processing temp file')
- begin
- ok = System.run('ghostscript',arguments)
- rescue
- ok = false
- # debug("fatal error: #{$!}")
- ensure
- end
- else
- eps.close
- ok = false
- end
-
- unless ok then
- begin
- report('no output file due to error')
- File.delete(outfile) if FileTest.file?(outfile)
- rescue
- # debug("fatal error: #{$!}")
- debug('file',outfile,'may be invalid')
- end
- end
-
- debug('deleting temp file')
- begin
- File.delete(@@pstempfile) if FileTest.file?(@@pstempfile)
- rescue
- end
-
- end
-
- tmp.close
- return FileTest.file?(outfile)
-
- end
-
- # hm, strange, no execute here, todo ! ! !
-
- def getdimensions (inpfile)
-
- # -dEPSFitPage and -dEPSCrop behave weird (don't work)
-
- arguments = "-sDEVICE=bbox -dSAFER -dNOPAUSE -dBATCH #{inpfile} "
-
- debug("ghostscript: #{arguments}")
-
- begin
- bbox = System.run('ghostscript',arguments,true,true)
- rescue
- bbox = ''
- end
-
- resetdimensions
-
- debug('bbox spec', bbox)
-
- if bbox =~ /(Exact|HiRes)BoundingBox:#{@@bboxspec}/moi then
- debug("high res bbox #{$2} #{$3} #{$4} #{$5}")
- setdimensions($2,$3,$4,$5)
- elsif bbox =~ /BoundingBox:#{@@bboxspec}/moi
- debug("low res bbox #{$1} #{$2} #{$3} #{$4}")
- setdimensions($1,$2,$3,$4)
- end
-
- return dimensions?
-
- end
-
- # def convertcropped (inpfile, outfile)
- # report("converting #{inpfile} cropped")
- # do_convertbounded(inpfile, @@pdftempfile)
- # return unless FileTest.file?(@@pdftempfile)
- # arguments = " --offset=#{@offset} #{@@pdftempfile} #{outfile}"
- # report("calling #{@@pdftrimwhite}")
- # unless ok = System.run(@@pdftrimwhite,arguments) then
- # report('cropping failed')
- # begin
- # File.delete(outfile)
- # rescue
- # end
- # begin
- # File.move(@@pdftempfile,outfile)
- # rescue
- # File.copy(@@pdftempfile,outfile)
- # File.delete(@@pdftempfile)
- # end
- # end
- # return ok
- # end
-
- def convertcropped (inpfile, outfile)
- report("converting #{inpfile} cropped")
- if File.expand_path(inpfile) == File.expand_path(outfile) then
- report("output filename must be different")
- elsif inpfile =~ /\.pdf$/io then
- System.run("pdftops -eps #{inpfile} #{@@pstempfile}")
- if getdimensions(@@pstempfile) then
- report("tight boundingbox found")
- end
- do_convertbounded(@@pstempfile, outfile)
- File.delete(@@pstempfile) if FileTest.file?(@@pstempfile)
- else
- if getdimensions(inpfile) then
- report("tight boundingbox found")
- end
- do_convertbounded(inpfile, outfile)
- end
- resetdimensions
- return true
- end
-
-
- def pipebounded (eps, out)
-
- epsbbox, skip, buffer = false, false, ''
-
- while str = eps.gets(rs=@rs) do
- if str =~ /^%!PS/oi then
- debug("looks like a valid ps file")
- break
- elsif str =~ /%PDF\-\d+\.\d+/oi then
- debug("looks like a pdf file, so let\'s quit")
- return false
- end
- end
-
- # why no BeginData check
-
- eps.rewind
-
-if dimensions? then
-
- debug('using found boundingbox')
-
-else
-
- debug('locating boundingbox')
- while str = eps.gets(rs=@rs) do
- case str
- when /^%%Page:/io then
- break
- when /^%%(Crop|HiResBounding|ExactBounding)Box:#{@@bboxspec}/moi then
- debug('high res boundingbox found')
- setdimensions($2,$3,$4,$5)
- break
- when /^%%BoundingBox:#{@@bboxspec}/moi then
- debug('low res boundingbox found')
- setdimensions($1,$2,$3,$4)
- end
- end
- debug('no boundingbox found') if @width == 0
-
-end
-
- eps.rewind
-
- while str = eps.gets(rs=@rs) do
- if str.sub!(/^(.*)%!PS/moi, "%!PS") then
- debug("removing pre banner data")
- out.puts(str)
- break
- end
- end
-
- while str = eps.gets(rs=@rs) do
- if skip then
- skip = false if str =~ /^%+(EndData|EndPhotoshop|BeginProlog).*$/o
- out.puts(str) if $1 == "BeginProlog"
- elsif str =~ /^%(BeginPhotoshop)\:\s*\d+.*$/o then
- skip = true
- elsif str =~ /^%%/mos then
- if ! epsbbox && str =~ /^%%(Page:|EndProlog)/io then
- out.puts(str) if $1 == "EndProlog"
- debug('faking papersize')
- # out.puts("<< /PageSize [#{@width} #{@height}] >> setpagedevice\n")
- if ! dimensions? then
- out.puts("<< /PageSize [1 1] >> setpagedevice\n")
- else
- out.puts("<< /PageSize [#{@width} #{@height}] >> setpagedevice\n")
- end
- out.puts("gsave #{@xoffset} #{@yoffset} translate\n")
- epsbbox = true
- elsif str =~ /^%%BeginBinary\:\s*\d+\s*$/o then
- debug('copying binary data')
- out.puts(str)
- while str = eps.gets(rs=@rs)
- if str =~ /^%%EndBinary\s*$/o then
- out.puts(str)
- else
- out.write(str)
- end
- end
- elsif str =~ /^%AI9\_PrivateDataBegin/o then
- debug('ignore private ai crap')
- break
- elsif str =~ /^%%EOF/o then
- debug('ignore post eof crap')
- break
- # elsif str =~ /^%%PageTrailer/o then
- # debug('ignoring post page trailer crap')
- # break
- elsif str =~ /^%%Trailer/o then
- debug('ignoring post trailer crap')
- break
- elsif str =~ /^%%Creator.*Illustrator.*$/io then
- debug('getting rid of problematic creator spec')
- str = "% Creator: Adobe Illustrator ..."
- out.puts(str)
- elsif str =~ /^%%AI.*(PaperRect|Margin)/io then
- debug('removing AI paper crap')
- elsif str =~ /^%%AI.*Version.*$/io then
- debug('removing dangerous version info')
- elsif str =~ /^(%+AI.*Thumbnail.*)$/o then
- debug('skipping AI thumbnail')
- skip = true
- else
- out.puts(str)
- end
- else
- out.puts(str)
- end
- end
-
- debug('done, sending EOF')
-
- out.puts "grestore\n%%EOF\n"
-
- # ok = $? == 0
- # report('process aborted, broken pipe, fatal error') unless ok
- # return ok
-
-resetdimensions
-
- return true
-
- end
-
- def downsample (inpfile, outfile, method='screen')
-
- # gs <= 8.50
-
- report("downsampling #{inpfile}")
-
- doit = true
- unless getvariable('force') then
- begin
- if f = File.open(inpfile) then
- f.binmode
- while doit && (data = f.gets) do
- if data =~ /\/ArtBox\s*\[\s*[\d\.]+\s+[\d\.]+\s+[\d\.]+\s+[\d\.]+\s*\]/io then
- doit = false
- end
- end
- f.close
- end
- rescue
- end
- end
-
- if doit then
- arguments = ''
- arguments << "-dPDFSETTINGS=/#{method} -dEmbedAllFonts=true "
- arguments << "#{gscolorswitch} "
- arguments << "#{gsdefaults} "
- arguments << "-q -sDEVICE=pdfwrite -dNOPAUSE -dNOCACHE -dBATCH -dSAFER "
- arguments << "-sOutputFile=#{outfile} #{inpfile} -c quit "
- unless ok = System.run('ghostscript',arguments) then
- begin
- File.delete(outfile) if FileTest.file?(outfile)
- report("removing file #{outfile}")
- rescue
- debug("file #{outfile} may be invalid")
- end
- end
- return ok
- else
- report("crop problem, straight copying #{inpfile}")
- File.copy(inpfile,outfile)
- return false
- end
-
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/graphics/inkscape.rb b/Master/texmf-dist/scripts/context/ruby/graphics/inkscape.rb
deleted file mode 100644
index 8f22d9b7954..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/graphics/inkscape.rb
+++ /dev/null
@@ -1,113 +0,0 @@
-# module : graphics/inkscape
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# ['base/variables','variables'].each do |r| begin require r ; rescue Exception ; else break ; end ; end
-# ['graphics/gs','gs'].each do |r| begin require r ; rescue Exception ; else break ; end ; end
-
-require 'base/variables'
-require 'base/system'
-require 'graphics/gs'
-
-class InkScape
-
- include Variables
-
- def initialize(logger=nil)
-
- unless logger then
- puts('inkscape class needs a logger')
- exit
- end
-
- @variables = Hash.new
- @logger = logger
-
- reset
-
- end
-
- def reset
- # nothing yet
- end
-
- def supported?(filename)
- filename =~ /.*\.(svg|svgz)/io
- end
-
- def convert(logfile=System.null)
-
- directpdf = false
-
- logfile = logfile.gsub(/\/+$/,"")
-
- inpfilename = getvariable('inputfile').dup
- outfilename = getvariable('outputfile').dup
- outfilename = inpfilename.dup if outfilename.empty?
- outfilename.gsub!(/(\.[^\.]*?)$/, ".pdf")
- tmpfilename = outfilename.gsub(/(\.[^\.]*?)$/, ".ps")
-
- if inpfilename.empty? || outfilename.empty? then
- report("no filenames given")
- return false
- end
- if inpfilename == outfilename then
- report("filenames must differ (#{inpfilename} #{outfilename})")
- return false
- end
- unless FileTest.file?(inpfilename) then
- report("unknown file #{inpfilename}")
- return false
- end
-
- # we need to redirect the error info else we get a pop up console
-
- if directpdf then
- report("converting #{inpfilename} to #{outfilename}")
- # resultpipe = "--without-gui --export-pdf=\"#{outfilename}\" 2>#{logfile}"
- resultpipe = "--without-gui --export-filename=\"#{outfilename}\" 2>#{logfile}"
- else
- report("converting #{inpfilename} to #{tmpfilename}")
- resultpipe = "--without-gui --print=\">#{tmpfilename}\" 2>#{logfile}"
- end
-
- arguments = [resultpipe,inpfilename].join(' ').gsub(/\s+/,' ')
-
- ok = true
- begin
- debug("inkscape: #{arguments}")
- # should work
- # ok = System.run('inkscape',arguments) # does not work here
- # but 0.40 only works with this:
- command = "inkscape #{arguments}"
- report(command)
- ok = system(command)
- # and 0.41 fails with everything
- # and 0.45 is better
- rescue
- report("aborted due to error")
- return false
- else
- return false unless ok
- end
-
- if not directpdf then
- ghostscript = GhostScript.new(@logger)
- ghostscript.setvariable('inputfile',tmpfilename)
- ghostscript.setvariable('outputfile',outfilename)
- report("converting #{tmpfilename} to #{outfilename}")
- ghostscript.convert
- begin
- File.delete(tmpfilename)
- rescue
- end
- end
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/graphics/magick.rb b/Master/texmf-dist/scripts/context/ruby/graphics/magick.rb
deleted file mode 100644
index f59087bdf44..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/graphics/magick.rb
+++ /dev/null
@@ -1,161 +0,0 @@
-# module : graphics/inkscape
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# ['base/variables','variables'].each do |r| begin require r ; rescue Exception ; else break ; end ; end
-
-require 'base/variables'
-
-class ImageMagick
-
- include Variables
-
- def initialize(logger=nil)
-
- unless logger then
- puts('magick class needs a logger')
- exit
- end
-
- @variables = Hash.new
- @logger = logger
-
- reset
-
- end
-
- def reset
- ['compression','depth','colorspace','quality'].each do |key|
- setvariable(key)
- end
- end
-
- def supported?(filename) # ? pdf
- filename =~ /.*\.(png|gif|tif|tiff|jpg|jpeg|eps|ai\d*)/io
- end
-
- def convert(suffix='pdf')
-
- inpfilename = getvariable('inputfile').dup
- outfilename = getvariable('outputfile').dup
- outfilename = inpfilename.dup if outfilename.empty?
- outfilename.gsub!(/(\.[^\.]*?)$/, ".#{suffix}")
-
- if inpfilename.empty? || outfilename.empty? then
- report("no filenames given")
- return false
- end
- if inpfilename == outfilename then
- report("filenames must differ (#{inpfilename} #{outfilename})")
- return false
- end
- unless FileTest.file?(inpfilename) then
- report("unknown file #{inpfilename}")
- return false
- end
-
- if inpfilename =~ /\.tif+$/io then
- tmpfilename = 'temp.png'
- arguments = "#{inpfilename} #{tmpfilename}"
- begin
- debug("imagemagick: #{arguments}")
- ok = System.run('imagemagick',arguments)
- rescue
- report("aborted due to error")
- return false
- else
- return false unless ok
- end
- inpfilename = tmpfilename
- end
-
- compression = depth = colorspace = quality = ''
-
- if getvariable('compression') =~ /(zip|jpeg)/o then
- compression = " -compress #{$1}"
- end
- if getvariable('depth') =~ /(8|16)/o then
- depth = "-depth #{$1}"
- end
- if getvariable('colorspace') =~ /(gray|rgb|cmyk)/o then
- colorspace = "-colorspace #{$1}"
- end
- case getvariable('quality')
- when 'low' then quality = '-quality 0'
- when 'medium' then quality = '-quality 75'
- when 'high' then quality = '-quality 100'
- end
-
- report("converting #{inpfilename} to #{outfilename}")
-
- arguments = [compression,depth,colorspace,quality,inpfilename,outfilename].join(' ').gsub(/\s+/,' ')
-
- begin
- debug("imagemagick: #{arguments}")
- ok = System.run('imagemagick',arguments)
- rescue
- report("aborted due to error")
- return false
- else
- return ok
- end
-
- end
-
- def autoconvert
-
- inpfilename = getvariable('inputfile')
- outfilename = getvariable('outputfile')
-
- if inpfilename.empty? || ! FileTest.file?(inpfilename) then
- report("missing file #{inpfilename}")
- return
- end
-
- outfilename = inpfilename.dup if outfilename.empty?
- tmpfilename = 'temp.jpg'
-
- reset
-
- megabyte = 1024*1024
-
- ok = false
-
- if FileTest.size(inpfilename)>2*megabyte
- setvariable('compression','zip')
- ok = convert
- else
- setvariable('compression','jpeg')
- if FileTest.size(inpfilename)>10*megabyte then
- setvariable('quality',85)
- elsif FileTest.size(inpfilename)>5*megabyte then
- setvariable('quality',90)
- else
- setvariable('quality',95)
- end
- report("auto quality #{getvariable('quality')}")
- setvariable('outputfile', tmpfilename)
- ok = convert('jpg')
- setvariable('inputfile', tmpfilename)
- setvariable('outputfile', outfilename)
- ok = convert
- begin
- File.delete(tmpfilename)
- rescue
- report("#{tmpfilename} cannot be deleted")
- end
- end
-
- reset
-
- return ok
-
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/imgtopdf.rb b/Master/texmf-dist/scripts/context/ruby/imgtopdf.rb
deleted file mode 100644
index 98a36c17fd9..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/imgtopdf.rb
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/env ruby
-
-# program : newimgtopdf
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2006
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-unless defined? ownpath
- ownpath = $0.sub(/[\\\/]\w*?\.rb/i,'')
- $: << ownpath
-end
-
-require 'base/switch'
-require 'base/logger'
-
-require 'graphics/magick'
-
-banner = ['ImgToPdf', 'version 1.1.2', '2002-2006', 'PRAGMA ADE/POD']
-
-class Commands
-
- include CommandBase
-
- # nowadays we would force a directive, but
- # for old times sake we handle default usage
-
- def main
- filename = @commandline.argument('first')
-
- if filename.empty? then
- help
- else
- convert
- end
- end
-
- # actions
-
- def convert
-
- magick = Magick.new(session)
-
- ['compression','depth','colorspace','quality','inputpath','outputpath'].each do |v|
- magick.setvariable(v,@commandline.option(v))
- end
-
- @commandline.arguments.each do |fullname|
- magick.setvariable('inputfile',fullname)
- magick.setvariable('outputfile',fullname.gsub(/(\..*?$)/io, '.pdf'))
- if @commandline.option('auto') then
- magick.autoconvert
- else
- magick.convert
- end
- end
- end
-
-end
-
-logger = Logger.new(banner.shift)
-commandline = CommandLine.new
-
-commandline.registerflag('auto')
-
-commandline.registervalue('compression')
-commandline.registervalue('depth')
-commandline.registervalue('colorspace')
-commandline.registervalue('quality')
-
-commandline.registervalue('inputpath')
-commandline.registervalue('outputpath')
-
-
-commandline.registeraction('help')
-commandline.registeraction('version')
-
-commandline.registeraction('convert', 'convert image into pdf')
-
-commandline.expand
-
-Commands.new(commandline,logger,banner).send(commandline.action || 'main')
diff --git a/Master/texmf-dist/scripts/context/ruby/pdftools.rb b/Master/texmf-dist/scripts/context/ruby/pdftools.rb
deleted file mode 100644
index 8ad74ec4f36..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/pdftools.rb
+++ /dev/null
@@ -1,861 +0,0 @@
-#!/usr/bin/env ruby
-
-# program : pdftools
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2003-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# This script will harbor some handy manipulations on tex
-# related files.
-
-banner = ['PDFTools', 'version 1.2.1', '2003/2005', 'PRAGMA ADE/POD']
-
-$: << File.expand_path(File.dirname($0)) ; $: << File.join($:.last,'lib') ; $:.uniq!
-
-require 'base/switch'
-require 'base/logger'
-
-require 'fileutils'
-# require 'ftools'
-
-class File
-
- def File.deletefiles(*filenames)
- filenames.flatten.each do |filename|
- begin
- delete(filename) if FileTest.file?(filename)
- rescue
- end
- end
- end
-
- def File.needsupdate(oldname,newname)
- begin
- return File.stat(oldname).mtime != File.stat(newname).mtime
- rescue
- return true
- end
- end
-
- def File.syncmtimes(oldname,newname)
- begin
- t = Time.now # i'm not sure if the time is frozen, so we do it here
- File.utime(0,t,oldname,newname)
- rescue
- end
- end
-
- def File.replacesuffix(oldname,subpath='')
- newname = File.expand_path(oldname.sub(/\.\w+?$/,'.pdf'))
- File.join(File.dirname(newname),subpath,File.basename(newname))
- end
-
-end
-
-class ImageMagick
-
- def initialize
-
- begin
- version = `convert -version`
- rescue
- @binary = nil
- ensure
- if (version) && (! version.empty?) && (version =~ /ImageMagick/mo) && (version =~ /version/mio) then
- @binary = 'convert'
- else
- @binary = 'imagemagick'
- end
- end
-
- end
-
- def process(arguments)
- begin
- @binary && system("#{@binary} #{arguments}")
- rescue
- false
- end
- end
-
-end
-
-class TexExec
-
- def initialize
- @binary = 'texmfstart texexec.pl --pdf --batch --silent --purge'
- end
-
- def process(arguments,once=true)
- begin
- if once then
- @binary && system("#{@binary} --once #{arguments}")
- else
- @binary && system("#{@binary} #{arguments}")
- end
- rescue
- false
- end
- end
-
-end
-
-class PdfImages
-
- def initialize
- @binary = "pdfimages"
- end
-
- def process(arguments)
- begin
- @binary && system("#{@binary} #{arguments}")
- rescue
- false
- end
- end
-
-end
-
-class ConvertImage
-
- def initialize(command=nil)
- @command = command
- end
-
- def convertimage(filename)
-
- return if filename =~ /\.(pdf)$/io
-
- retain = @command.option('retain')
- subpath = @command.option('subpath')
-
- if filename =~ /\s/ then
- @command.report("skipping strange filename '#{filename}'")
- else
- newname = File.replacesuffix(filename,subpath)
- # newname.gsub!(s/[^a-zA-Z0-9\_-\.]/o, '-')
- begin
- File.makedirs(File.dirname(newname))
- rescue
- end
- if ! retain || File.needsupdate(filename,newname) then
- imagemagick = ImageMagick.new
- if imagemagick then
- ok = imagemagick.process("-compress zip -quality 99 #{filename} #{newname}")
- File.syncmtimes(oldname,newname) if retain
- end
- end
- end
- end
-
-end
-
-class DownsampleImage
-
- def initialize(command=nil)
- @command = command
- end
-
- def convertimage(filename)
-
- return if filename =~ /\.(pdf)$/io
-
- retain = @command.option('retain')
- subpath = @command.option('subpath')
-
- if @command.option('lowres') then
- method = '4'
- elsif @command.option('medres') || @command.option('normal') then
- method = '5'
- else
- method = '4'
- end
-
- if filename =~ /\s/ then
- @command.report("skipping strange filename '#{filename}'")
- else
- newname = File.replacesuffix(filename,subpath)
- begin
- File.makedirs(File.dirname(newname))
- rescue
- end
- if ! retain || File.needsupdate(filename,newname) then
- ok = system("texmfstart pstopdf.rb --method=#{method} #{filename} #{newname}")
- File.syncmtimes(oldname,newname) if retain
- end
- end
- end
-
-end
-
-class ColorImage
-
- def initialize(command=nil,tmpname='pdftools')
- @command = command
- @tmpname = tmpname
- @colorname = nil
- @colorspec = nil
- @colorspace = nil
- end
-
- def registercolor(spec='.5',name='c')
- name = name || 'c'
- spec = spec.split(',')
- case spec.length
- when 4
- @colorname, @colorspec, @colorspace = name, spec.join('/'), 'cmyk'
- when 3
- @colorname, @colorspec, @colorspace = name, spec.join('/'), 'rgb'
- when 1
- @colorname, @colorspec, @colorspace = name, spec.join('/'), 'gray'
- else
- @colorname, @colorspec, @colorspace = nil, nil, nil
- end
- end
-
- def convertimage(filename)
-
- invert = @command.option('invert')
- retain = @command.option('retain')
- subpath = @command.option('subpath')
-
- subpath += '/' unless subpath.empty?
-
- if @colorname && ! @colorname.empty? && @colorspec && ! @colorspec.empty? then
- basename = filename.sub(/\.\w+?$/,'')
- oldname = filename
- ppmname = @tmpname + '-000.ppm'
- jpgname = @tmpname + '-000.jpg'
- newname = File.expand_path(oldname)
- newname = File.dirname(newname) + '/' + subpath + @colorname + '-' + File.basename(newname)
- newname.sub!(/\.\w+?$/, '.pdf')
- begin
- File.makedirs(File.dirname(newname))
- rescue
- end
- if ! retain || File.needsupdate(filename,newname) then
- pdfimages = PdfImages.new
- imagemagick = ImageMagick.new
- if pdfimages && imagemagick then
- File.deletefiles(ppmname,jpgname,newname)
- if filename =~ /\.(pdf)$/io then
- ok = pdfimages.process("-j -f 1 -l 1 #{filename} #{@tmpname}")
- if ok then
- if FileTest.file?(ppmname) then
- inpname = ppmname
- elsif FileTest.file?(jpgname) then
- inpname = jpgname
- else
- ok = false
- end
- if ok then
- switch = if ! invert then '-negate' else '' end
- # make sure that we keep the format
- tmpname = File.basename(inpname)
- tmpname = tmpname.sub(/(.*)\..*?$/,@tmpname) # somehow sub! fails here
- ok = imagemagick.process("-colorspace gray #{switch} #{inpname} #{tmpname}")
- if ! ok || ! FileTest.file?(tmpname) then
- # problems
- else
- ok = imagemagick.process("-colorspace #{switch} #{@colorspace} -colorize #{@colorspec} -compress zip #{tmpname} #{newname}")
- if ! ok || ! FileTest.file?(newname) then
- # unable to colorize image
- else
- # conversion done
- end
- end
- end
- end
- else
- # make sure that we keep the format
- tmpname = File.basename(basename)
- tmpname = tmpname.sub(/(.*)\..*?$/,@tmpname) # somehow sub! fails here
- ok = imagemagick.process("-colorspace gray #{oldname} #{tmpname}")
- if ! ok || ! FileTest.file?(tmpname) then
- # unable to convert color to gray
- else
- ok = imagemagick.process("-colorspace #{@colorspace} -colorize #{@colorspec} -compress zip #{tmpname} #{newname}")
- if ! ok || ! FileTest.file?(newname) then
- # unable to colorize image
- else
- # conversion done
- end
- end
- end
- File.deletefiles(ppmname,jpgname,tmpname)
- File.syncmtimes(filename,newname) if retain
- end
- end
- end
- end
-
-end
-
-class SpotColorImage
-
- def initialize(command=nil, tmpname='pdftools')
- @command = command
- @tmpname = tmpname
- @colorname = nil
- @colorspec = nil
- @colorspace = nil
- @colorfile = nil
- end
-
- def registercolor(spec='.5',name='unknown')
- name = name || 'unknown'
- if spec =~ /^[\d\.\,]+$/ then
- spec = spec.split(',')
- case spec.length
- when 4
- @colorname, @colorspec, @colorspace = name, ["c=#{spec[0]}","m=#{spec[1]}","y=#{spec[2]}","k=#{spec[3]}"].join(','), 'cmyk'
- when 3
- @colorname, @colorspec, @colorspace = name, ["r=#{spec[0]}","g=#{spec[1]}","b=#{spec[2]}"].join(','), 'rgb'
- when 1
- @colorname, @colorspec, @colorspace = name, ["s=#{spec[0]}"].join(','), 'gray'
- else
- @colorname, @colorspec, @colorspace = nil, nil, nil
- end
- else
- @colorname, @colorfile = name, spec
- end
- end
-
- def convertgrayimage(filename)
-
- invert = @command.option('invert')
- retain = @command.option('retain')
- subpath = @command.option('subpath')
-
- subpath += '/' unless subpath.empty?
-
- if @colorname && ! @colorname.empty? && ((@colorspec && ! @colorspec.empty?) || (@colorfile && ! @colorfile.empty?)) then
- basename = filename.sub(/\.\w+?$/,'')
- oldname = filename # png jpg pdf
- newname = File.expand_path(oldname)
- ppmname = @tmpname + '-000.ppm'
- jpgname = @tmpname + '-000.jpg'
- outname = @tmpname + '-000.pdf'
- texname = @tmpname + '-temp.tex'
- pdfname = @tmpname + '-temp.pdf'
- newname = File.dirname(newname) + '/' + subpath + @colorname + '-' + File.basename(newname)
- newname.sub!(/\.\w+?$/, '.pdf')
- begin
- File.makedirs(File.dirname(newname))
- rescue
- end
- if ! retain || File.needsupdate(filename,newname) then
- pdfimages = PdfImages.new
- imagemagick = ImageMagick.new
- texexec = TexExec.new
- if pdfimages && imagemagick && texexec then
- if filename =~ /\.(jpg|png|pdf)$/io then
- @command.report("processing #{basename}")
- File.deletefiles(ppmname,jpgname,newname)
- switch = if ! invert then '-negate' else '' end
- if filename =~ /\.(pdf)$/io then
- ok = pdfimages.process("-j -f 1 -l 1 #{oldname} #{@tmpname}")
- if ok then
- if FileTest.file?(ppmname) then
- inpname = ppmname
- elsif FileTest.file?(jpgname) then
- inpname = jpgname
- else
- ok = false
- end
- if ok then
- ok = imagemagick.process("-colorspace gray #{switch} -compress zip #{inpname} #{outname}")
- end
- end
- else
- ok = imagemagick.process("-colorspace gray #{switch} -compress zip #{oldname} #{outname}")
- end
- if ok then
- ok = false unless FileTest.file?(outname)
- end
- if ok then
- if f = File.open(texname, 'w') then
- f.puts(conversionfile(filename,outname,newname))
- f.close
- ok = texexec.process(texname)
- else
- ok = false
- end
- @command.report("error in processing #{newname}") unless ok
- if FileTest.file?(pdfname) then
- if f = File.open(pdfname,'r') then
- f.binmode
- begin
- if g = File.open(newname,'w') then
- g.binmode
- data = f.read
- # pdftex (direct) & imagemagick (indirect)
- if data =~ /(\d+)\s+0\s+obj\s+\[\/Separation\s+\/#{@colorname}/mos then
- @command.report("replacing separation color")
- object = $1
- data.gsub!(/(\/Type\s+\/XObject.*?)(\/ColorSpace\s*(\/DeviceGray|\/DeviceCMYK|\/DeviceRGB|\d+\s+\d+\s+R))/moi) do
- $1 + "/ColorSpace #{object} 0 R".ljust($2.length)
- end
- elsif data =~ /(\d+)\s+0\s+obj\s+\[\/Indexed\s*\[/mos then
- @command.report("replacing indexed color")
- # todo: more precise check on color
- object = $1
- data.gsub!(/(\/Type\s+\/XObject.*?)(\/ColorSpace\s*(\/DeviceGray|\/DeviceCMYK|\/DeviceRGB|\d+\s+\d+\s+R))/moi) do
- $1 + "/ColorSpace #{object} 0 R".ljust($2.length)
- end
- elsif data =~ /(\d+)\s+0\s+obj\s+\[\/Separation/mos then
- @command.report("replacing separation color")
- object = $1
- data.gsub!(/(\/Type\s+\/XObject.*?)(\/ColorSpace\s*(\/DeviceGray|\/DeviceCMYK|\/DeviceRGB|\d+\s+\d+\s+R))/moi) do
- $1 + "/ColorSpace #{object} 0 R".ljust($2.length)
- end
- end
- g.write(data)
- g.close
- end
- rescue
- @command.report("error in converting #{newname}")
- else
- @command.report("#{newname} is converted")
- end
- f.close
- end
- else
- @command.report("error in writing #{newname}")
- end
- else
- @command.report("error in producing #{newname}")
- end
- File.deletefiles(ppmname,jpgname,outname)
- # File.deletefiles(texname,pdfname)
- File.syncmtimes(filename,newname) if retain
- end
- else
- @command.report("error in locating binaries")
- end
- else
- @command.report("#{newname} is not changed")
- end
- end
- end
-
- private
-
- # % example colorfile:
- #
- # \definecolor [darkblue] [c=1,m=.38,y=0,k=.64] % pantone pms 2965 uncoated m
- # \definecolor [darkyellow] [c=0,m=.28,y=1,k=.06] % pantone pms 124 uncoated m
- #
- # % \definecolor [darkblue-100] [darkblue] [p=1]
- # % \definecolor [darkyellow-100] [darkyellow] [p=1]
- #
- # \definecolorcombination [pdftoolscolor] [darkblue=.12,darkyellow=.28] [c=.1,m=.1,y=.3,k=.1]
-
- def conversionfile(originalname,filename,finalname)
- tex = "\\setupcolors[state=start]\n"
- if @colorfile then
- tex += "\\readfile{#{@colorfile}}{}{}\n"
- tex += "\\starttext\n"
- # tex += "\\predefineindexcolor[pdftoolscolor]\n"
- tex += "\\startTEXpage\n"
- tex += "\\pdfimage{#{filename}}\n"
- tex += "\\stopTEXpage\n"
- tex += "\\stoptext\n"
- else
- tex += "\\definecolor[#{@colorname}][#{@colorspec}]\n"
- tex += "\\definecolor[pdftoolscolor][#{@colorname}][p=1]\n"
- tex += "\\starttext\n"
- tex += "\\startTEXpage\n"
- tex += "\\hbox{\\color[pdftoolscolor]{\\pdfimage{#{filename}}}}\n"
- tex += "\\stopTEXpage\n"
- tex += "\\stoptext\n"
- end
- tex += "\n"
- tex += "% old: #{originalname}\n"
- tex += "% new: #{finalname}\n"
- return tex
- end
-
-end
-
-module XML
-
- def XML::version
- "<?xml version='1.0'?>"
- end
-
- def XML::start(element, attributes='')
- if attributes.empty? then
- "<#{element}>"
- else
- "<#{element} #{attributes}>"
- end
- end
-
- def XML::end(element)
- "</#{element}>"
- end
-
- def XML::empty(element, attributes='')
- if attributes && attributes.empty? then
- "<#{element}/>"
- else
- "<#{element} #{attributes}/>"
- end
- end
-
- def XML::element(element, attributes='', content='')
- if content && ! content.empty? then
- XML::start(element,attributes) + content + XML::end(element)
- else
- XML::empty(element,attributes)
- end
- end
-
- def XML::box(tag, rect, type=1)
- case type
- when 1
- if rect && ! rect.empty? then
- rect = rect.split(' ')
- XML::element("#{tag}box", '',
- XML::element("llx", '', rect[0]) +
- XML::element("lly", '', rect[1]) +
- XML::element("ulx", '', rect[2]) +
- XML::element("uly", '', rect[3]) )
- else
- XML::empty("#{tag}box")
- end
- when 2
- if rect && ! rect.empty? then
- rect = rect.split(' ')
- XML::element("box", "type='#{tag}'",
- XML::element("llx", '', rect[0]) +
- XML::element("lly", '', rect[1]) +
- XML::element("ulx", '', rect[2]) +
- XML::element("uly", '', rect[3]) )
- else
- XML::empty("box", "type='#{tag}'")
- end
- when 3
- if rect && ! rect.empty? then
- rect = rect.split(' ')
- XML::element("box", "type='#{tag}' llx='#{rect[0]}' lly='#{rect[1]}' ulx='#{rect[2]}' uly='#{rect[3]}'")
- else
- XML::empty("box", "type='#{tag}'")
- end
- else
- ''
- end
- end
-
- def XML::crlf
- "\n"
- end
-
- def XML::skip(n=1)
- ' '*n
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- # alias savedhelp :help
-
- # def help
- # savedhelp
- # report("under construction (still separate tools)")
- # end
-
- # filename.pdf --spotimage --colorname=darkblue --colorspec=1,0.38,0,0.64
-
- def spotimage
-
- if ! @commandline.argument('first').empty? && files = findfiles() then
- colorname = @commandline.option('colorname')
- colorspec = @commandline.option('colorspec')
- if colorname && ! colorname.empty? && colorspec && ! colorspec.empty? then
- files.each do |filename|
- s = SpotColorImage.new(self)
- s.registercolor(colorspec,colorname)
- s.convertgrayimage(filename)
- end
- else
- report("provide --colorname=somename --colorspec=c,m,y,k")
- end
- else
- report("provide filename (png, jpg, pdf)")
- end
-
- end
-
- def colorimage
-
- if ! @commandline.argument('first').empty? && files = findfiles() then
- colorname = @commandline.option('colorname')
- colorspec = @commandline.option('colorspec')
- if colorspec && ! colorspec.empty? then
- files.each do |filename|
- s = ColorImage.new(self)
- s.registercolor(colorspec,colorname) # name optional
- s.convertimage(filename)
- end
- else
- report("provide --colorspec=c,m,y,k")
- end
- else
- report("provide filename")
- end
-
- end
-
- def convertimage
-
- if ! @commandline.argument('first').empty? && files = findfiles() then
- files.each do |filename|
- s = ConvertImage.new(self)
- s.convertimage(filename)
- end
- else
- report("provide filename")
- end
-
- end
-
- def downsampleimage
-
- if ! @commandline.argument('first').empty? && files = findfiles() then
- files.each do |filename|
- s = DownsampleImage.new(self)
- s.convertimage(filename)
- end
- else
- report("provide filename")
- end
-
- end
-
- def info
-
- if files = findfiles() then
-
- print(XML.version + XML.crlf)
- print(XML.start('pdfinfo', "xmlns='http://www.pragma-ade.com/schemas/pdfinfo.rng'") + XML.crlf)
-
- files.each do |filename|
-
- if filename =~ /\.pdf$/io then
-
- begin
- data = `pdfinfo -box #{filename}`.chomp.split("\n")
- rescue
- data = nil
- end
-
- if data then
-
- pairs = Hash.new
-
- data.each do |d|
- if (d =~ /^\s*(.*?)\s*\:\s*(.*?)\s*$/moi) then
- key, val = $1, $2
- pairs[key.downcase.sub(/ /,'')] = val
- end
- end
-
- print(XML.skip(1) + XML.start('pdffile', "filename='#{filename}'") + XML.crlf)
-
- print(XML.skip(2) + XML.element('path', '', File.expand_path(filename)) + XML.crlf)
-
- if pairs.key?('error') then
-
- print(XML.skip(2) + XML.element('comment', '', pairs['error']) + XML.crlf)
-
- else
-
- print(XML.skip(2) + XML.element('version', '', pairs['pdfversion']) + XML.crlf)
- print(XML.skip(2) + XML.element('pages', '', pairs['pages' ]) + XML.crlf)
- print(XML.skip(2) + XML.element('title', '', pairs['title' ]) + XML.crlf)
- print(XML.skip(2) + XML.element('subject', '', pairs['subject' ]) + XML.crlf)
- print(XML.skip(2) + XML.element('author', '', pairs['author' ]) + XML.crlf)
- print(XML.skip(2) + XML.element('producer', '', pairs['producer' ]) + XML.crlf)
-
- if pairs.key?('creationdate') then
- pairs['creationdate'].sub!(/(\d\d)\/(\d\d)\/(\d\d)/) do
- '20' + $3 + '-' + $1 + '-' +$2
- end
- pairs['creationdate'].sub!(/(\d\d)\/(\d\d)\/(\d\d\d\d)/) do
- $3 + '-' + $1 + '-' + $2
- end
- print(XML.skip(2) + XML.element('creationdate', '', pairs['creationdate']) + XML.crlf)
- end
-
- if pairs.key?('moddate') then
- if pairs['moddate'] =~ /(\d\d\d\d)(\d\d)(\d\d)/ then
- pairs['moddate'] = "#{$1}-#{$2}-#{$3}"
- end
- print(XML.skip(2) + XML.element('modificationdate', '', pairs['moddate']) + XML.crlf)
- end
-
- print(XML.skip(2) + XML.element('tagged', '', pairs['tagged' ]) + XML.crlf)
- print(XML.skip(2) + XML.element('encrypted', '', pairs['encrypted']) + XML.crlf)
- print(XML.skip(2) + XML.element('optimized', '', pairs['optimized']) + XML.crlf)
-
- if pairs.key?('PageSize') then
- print(XML.skip(2) + XML.element('width', '', pairs['pagesize'].sub(/\s*(.*?)\s+(.*?)\s+.*/, $1)) + XML.crlf)
- print(XML.skip(2) + XML.element('height', '', pairs['pagesize'].sub(/\s*(.*?)\s+(.*?)\s+.*/, $2)) + XML.crlf)
- end
-
- if pairs.key?('FileSize') then
- print(XML.skip(2) + XML.element('size', '', pairs['filesize'].sub(/\s*(.*?)\s+.*/, $1)) + XML.crlf)
- end
-
- print(XML.skip(2) + XML.box('media', pairs['mediabox']) + XML.crlf)
- print(XML.skip(2) + XML.box('crop' , pairs['cropbox' ]) + XML.crlf)
- print(XML.skip(2) + XML.box('bleed', pairs['bleedbox']) + XML.crlf)
- print(XML.skip(2) + XML.box('trim' , pairs['trimBox' ]) + XML.crlf)
- print(XML.skip(2) + XML.box('art' , pairs['artbox' ]) + XML.crlf)
-
- end
-
- print(XML.skip(1) + XML.end('pdffile') + XML.crlf)
-
- end
-
- end
-
- end
-
- print(XML.end('pdfinfo') + XML.crlf)
-
- end
-
- end
-
- # name type emb sub uni object ID
- # ------------------------------------ ------------ --- --- --- ---------
- # EOPLBP+TimesNewRomanPSMT TrueType yes yes no 167 0
- # Times-Roman TrueType no no no 95 0
- # EPBAAB+Helvetica Type 1C yes yes yes 108 0
- # EPBMLE+Helvetica-Oblique Type 1C yes yes yes 111 0
- # Helvetica TrueType no no no 112 0
-
- def checkembedded
- $stderr = $stdout
- $stdout.flush
- if @commandline.option('pattern') then
- # **/*.pdf
- filenames, n = globfiles(@commandline.option('pattern'),'pdf'), 0
- else
- filenames, n = findfiles('pdf'), 0
- end
- filenames.sort.each do |file|
- report("= checking #{File.expand_path(file)}")
- result = `pdffonts #{file}`.chomp
- lines = result.split(/\n/)
- if result =~ /emb\s+sub\s+uni/io then
- lines.each do |line|
- report("! #{line}") if line =~ /no\s+(no|yes)\s+(no|yes)/io
- end
- else
- lines.each do |line|
- report("? #{line}")
- end
- end
- report("")
- end
- end
-
- def countpages
- if @commandline.option('pattern') then
- filenames, n = globfiles(@commandline.option('pattern'),'pdf'), 0
- else
- filenames, n = findfiles('pdf'), 0
- end
- threshold = @commandline.option('threshold').to_i rescue 0
- filenames.each do |filename|
- if `pdfinfo #{filename}`.chomp =~ /^pages\s*\:\s*(\d+)/moi then
- p = $1
- m = p.to_i rescue 0
- if threshold == 0 or m > threshold then
- report("#{p.rjust(4)} pages found in #{filename}")
- n += m
- end
- end
- end
- report("")
- report("#{n.to_s.rjust(4)} pages in total")
- end
-
- def analyzefile
- # needs an update
- filenames = @commandline.arguments
- filenames.each do |filename|
- if filename && FileTest.file?(filename) && filename =~ /\.pdf/io then
- filesize = FileTest.size(filename)
- report("analyzing file : #{filename}")
- report("file size : #{filesize}")
- if pdf = File.open(filename) then
- pdf.binmode
- nofobject, nofxform, nofannot, noflink, nofwidget, nofnamed, nofscript, nofcross = 0, 0, 0, 0, 0, 0, 0, 0
- while data = pdf.gets do
- data.scan(/\d+\s+\d+\s+obj/o) do nofobject += 1 end
- data.scan(/\/Type\s*\/XObject/o) do nofxform += 1 end
- data.scan(/\/Type\s*\/Annot/o) do nofannot += 1 end
- data.scan(/\/GoToR\s*\/F/o) do nofcross += 1 end
- data.scan(/\/Subtype\s*\/Link/o) do noflink += 1 end
- data.scan(/\/Subtype\s*\/Widget/o) do nofwidget += 1 end
- data.scan(/\/S\s*\/Named/o) do nofnamed += 1 end
- data.scan(/\/S\s*\/JavaScript/o) do nofscript += 1 end
- end
- pdf.close
- report("objects : #{nofobject}")
- report("xforms : #{nofxform}")
- report("annotations : #{nofannot}")
- report("links : #{noflink} (#{nofnamed} named / #{nofscript} scripts / #{nofcross} files)")
- report("widgets : #{nofwidget}")
- end
- end
- end
- end
-
-end
-
-logger = Logger.new(banner.shift)
-commandline = CommandLine.new
-
-commandline.registeraction('spotimage' , 'filename --colorspec= --colorname= [--retain --invert --subpath=]')
-commandline.registeraction('colorimage', 'filename --colorspec= [--retain --invert --colorname= ]')
-commandline.registeraction('convertimage', 'filename [--retain --subpath]')
-commandline.registeraction('downsampleimage', 'filename [--retain --subpath --lowres --normal]')
-commandline.registeraction('info', 'filename')
-commandline.registeraction('countpages', '[--pattern --threshold]')
-commandline.registeraction('checkembedded', '[--pattern]')
-
-commandline.registeraction('analyzefile' , 'filename')
-
-commandline.registeraction('help')
-commandline.registeraction('version')
-
-commandline.registervalue('colorname')
-commandline.registervalue('colorspec')
-commandline.registervalue('subpath')
-commandline.registervalue('pattern')
-commandline.registervalue('threshold',0)
-
-commandline.registerflag('lowres')
-commandline.registerflag('medres')
-commandline.registerflag('normal')
-commandline.registerflag('invert')
-commandline.registerflag('retain')
-
-commandline.expand
-
-Commands.new(commandline,logger,banner).send(commandline.action || 'help')
diff --git a/Master/texmf-dist/scripts/context/ruby/pstopdf.rb b/Master/texmf-dist/scripts/context/ruby/pstopdf.rb
deleted file mode 100644
index 73e628df23b..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/pstopdf.rb
+++ /dev/null
@@ -1,533 +0,0 @@
-#!/usr/bin/env ruby
-
-# program : pstopdf
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-banner = ['PsToPdf', 'version 2.0.1', '2002-2006', 'PRAGMA ADE/POD']
-
-$: << File.expand_path(File.dirname($0)) ; $: << File.join($:.last,'lib') ; $:.uniq!
-
-# todo: paden/prefix in magick and inkscape
-# todo: clean up method handling (pass strings, no numbers)
-# --method=crop|bounded|raw|...
-# --resolution=low|normal|medium|high|printer|print|screen|ebook|default
-# + downward compatible flag handling
-
-require 'base/switch'
-require 'base/tool'
-require 'base/logger'
-
-require 'graphics/gs'
-require 'graphics/magick'
-require 'graphics/inkscape'
-
-require 'rexml/document'
-
-exit if defined?(REQUIRE2LIB)
-
-class Commands
-
- include CommandBase
-
- # nowadays we would force a directive, but
- # for old times sake we handle default usage
-
- def main
- filename = @commandline.argument('first')
- pattern = @commandline.option('pattern')
- if filename.empty? && ! pattern.empty? then
- pattern = "**/#{pattern}" if @commandline.option('recurse')
- globfiles(pattern)
- end
- filename = @commandline.argument('first')
- if filename.empty? then
- help
- elsif filename =~ /\.exa$/ then
- request
- else
- convert
- end
- end
-
- # actions
-
- def convert
-
- ghostscript = GhostScript.new(logger)
- magick = ImageMagick.new(logger)
- inkscape = InkScape.new(logger)
-
- outpath = @commandline.option('outputpath')
- unless outpath.empty? then
- begin
- File.expand_path(outpath)
- outpath = File.makedirs(outpath) unless FileTest.directory?(outpath)
- rescue
- # sorry
- end
- end
-
- @commandline.arguments.each do |filename|
-
- filename = Tool.cleanfilename(filename,@commandline) # brrrr
- inppath = @commandline.option('inputpath')
- if inppath.empty? then
- inppath = '.'
- fullname = filename # avoid duplicate './'
- else
- fullname = File.join(inppath,filename)
- end
- if FileTest.file?(fullname) then
- handle_whatever(ghostscript,inkscape,magick,filename)
- else
- report("file #{fullname} does not exist")
- end
-
- end
-
- end
-
- def request
-
- # <exa:request>
- # <exa:application>
- # <exa:command>pstopdf</exa:command>
- # <exa:filename>E:/tmp/demo.ps</exa:filename>
- # </exa:application>
- # <exa:data>
- # <exa:variable label='gs:DoThumbnails'>false</exa:variable>
- # <exa:variable label='gs:ColorImageDepth'>-1</exa:variable>
- # </exa:data>
- # </exa:request>
-
- ghostscript = GhostScript.new(logger)
- magick = ImageMagick.new(logger)
- inkscape = InkScape.new(logger)
-
- dataname = @commandline.argument('first') || ''
- filename = @commandline.argument('second') || ''
-
- if dataname.empty? || ! FileTest.file?(dataname) then
- report('provide valid exa file')
- return
- else
- begin
- request = REXML::Document.new(File.new(dataname))
- rescue
- report('provide valid exa file (xml error)')
- return
- end
- end
- if filename.empty? then
- begin
- if filename = REXML::XPath.first(request.root,"exa:request/exa:application/exa:filename/text()") then
- filename = filename.to_s
- else
- report('no filename found in exa file')
- return
- end
- rescue
- filename = ''
- end
- end
- if filename.empty? then
- report('provide valid filename')
- return
- elsif ! FileTest.file?(filename) then
- report("invalid filename #{filename}")
- return
- end
-
- [ghostscript,inkscape,magick].each do |i|
- i.setvariable('inputfile',filename)
- end
-
- # set ghostscript variables
- REXML::XPath.each(request.root,"/exa:request/exa:data/exa:variable") do |v|
- begin
- if (key = v.attributes['label']) and (value = v.text.to_s) then
- case key
- when /gs[\:\.](var[\:\.])*(offset)/io then ghostscript.setoffset(value)
- when /gs[\:\.](var[\:\.])*(method)/io then ghostscript.setvariable('method',value)
- when /gs[\:\.](var[\:\.])*(.*)/io then ghostscript.setpsoption($2,value)
- end
- end
- rescue
- end
- end
-
- # no inkscape and magick variables (yet)
-
- handle_whatever(ghostscript,inkscape,magick,filename)
-
- end
-
- def watch
-
- ghostscript = GhostScript.new(logger)
- magick = ImageMagick.new(logger)
- inkscape = InkScape.new(logger)
-
- pathname = commandline.option('watch')
-
- unless pathname and not pathname.empty? then
- report('empty watchpath is not supported')
- exit
- end
-
- if pathname == '.' then
- report("watchpath #{pathname} is not supported")
- exit
- end
-
- if FileTest.directory?(pathname) then
- if Dir.chdir(pathname) then
- report("watching path #{pathname}")
- else
- report("unable to change to path #{pathname}")
- exit
- end
- else
- report("invalid path #{pathname}")
- exit
- end
-
- waiting = false
-
- loop do
-
- if waiting then
- report("waiting #{getvariable('delay')}")
- waiting = false
- sleep(getvariable('delay').to_i)
- end
-
- files = Dir.glob("**/*.*")
-
- if files and files.length > 0 then
-
- files.each do |fullname|
-
- next unless fullname
-
- if FileTest.directory?(fullname) then
- debug('skipping path', fullname)
- next
- end
-
- unless magick.supported(fullname) then
- debug('not supported', fullname)
- next
- end
-
- if (! FileTest.file?(fullname)) || (FileTest.size(fullname) < 100) then
- debug("skipping small crap file #{fullname}")
- next
- end
-
- debug("handling file #{fullname}")
-
- begin
- next unless File.rename(fullname,fullname) # access trick
- rescue
- next # being written
- end
-
- fullname = Tool.cleanfilename(fullname,@commandline)
-
- fullname.gsub!(/\\/io, '/')
-
- filename = File.basename(fullname)
- filepath = File.dirname(fullname)
-
- next if filename =~ /gstemp.*/io
-
- if filepath !~ /(result|done|raw|crop|bound|bitmap)/io then
- begin
- File.makedirs(filepath+'/raw')
- File.makedirs(filepath+'/bound')
- File.makedirs(filepath+'/crop')
- File.makedirs(filepath+'/bitmap')
- debug("creating prefered input paths on #{filepath}")
- rescue
- debug("creating input paths on #{filepath} failed")
- end
- end
-
- if filepath =~ /^(.*\/|)(done|result)$/io then
- debug("skipping file #{fullname}")
- else
- report("start processing file #{fullname}")
- if filepath =~ /^(.*\/*)(raw|crop|bound)$/io then
- donepath = $1 + 'done'
- resultpath = $1 + 'result'
- case $2
- when 'raw' then method = 1
- when 'bound' then method = 2
- when 'crop' then method = 3
- else method = 2
- end
- report("forcing method #{method}")
- else
- method = 2
- donepath = filepath + '/done'
- resultpath = filepath + '/result'
- report("default method #{method}")
- end
-
- begin
- File.makedirs(donepath)
- File.makedirs(resultpath)
- rescue
- report('result path creation fails')
- end
-
- if FileTest.directory?(donepath) && FileTest.directory?(resultpath) then
-
- resultname = resultpath + '/' + filename.sub(/\.[^\.]*$/,'') + '.pdf'
-
- @commandline.setoption('inputpath', filepath)
- @commandline.setoption('outputpath', resultpath)
- @commandline.setoption('method', method)
-
- if ghostscript.psfile?(fullname) then
- handle_ghostscript(ghostscript,filename)
- else
- handle_magick(magick,filename)
- end
-
- sleep(1) # calm down
-
- if FileTest.file?(fullname) then
- begin
- File.copy(fullname,donepath + '/' + filename)
- File.delete(fullname)
- rescue
- report('cleanup fails')
- end
- end
-
- end
-
- end
-
- end
-
- end
-
- waiting = true
- end
-
- end
-
- private
-
- def handle_whatever(ghostscript,inkscape,magick,filename)
- if ghostscript.psfile?(filename) then
- # report("processing ps file #{filename}")
- ghostscript.setvariable('pipe',false) if @commandline.option('nopipe')
- # ghostscript.setvariable('pipe',not @commandline.option('nopipe'))
- ghostscript.setvariable('colormodel',@commandline.option('colormodel'))
- ghostscript.setvariable('offset',@commandline.option('offset'))
- handle_ghostscript(ghostscript,filename)
- elsif ghostscript.pdffile?(filename) && ghostscript.pdfmethod?(@commandline.option('method')) then
- # report("processing pdf file #{filename}")
- handle_ghostscript(ghostscript,filename)
- elsif inkscape.supported?(filename) then
- # report("processing non ps/pdf file #{filename}")
- handle_inkscape(inkscape,filename)
- elsif magick.supported?(filename) then
- # report("processing non ps/pdf file #{filename}")
- handle_magick(magick,filename)
- else
- report("option not supported for #{filename}")
- end
- end
-
- def handle_magick(magick,filename)
-
- report("converting non-ps file #{filename} into pdf")
-
- inppath = @commandline.option('inputpath')
- outpath = @commandline.option('outputpath')
-
- inppath = inppath + '/' if not inppath.empty?
- outpath = outpath + '/' if not outpath.empty?
-
- prefix = @commandline.option('prefix')
- suffix = @commandline.option('suffix')
-
- inpfilename = "#{inppath}#{filename}"
- outfilename = "#{outpath}#{prefix}#{filename.sub(/\.([^\.]*?)$/, '')}#{suffix}.pdf"
-
- magick.setvariable('inputfile' , inpfilename)
- magick.setvariable('outputfile', outfilename)
-
- magick.autoconvert
-
- end
-
- def handle_inkscape(inkscape,filename)
-
- report("converting svg(z) file #{filename} into pdf")
-
- inppath = @commandline.option('inputpath')
- outpath = @commandline.option('outputpath')
-
- inppath = inppath + '/' if not inppath.empty?
- outpath = outpath + '/' if not outpath.empty?
-
- prefix = @commandline.option('prefix')
- suffix = @commandline.option('suffix')
-
- inpfilename = "#{inppath}#{filename}"
- outfilename = "#{outpath}#{prefix}#{filename.sub(/\.([^\.]*?)$/, '')}#{suffix}.pdf"
-
- inkscape.setvariable('inputfile' , inpfilename)
- inkscape.setvariable('outputfile', outfilename)
-
- if @commandline.option('verbose') || @commandline.option('debug') then
- logname = filename.gsub(/\.[^\.]*?$/, '.log')
- report("log info saved in #{logname}")
- inkscape.convert(logname) # logname ook doorgeven
- else
- inkscape.convert
- end
-
- end
-
- def handle_ghostscript(ghostscript,filename)
-
- ghostscript.reset
-
- method = ghostscript.method(@commandline.option('method'))
- force = ghostscript.method(@commandline.option('force'))
-
- ghostscript.setvariable('method', method)
- ghostscript.setvariable('force', force)
-
- # report("conversion method #{method}")
-
- inppath = @commandline.option('inputpath')
- outpath = @commandline.option('outputpath')
-
- inppath = inppath + '/' if not inppath.empty?
- outpath = outpath + '/' if not outpath.empty?
-
- prefix = @commandline.option('prefix')
- suffix = @commandline.option('suffix')
-
- ok = false
-
- if ghostscript.pdfmethod?(method) then
-
- report("converting pdf file #{filename} into pdf")
-
- if prefix.empty? && suffix.empty? && inppath.empty? && outpath.empty? then
- prefix = ghostscript.pdfprefix(method)
- end
-
- if ghostscript.pdffile?(filename) then
-
- filename = filename.sub(/\.pdf$/, '')
-
- inpfilename = "#{inppath}#{filename}.pdf"
- outfilename = "#{outpath}#{prefix}#{filename}#{suffix}.pdf"
-
- ghostscript.setvariable('inputfile' ,inpfilename)
- ghostscript.setvariable('outputfile',outfilename)
-
- if FileTest.file?(inpfilename) then
- ok = ghostscript.convert
- else
- report("no file found #{filename}")
- end
-
- else
- report("no pdf file #{filename}")
- end
-
- elsif ghostscript.psfile?(filename) then
-
- if filename =~ /(.*)\.([^\.]*?)$/io then
- filename, filesuffix = $1, $2
- else
- filesuffix = 'eps'
- end
-
- report("converting #{filesuffix} (ps) into pdf")
-
- inpfilename = "#{inppath}#{filename}.#{filesuffix}"
- outfilename = "#{outpath}#{prefix}#{filename}#{suffix}.pdf"
-
- ghostscript.setvariable('inputfile' , inpfilename)
- ghostscript.setvariable('outputfile', outfilename)
-
- if FileTest.file?(inpfilename) then
- ok = ghostscript.convert
- if ! ok && FileTest.file?(outfilename) then
- begin
- File.delete(outfilename)
- rescue
- end
- end
- else
- report("no file with name #{filename} found")
- end
-
- else
- report('file must be of type eps/ps/ai/pdf')
- end
-
- return ok
-
- end
-
-end
-
-# ook pdf -> pdf onder optie 0, andere kleurruimte
-
-logger = Logger.new(banner.shift)
-commandline = CommandLine.new
-
-commandline.registerflag('debug')
-commandline.registerflag('verbose')
-commandline.registerflag('nopipe')
-
-commandline.registervalue('method',2)
-commandline.registervalue('offset',0)
-
-commandline.registervalue('prefix')
-commandline.registervalue('suffix')
-
-commandline.registervalue('inputpath')
-commandline.registervalue('outputpath')
-
-commandline.registerflag('watch')
-commandline.registerflag('force')
-commandline.registerflag('recurse')
-
-commandline.registervalue('delay',2)
-
-commandline.registervalue('colormodel','cmyk')
-commandline.registervalue('pattern','')
-
-commandline.registeraction('help')
-commandline.registeraction('version')
-
-commandline.registeraction('convert', 'convert ps into pdf')
-commandline.registeraction('request', 'handles exa request file')
-commandline.registeraction('watch', 'watch folders for conversions (untested)')
-
-commandline.expand
-
-logger.verbose if (commandline.option('verbose') || commandline.option('debug'))
-
-Commands.new(commandline,logger,banner).send(commandline.action || 'main')
diff --git a/Master/texmf-dist/scripts/context/ruby/rlxtools.rb b/Master/texmf-dist/scripts/context/ruby/rlxtools.rb
deleted file mode 100644
index 6a5c5ca2098..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/rlxtools.rb
+++ /dev/null
@@ -1,368 +0,0 @@
-#!/usr/bin/env ruby
-
-# program : rlxtools
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2004-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-banner = ['RlxTools', 'version 1.0.1', '2004/2005', 'PRAGMA ADE/POD']
-
-$: << File.expand_path(File.dirname($0)) ; $: << File.join($:.last,'lib') ; $:.uniq!
-
-require 'base/switch'
-require 'base/logger'
-require 'base/system'
-require 'base/kpse'
-
-require 'fileutils'
-# require 'ftools'
-require 'rexml/document'
-
-class Commands
-
- include CommandBase
-
- # <?xml version='1.0 standalone='yes'?>
- # <rl:manipulators>
- # <rl:manipulator name='lowres' suffix='pdf'>
- # <rl:step>
- # texmfstart
- # --verbose
- # --iftouched=<rl:value name='path'/>/<rl:value name='file'/>,<rl:value name='path'/>/<rl:value name='prefix'/><rl:value name='file'/>
- # pstopdf
- # --method=5
- # --inputpath=<rl:value name='path'/>
- # --outputpath=<rl:value name='path'/>/<rl:value name='prefix'/>
- # <rl:value name='file'/>
- # </rl:step>
- # </rl:manipulator>
- # </rl:manipulators>
- #
- # <?xml version='1.0' standalone='yes'?>
- # <rl:library>
- # <rl:usage>
- # <rl:type>figure</rl:type>
- # <rl:state>found</rl:state>
- # <rl:file>cow.pdf</rl:file>
- # <rl:suffix>pdf</rl:suffix>
- # <rl:path>.</rl:path>
- # <rl:conversion>lowres</rl:conversion>
- # <rl:prefix>lowres/</rl:prefix>
- # <rl:width>276.03125pt</rl:width>
- # <rl:height>200.75pt</rl:height>
- # </rl:usage>
- # </r:library>
-
- def manipulate
-
- procname = @commandline.argument('first') || ''
- filename = @commandline.argument('second') || ''
-
- procname = Kpse.found(procname)
-
- if procname.empty? || ! FileTest.file?(procname) then
- report('provide valid manipulator file')
- elsif filename.empty? || ! FileTest.file?(filename) then
- report('provide valid resource log file')
- else
- begin
- data = REXML::Document.new(File.new(filename))
- rescue
- report('provide valid resource log file (xml error)')
- return
- end
- begin
- proc = REXML::Document.new(File.new(procname))
- rescue
- report('provide valid manipulator file (xml error)')
- return
- end
- report("manipulator file: #{procname}")
- report("resourcelog file: #{filename}")
- begin
- nofrecords, nofdone = 0, 0
- REXML::XPath.each(data.root,"/rl:library/rl:usage") do |usage|
- nofrecords += 1
- variables = Hash.new
- usage.elements.each do |e|
- variables[e.name] = e.text.to_s
- end
- report("processing record #{nofrecords} (#{variables['file'] || 'noname'}: #{variables.size} entries)")
- if conversion = variables['conversion'] then
- report("testing for conversion #{conversion}")
- if suffix = variables['suffix'] then
- suffix.downcase!
- if ! suffix.empty? && variables['file'] && variables['file'] !~ /\.([a-z]+)$/i then
- variables['file'] += ".#{suffix}"
- end
- if file = variables['file'] then
- report("conversion #{conversion} for suffix #{suffix} for file #{file}")
- else
- report("conversion #{conversion} for suffix #{suffix}")
- end
- pattern = "@name='#{conversion}' and @suffix='#{suffix}'"
- if steps = REXML::XPath.first(proc.root,"/rl:manipulators/rl:manipulator[#{pattern}]") then
- localsteps = steps.deep_clone
- ['rl:old','rl:new'].each do |tag|
- REXML::XPath.each(localsteps,tag) do |extras|
- REXML::XPath.each(extras,"rl:value") do |value|
- if name = value.attributes['name'] then
- substitute(value,variables[name.to_s] || '')
- end
- end
- end
- end
- old = REXML::XPath.first(localsteps,"rl:old")
- new = REXML::XPath.first(localsteps,"rl:new")
- if old && new then
- old, new = justtext(old.to_s), justtext(new.to_s)
- variables['old'], variables['new'] = old, new
- begin
- [old,new].each do |d|
- File.makedirs(File.dirname(d))
- end
- rescue
- report("error during path creation")
- end
- report("old file #{old}")
- report("new file #{new}")
- level = if File.needsupdate(old,new) then 2 else 0 end
- else
- level = 1
- end
- if level>0 then
- REXML::XPath.each(localsteps,"rl:step") do |command|
- REXML::XPath.each(command,"rl:old") do |value|
- replace(value,old)
- end
- REXML::XPath.each(command,"rl:new") do |value|
- replace(value,new)
- end
- REXML::XPath.each(command,"rl:value") do |value|
- if name = value.attributes['name'] then
- substitute(value,variables[name.to_s])
- end
- end
- str = justtext(command.to_s)
- # str.gsub!(/(\.\/)+/io, '')
- report("command #{str}")
- System.run(str) unless @commandline.option('test')
- report("synchronizing #{old} and #{new}")
- File.syncmtimes(old,new) if level > 1
- nofdone += 1
- end
- else
- report("no need for a manipulation")
- end
- else
- report("no manipulator found")
- end
- else
- report("no suffix specified")
- end
- else
- report("no conversion needed")
- end
- end
- if nofdone > 0 then
- jobname = filename.gsub(/\.(.*?)$/,'') # not 'tuo' here
- tuoname = jobname + '.tuo'
- if FileTest.file?(tuoname) && (f = File.open(tuoname,'a')) then
- f.puts("%\n% number of rlx manipulations: #{nofdone}\n")
- f.close
- end
- end
- rescue
- report("error in manipulating files: #{$!}")
- end
- begin
- logname = "#{filename}.log"
- File.delete(logname) if FileTest.file?(logname)
- File.copy(filename,logname)
- rescue
- end
- end
-
- end
-
- private
-
- def justtext(str)
- str = str.to_s
- str.gsub!(/<[^>]*?>/o, '')
- str.gsub!(/\s+/o, ' ')
- str.gsub!(/&lt;/o, '<')
- str.gsub!(/&gt;/o, '>')
- str.gsub!(/&amp;/o, '&')
- str.gsub!(/&quot;/o, '"')
- str.gsub!(/[\/\\]+/o, '/')
- return str.strip
- end
-
- def substitute(value,str='')
- if str then
- begin
- if value.attributes.key?('method') then
- str = filtered(str.to_s,value.attributes['method'].to_s)
- end
- if str.empty? && value.attributes.key?('default') then
- str = value.attributes['default'].to_s
- end
- value.insert_after(value,REXML::Text.new(str.to_s))
- rescue Exception
- end
- end
- end
-
- def replace(value,str)
- if str then
- begin
- value.insert_after(value,REXML::Text.new(str.to_s))
- rescue Exception
- end
- end
- end
-
- def filtered(str,method)
-
- str = str.to_s # to be sure
- case method
- when 'name' then # no path, no suffix
- case str
- when /^.*[\\\/](.+?)\..*?$/o then $1
- when /^.*[\\\/](.+?)$/o then $1
- when /^(.*)\..*?$/o then $1
- else str
- end
- when 'path' then if str =~ /^(.+)([\\\/])(.*?)$/o then $1 else '' end
- when 'suffix' then if str =~ /^.*\.(.*?)$/o then $1 else '' end
- when 'nosuffix' then if str =~ /^(.*)\..*?$/o then $1 else str end
- when 'nopath' then if str =~ /^.*[\\\/](.*?)$/o then $1 else str end
- else str
- end
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- @@xmlbanner = "<?xml version='1.0' standalone='yes'?>"
-
- def identify(resultfile='rlxtools.rli')
- if @commandline.option('collect') then
- begin
- File.open(resultfile,'w') do |f|
- f << "#{@@xmlbanner}\n"
- f << "<rl:identification>\n"
- @commandline.arguments.each do |filename|
- if state = do_identify(filename) then
- report("#{filename} is identified")
- f << state
- else
- report("unable to identify #{filename}")
- end
- end
- f << "</rl:identification>\n"
- report("result saved in #{resultfile}")
- end
- rescue
- report("error in writing result")
- end
- else
- @commandline.arguments.each do |filename|
- if state = do_identify(filename) then
- begin
- File.open(filename+'.rli','w') do |f|
- f << "#{@@xmlbanner}\n"
- f << state
- end
- rescue
- report("error in identifying #{filename}")
- else
- report("#{filename} is identified")
- end
- else
- report("unable to identify #{filename}")
- end
- end
- end
- end
-
- private
-
- def do_identify(filename,centimeters=false)
- begin
- str = nil
- if FileTest.file?(filename) then
- # todo: use pdfinto for pdf files, identify is bugged
- if centimeters then
- result = `identify -units PixelsPerCentimeter -format \"x=%x,y=%y,w=%w,h=%h,b=%b\" #{filename}`.chomp.split(',')
- else
- result = `identify -units PixelsPerInch -format \"x=%x,y=%y,w=%w,h=%h,b=%b\" #{filename}`.chomp.split(',')
- end
- tags = Hash.new
- result.each do |r|
- if rr = r.split("=") then
- tags[rr[0]] = rr[1]
- end
- end
- size = (tags['b']||0).to_i
- width = unified(tags['w']||0,tags['x']||'1')
- height = unified(tags['h']||0,tags['y']||'1')
- if size > 0 then
- str = ''
- str << "<rl:identify name='#{File.basename(filename)}'>\n"
- str << " <rl:size>#{size}</rl:size>\n"
- str << " <rl:path>#{File.dirname(filename).sub(/\\/o,'/')}</rl:path>\n"
- str << " <rl:width>#{width}</rl:width>\n"
- str << " <rl:height>#{height}</rl:height>\n"
- str << "</rl:identify>\n"
- end
- else
- str = nil
- end
- rescue
- str = nil
- end
- return str
- end
-
- def unified(dim,res)
- case res
- when /([\d\.]+)\s*PixelsPerInch/io then
- sprintf("%.4fin",dim.to_f/$1.to_f)
- when /([\d\.]+)\s*PixelsPerCentimeter/io then
- sprintf("%.4fcm",dim.to_f/$1.to_f)
- when /([\d\.]+)\s*PixelsPerMillimeter/io then
- sprintf("%.4fmm",dim.to_f/$1.to_f)
- when /([\d\.]+)\s*PixelsPerPoint/io then
- sprintf("%.4fbp",dim.to_f/$1.to_f)
- else
- sprintf("%.4fbp",dim.to_f)
- end
- end
-
-end
-
-logger = Logger.new(banner.shift)
-commandline = CommandLine.new
-
-commandline.registeraction('manipulate', '[--test] manipulatorfile resourselog')
-commandline.registeraction('identify' , '[--collect] filename')
-
-commandline.registeraction('help')
-commandline.registeraction('version')
-
-commandline.registerflag('test')
-commandline.registerflag('collect')
-
-commandline.expand
-
-Commands.new(commandline,logger,banner).send(commandline.action || 'help')
diff --git a/Master/texmf-dist/scripts/context/ruby/rscortool.rb b/Master/texmf-dist/scripts/context/ruby/rscortool.rb
deleted file mode 100644
index c656fed8547..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/rscortool.rb
+++ /dev/null
@@ -1,63 +0,0 @@
-# program : rscortool
-# copyright : PRAGMA Publishing On Demand
-# version : 1.00 - 2002
-# author : Hans Hagen
-#
-# project : eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-pod.com / www.pragma-ade.com
-
-require 'rexml/document.rb'
-
-class Array
-
- def downcase
- self.collect { |l| l.to_s.downcase }
- end
-
-end
-
-class SortedXML
-
- def initialize (filename)
- return nil if not filename or filename.empty? or not test(?e,filename)
- @data = REXML::Document.new(File.new(filename),
- {:ignore_whitespace_nodes => :all,
- :compress_whitespace => :all})
- end
-
- def save (filename)
- # filename += '.xml' unless filename.match(/\..*?$/)
- filename += '.xml' unless filename =~ /\..*?$/
- if not filename.empty? and f = open(filename,'w')
- @data.write(f,0)
- f.close
- end
- end
-
- def sort
- keys = REXML::XPath.match(@data.root,"/contacts/contact/@label")
- return unless keys
- keys = keys.downcase
- records = @data.elements.to_a("/contacts/contact")
- @data.elements.delete_all("/contacts/contact")
- keys = keys.collect do |l| # prepare numbers
- l.gsub(/(\d+)/) do |d| sprintf('%05d', d) end
- end
- keys.sort.each do |s|
- @data.root.add_element(records[keys.index(s)])
- end
- end
-
-end
-
-def sortfile (filename)
- c = SortedXML.new(filename)
- c.sort
- c.save('test.xml')
-end
-
-exit if ARGV[0] == nil or ARGV[0].empty?
-
-sortfile(ARGV[0])
diff --git a/Master/texmf-dist/scripts/context/ruby/rsfiltool.rb b/Master/texmf-dist/scripts/context/ruby/rsfiltool.rb
deleted file mode 100644
index 6d7c7aba0a5..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/rsfiltool.rb
+++ /dev/null
@@ -1,341 +0,0 @@
-# program : rsfiltool
-# copyright : PRAGMA Publishing On Demand
-# version : 1.01 - 2002
-# author : Hans Hagen
-#
-# project : eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-pod.com / www.pragma-ade.com
-
-unless defined? ownpath
- ownpath = $0.sub(/[\\\/]\w*?\.rb/i,'')
- $: << ownpath
-end
-
-# --name=a,b,c.xml wordt names [a.xml, b.xml, c.xml]
-# --path=x/y/z/a,b,c.xml wordt [x/y/z/a.xml, x/y/z/b.xml, x/y/z/c.xml]
-
-# todo : split session stuff from xmpl/base into an xmpl/session module and "include xmpl/session" into base and here and ...
-
-require 'fileutils'
-# require 'ftools'
-require 'xmpl/base'
-require 'xmpl/switch'
-require 'xmpl/request'
-
-session = Example.new('rsfiltool', '1.01', 'PRAGMA POD')
-
-filterprefix = 'rsfil-'
-
-commandline = CommandLine.new
-
-commandline.registerflag('submit')
-commandline.registerflag('fetch')
-commandline.registerflag('report')
-#commandline.registerflag('split')
-commandline.registerflag('stamp')
-commandline.registerflag('silent')
-commandline.registerflag('request')
-commandline.registerflag('nobackup')
-
-commandline.registervalue('filter')
-
-commandline.registervalue('root')
-commandline.registervalue('path')
-commandline.registervalue('name')
-
-commandline.expand
-
-session.set('log.silent',true) if commandline.option('silent')
-
-session.inherit(commandline)
-
-session.identify
-
-# session.exit unless session.loadenvironment
-
-def prepare (session)
-
- # Normally the system provides the file, but a user can provide the rest; in
- # order to prevent problems with keying in names, we force lowercase names.
-
- session.set('option.file',session.get('argument.first')) if session.get('option.file').empty?
-
- root = session.get('option.root').downcase
- path = session.get('option.path').downcase
- name = session.get('option.name').downcase
- file = session.get('option.file').downcase
-
- session.error('provide file') if file.empty?
- session.error('provide root') if root.empty?
-
- filter = session.get('option.filter').downcase
- trash = session.get('option.trash').downcase
-
- trash = '' unless FileTest.directory?(trash)
-
- if not filter.empty? then
- begin
- require filter
- rescue Exception
- begin
- require filterprefix + filter
- rescue Exception
- session.error('invalid filter')
- end
- end
- begin
- if RSFIL::valid?(file) then
- split = RSFIL::split(file,name)
- path = if split[0].downcase then split[0] else '' end
- file = if split[1].downcase then split[1] else '' end
- name = if split[2].downcase then split[2] else '' end
- session.report('split result',split.inspect)
- session.error('unable to split off path') if path.empty?
- session.error('unable to split off file') if file.empty?
- session.error('unable to split off name') if name.empty?
- session.set('option.path',path) if path
- session.set('option.file',file) if file
- session.set('option.name',name) if name
- else
- session.error('invalid filename', file)
- unless trash.empty? then
- File.copy(file,trash + '/' + file)
- end
- end
- rescue
- session.error('unable to split',file,'with filter',filter)
- end
- end
-
- session.error('provide path') if path.empty?
-
- session.error('invalid root') unless test(?d,root)
-
- exit if session.error?
-
- session.set('fb.filename',file)
-
- path.gsub!(/\\/o, '/')
- path.gsub!(/\s/o, '')
-
- path = root + '/' + path
-
- # multiple paths
-
- if path =~ /^(.*)\/(.*?)$/o then
- prepath = $1
- postpath = $2
- paths = postpath.split(/\,/)
- paths.collect! do |p|
- prepath + '/' + p
- end
- else
- paths = Array.new
- paths.push(path)
- end
-
- paths.collect! do |p|
- p.gsub(/[^a-zA-Z0-9\s\-\_\/\.\:]/o, '-')
- end
-
- file.gsub!(/\\/o, '/')
- file.gsub!(/[^a-zA-Z0-9\s\-\_\/\.\:]/o, '-')
-
-# if session.get('option.split')
-# if file =~ /(.*)\.(.*?)$/o
-# path = path + '/' + $1
-# else
-# session.error('nothing to split in filename')
-# end
-# end
-
- paths.each do |p|
- begin
- session.report('creating path', p)
- File.makedirs(p)
- rescue
- session.error('unable to create path', p)
- end
- end
-
- name.gsub!(/\s+/,'')
-
- # can be a,b,c.exa.saved => a.exa.saved,b.exa.saved,c.exa.saved
-
- if name =~ /(.*?)\.(.*)$/
- name = $1
- suffix = $2
- names = name.split(/\,/)
- names.collect! do |n|
- n + '.' + suffix
- end
- name = names.join(',')
- else
- names = name.split(/\,/)
- end
-
- session.set('fb.path',path)
- session.set('fb.paths',paths)
- session.set('fb.name',name)
- session.set('fb.names',names)
-
-end
-
-def thefullname(path,file,name='')
-
- filename = file.gsub(/.*?\//, '')
-
- if name.empty?
- path + '/' + filename
- else
- unless name =~ /\..+$/o # unless name.match(/\..+$/o)
- if filename =~ /(\..+)$/o # if file.match(/(\..+)$/o)
- name = name + $1
- end
- end
- path + '/' + name
- end
-
-end
-
-def submitfile (session)
-
- filename = session.get('fb.filename')
- paths = session.get('fb.paths')
- names = session.get('fb.names')
-
- paths.each do |path|
- session.report('submitting path',path)
- names.each do |name|
- session.report('submitting file',filename,'to',name)
- submit(session,path,filename,name)
- end
- end
-
-end
-
-def submitlist (session)
-
- requestname = session.get('fb.filename')
- paths = session.get('fb.paths')
-
- if test(?e,requestname)
- session.report('loading request file', requestname)
- if request = ExaRequest.new(requestname)
- filelist = request.files
- if filelist && (filelist.size > 0)
- filelist.each do |filename|
- paths.each do |path|
- session.report('submitting file from list', filename)
- submit(session,path,filename,request.naturalname(filename))
- end
- end
- else
- session.warning('no filelist in', requestname)
- end
- else
- session.warning('unable to load', requestname)
- end
- else
- session.warning('no file', requestname)
- end
-
-end
-
-def submit (session, path, filename, newname)
-
- fullname = thefullname(path,newname)
-
- unless test(?e,filename)
- session.warning('no file to submit', filename)
- return
- end
-
- begin
- File.copy(fullname,fullname+'.old') if ! session.get('nobackup') && test(?e,fullname)
- if test(?e,filename)
- File.copy(filename,fullname)
- session.report('submit', filename, 'in', fullname)
- if session.get('option.stamp')
- f = open(fullname+'.tim','w')
- f.puts(Time.now.gmtime.strftime("%a %b %d %H:%M:%S %Y"))
- f.close
- end
- else
- session.error('unable to locate', filename)
- end
- rescue
- session.error('unable to move', filename, 'to', fullname)
- end
-
-end
-
-def fetch (session)
-
- filename = session.get('fb.filename')
- paths = session.get('fb.paths')
- name = session.get('fb.name')
-
- begin
- File.copy(filename,filename+'.old') if ! session.get('nobackup') && test(?e,filename)
- paths.each do |path|
- # fullname = thefullname(path,request.naturalname(filename))
- # fullname = thefullname(path,filename)
- fullname = thefullname(path,name)
- if test(?e,fullname)
- File.copy(fullname,filename)
- session.report('fetch', filename, 'from', fullname)
- return
- else
- session.report('file',fullname, 'is not present')
- end
- end
- rescue
- session.error('unable to fetch file from path')
- end
- session.error('no file',filename, 'fetched') unless test(?e,filename)
-
-end
-
-def report (session)
-
- filename = session.get('fb.filename')
- paths = session.get('fb.paths')
-
- paths.each do |path|
- fullname = thefullname(path,request.naturalname(filename))
- if test(?e,fullname)
- begin
- session.report('file', fullname)
- session.report('size', test(?s,fullname))
- if test(?e,fullname+'.tim')
- str = IO.readlines(fullname+'.tim')
- # str = IO.read(fullname+'.tim')
- session.report('time', str)
- end
- rescue
- session.error('unable to report about', fullname)
- end
- end
- end
-
-end
-
-if session.get('option.submit')
- prepare(session)
- if session.get('option.request')
- submitlist(session)
- else
- submitfile(session)
- end
-elsif session.get('option.fetch')
- prepare(session)
- fetch(session)
-elsif session.get('option.report')
- prepare(session)
- report(session)
-else
- session.report('provide action')
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/rslb/base.rb b/Master/texmf-dist/scripts/context/ruby/rslb/base.rb
deleted file mode 100644
index 66ce3a19e71..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/rslb/base.rb
+++ /dev/null
@@ -1,270 +0,0 @@
-# hans hagen, pragma-ade, hasselt nl
-# experimental code, don't touch it
-
-require 'rexml/document.rb'
-
-class Array
-
- def downcase
- self.collect do |l|
- l.to_s.downcase
- end
- end
-
-end
-
-class Resource
-
- @@rslburl = 'http://www.pragma-ade.com/rng/rslb.rng'
- @@rslbns = 'rl'
- @@rslbtmp = 'rslbtool-tmp.xml'
-
- def initialize (filename='',namespace=@@rslbns)
- @ns = if namespace then @@rslbns + ':' else '' end
- set_filename(filename)
- @library = REXML::Document.new(skeleton,
- {:ignore_whitespace_nodes => :all,
- :compress_whitespace => :all})
- @lastindex = 0
- @texexec = 'texexec'
- @downcaselabels = true
- @downcasefilenames = true
- end
-
- def keeplabelcase
- @downcaselabels = false
- end
-
- def keepfilenamecase
- @downcasefilenames = false
- end
-
- def outer_skeleton (str)
- tmp = if @ns.empty? then '' else " xmlns:#{@ns.sub(':','')}='#{@@rslburl}'" end
- "<?xml version='1.0'?>\n" + "<#{@ns}library#{tmp}>\n" + str + "\n</#{@ns}library>"
- end
-
- def skeleton
- outer_skeleton("<#{@ns}description>" +
- "<#{@ns}organization>unknown</#{@ns}organization>" +
- "<#{@ns}project>unknown</#{@ns}project>" +
- "<#{@ns}product>unknown</#{@ns}product>" +
- "<#{@ns}comment>unknown</#{@ns}comment>" +
- "</#{@ns}description>")
- end
-
- def set_filename (filename)
- @filename = if filename.empty? then 'unknown' else filename end
- @fullname = @filename
- @filename = File.basename(@filename).sub(/\..*$/,'')
- end
-
- def set_texexec (filename)
- print "setting texexec binary to: #{filename}\n"
- @texexec = filename
- end
-
- def load (filename='')
- set_filename(filename)
- if not filename.empty? and FileTest.file?(filename) # todo: test op valide fig base
- @library = REXML::Document.new(File.new(filename),
- {:ignore_whitespace_nodes => :all,
- :compress_whitespace => :all})
- unless @library.root.prefix.empty?
- @ns = @library.root.prefix + ':'
- end
- else
- initialize(filename,!@ns.empty?)
- end
- end
-
- def save (filename)
- filename += '.xml' unless filename =~ /\..*?$/
- if not filename.empty? and f = open(filename,'w')
- @library.write(f,0)
- f.close
- end
- end
-
- def figure_labels
- REXML::XPath.match(@library.root,"/#{@ns}library/#{@ns}figure/#{@ns}label/text()")
- end
-
- def figure_records
- @library.elements.to_a("/#{@ns}library/#{@ns}figure")
- end
-
- def figure_files
- REXML::XPath.match(@library.root,"/#{@ns}library/#{@ns}figure/#{@ns}file/text()")
- end
-
- def delete_figure (label='')
- return if label.empty?
- labels = figure_labels
- labels.each_index do |i|
- if labels[i].to_s.downcase == label.downcase
- @library.elements.delete_all("/#{@ns}library/#{@ns}figure[#{i+1}]")
- end
- end
- end
-
- def add_figure (file='',label='',prefix='')
- return if file.empty? or file.match(/^#{@filename}\..*$/i)
- labels = figure_labels
- prefix = @filename if prefix.empty?
- if label.empty?
- i = @lastindex
- loop do
- i += 1
- label = prefix + ' ' + i.to_s
- break unless labels.include?(label)
- end
- else
- delete_figure(label) unless label.empty?
- end
- e = REXML::Element.new("#{@ns}figure")
- l = REXML::Element.new("#{@ns}label")
- f = REXML::Element.new("#{@ns}file")
- l.text, f.text = label, file
- e.add_element(l)
- e.add_element(f)
- @library.root.add_element(e)
- end
-
- def add_figures (list='',prefix='')
- if @downcasefilenames then
- files = figure_files.downcase
- [list].flatten.downcase.each do |f|
- next unless FileTest.file?(f)
- add_figure(f,'',prefix) unless files.include?(f)
- end
- else
- files = figure_files
- [list].flatten.each do |f|
- next unless FileTest.file?(f)
- add_figure(f,'',prefix) unless files.include?(f)
- end
- end
- end
-
- def delete_figures (list='')
- [list].flatten.downcase.each do |l|
- delete_figure(l)
- end
- end
-
- def sort_figures
- if @downcaselabels then
- labels = figure_labels.downcase
- else
- labels = figure_labels
- end
- return unless labels
- figures = figure_records
- @library.elements.delete_all("/#{@ns}library/#{@ns}figure")
- labels = labels.collect do |l| # prepare numbers
- l.gsub(/(\d+)/) do |d| sprintf('%05d', d) end
- end
- labels.sort.each do |s|
- @library.root.add_element(figures[labels.index(s)])
- end
- end
-
- def purge_figures
- REXML::XPath.each(@library.root,"/#{@ns}library/#{@ns}figure") do |e|
- filename = REXML::XPath.match(e,"#{@ns}file/text()").to_s
- e.parent.delete(e) unless FileTest.file?(filename)
- end
- end
-
- def run_command(command)
- print "calling #{command}\n"
- print "\n"
- begin
- system(command)
- rescue
- # sorry again
- end
- print "\n"
- end
-
- def create_dummies(process=false,result='',zipalso='')
- result = @filename if result.empty?
- list = REXML::XPath.match(@library.root,"/#{@ns}library/#{@ns}usage")
- begin
- File.delete(result+'.pdf')
- rescue
- # no way
- end
- return unless list && list.length>0
- done = Array.new
- list.each do |e|
- t = REXML::XPath.match(e,"#{@ns}type/text()")
- s = REXML::XPath.match(e,"#{@ns}state/text()")
- if t && (t.to_s == 'figure') && s && (s.to_s == 'missing')
- begin
- f = REXML::XPath.match(e,"#{@ns}file/text()").to_s
- if done.index(f)
- print "skipping dummy figure: " + f + "\n"
- elsif f =~ /\s/o
- print "skipping crappy fname: " + f + "\n"
- elsif f == 'dummy'
- print "skipping dummy figure: " + f + "\n"
- else
- print "creating dummy figure: " + f + "\n"
- if process && (x = open(@@rslbtmp,'w'))
- x.puts(outer_skeleton(e.to_s))
- x.close
- run_command ("#{@texexec} --pdf --once --batch --silent --random --use=res-10 --xml --result=#{f} #{@@rslbtmp}")
- end
- done.push(f+'.pdf')
- begin
- File.delete(@@rslbtmp)
- rescue
- # sorry once more
- end
- end
- rescue
- # sorry, skip 'm
- end
- end
- end
- if process && (done.length>0)
- begin
- File.delete(result + '.zip')
- rescue
- # ok
- end
- run_command("zip #{result+'.zip'} #{@fullname}")
- unless zipalso.empty?
- begin
- zipalso.split(',').each do |name|
- run_command("zip #{result+'.zip'} #{name}")
- end
- end
- end
- done.each do |name|
- run_command("zip #{result+'.zip'} #{name}")
- end
- run_command("#{@texexec} --pdf --batch --silent --use=res-11 --xml --result=#{result} #{@fullname}")
- done.each do |name|
- begin
- File.delete(name)
- rescue
- # sorry
- end
- end
- end
- end
-
-end
-
-# reslib = Resource.new
-# reslib.load('f.xml') # reslib.load('figbase.xml')
-# reslib.delete_figure('figbase 5')
-# reslib.delete_figure('figbase 5')
-# reslib.add_figure('a.pdf')
-# reslib.add_figure('b.pdf','something')
-# reslib.add_figure('c.pdf')
-# reslib.add_files('x.pdf')
-# reslib.save('figbase.tmp')
diff --git a/Master/texmf-dist/scripts/context/ruby/rslibtool.rb b/Master/texmf-dist/scripts/context/ruby/rslibtool.rb
deleted file mode 100644
index 7ae5efb647e..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/rslibtool.rb
+++ /dev/null
@@ -1,114 +0,0 @@
-# program : rslibtool
-# copyright : PRAGMA Publishing On Demand
-# version : 1.00 - 2002
-# author : Hans Hagen
-#
-# project : eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-pod.com / www.pragma-ade.com
-
-# --add --base=filename --path=directory pattern
-# --remove --base=filename --path=directory label
-# --sort --base=filename --path=directory
-# --purge --base=filename --path=directory
-# --dummy --base=filename
-# --namespace
-
-# rewrite
-
-unless defined? ownpath
- ownpath = $0.sub(/[\\\/]\w*?\.rb/i,'')
- $: << ownpath
-end
-
-require 'rslb/base'
-require 'xmpl/base'
-require 'xmpl/switch'
-
-session = Example.new('rslbtool', '1.0', 'PRAGMA POD')
-
-session.identify
-
-commandline = CommandLine.new
-
-commandline.registerflag('add')
-commandline.registerflag('remove')
-commandline.registerflag('delete')
-commandline.registerflag('sort')
-commandline.registerflag('purge')
-commandline.registerflag('dummy')
-commandline.registerflag('process')
-commandline.registerflag('namespace')
-
-commandline.registervalue('prefix')
-commandline.registervalue('base')
-commandline.registervalue('path')
-commandline.registervalue('result')
-commandline.registervalue('texexec')
-commandline.registervalue('zipalso')
-
-commandline.expand
-
-session.inherit(commandline)
-
-base = session.get('option.base')
-path = session.get('option.path')
-
-base = 'rslbtool.xml' if base.empty?
-
-# when path is given, assume that arg list is list of
-# suffixes, else assume it is a list of globbed filespec
-
-if path.empty?
- base += '.xml' unless base =~ /\..+$/
- list = commandline.arguments
-else
- Dir.chdir(File.dirname(path))
- list = Dir.glob("*.{#{commandline.arguments.join(',')}}")
-end
-
-begin
- reslib = Resource.new(base,session.get('option.namespace'))
- reslib.load(base)
-rescue
- session.error('problems with loading base')
- exit
-end
-
-unless session.get('option.texexec').empty?
- reslib.set_texexec(session.get('option.texexec'))
-end
-
-if session.get('option.add')
-
- session.report('adding records', list)
- reslib.add_figures(list,session.get('option.prefix'))
-
-elsif session.get('option.remove') or session.get('option.delete')
-
- session.report('removing records')
- reslib.delete_figures(list)
-
-elsif session.get('option.sort')
-
- session.report('sorting records')
- reslib.sort_figures()
-
-elsif session.get('option.purge')
-
- session.report('purging records')
- reslib.purge_figures()
-
-elsif session.get('option.dummy')
-
- session.report('creating dummy records')
- reslib.create_dummies(session.get('option.process'),session.get('option.result'),session.get('option.zipalso'))
-
-else
-
- session.warning('provide action')
-
-end
-
-reslib.save(base)
diff --git a/Master/texmf-dist/scripts/context/ruby/runtools.rb b/Master/texmf-dist/scripts/context/ruby/runtools.rb
deleted file mode 100644
index 77f805221aa..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/runtools.rb
+++ /dev/null
@@ -1,506 +0,0 @@
-require 'timeout'
-require 'fileutils'
-# require 'ftools'
-require 'rbconfig'
-
-class File
-
- # we don't want a/b//c
- #
- # puts File.join('a','b','c')
- # puts File.join('/a','b','c')
- # puts File.join('a:','b','c')
- # puts File.join('a/','/b/','c')
- # puts File.join('/a','/b/','c')
- # puts File.join('//a/','/b/','c')
-
- def File.join(*list)
- path, prefix = [*list].flatten.join(File::SEPARATOR), ''
- path.sub!(/^([\/]+)/) do
- prefix = $1
- ''
- end
- path.gsub!(/([\\\/]+)/) do
- File::SEPARATOR
- end
- prefix + path
- end
-
-end
-
-
-class Job
-
- $ownfile, $ownpath = '', ''
-
- def Job::set_own_path(file)
- $ownfile, $ownpath = File.basename(file), File.expand_path(File.dirname(file))
- $: << $ownpath
- end
-
- def Job::ownfile
- $ownfile
- end
-
- def Job::ownpath
- $ownpath
- end
-
-end
-
-class Job
-
- def initialize
- @startuppath = Dir.getwd
- @log = Array.new
- @testmode = false
- @ownpath = $ownpath
- @paths = Array.new
- end
-
- def exit(showlog=false)
- Dir.chdir(@startuppath)
- show_log if showlog
- Kernel::exit
- end
-
- def platform
- case RbConfig::CONFIG['host_os']
- when /mswin/ then :windows
- else :unix
- end
- end
-
- def path(*components)
- File.join([*components].flatten)
- end
-
- def found(name)
- FileTest.file?(path(name)) || FileTest.directory?(path(name))
- end
-
- def binary(name)
- if platform == :windows then
- name.sub(/\.[^\/]+$/o,'') + '.exe'
- else
- name
- end
- end
-
- def suffixed(name,suffix)
- if name =~ /\.[^\/]+$/o then
- name
- else
- name + '.' + suffix
- end
- end
-
- def expanded(*name)
- File.expand_path(File.join(*name))
- end
-
- def argument(n,default=nil)
- ARGV[n] || default
- end
-
- def variable(name,default='')
- ENV[name] || default
- end
-
- def change_dir(*dir)
- dir, old = expanded(path(*dir)), expanded(Dir.getwd)
- unless old == dir then
- begin
- Dir.chdir(dir)
- rescue
- error("unable to change to path #{dir}")
- else
- if old == dir then
- error("error in changing to path #{dir}")
- else
- message("changed to path #{dir}")
- end
- end
- end
- # return File.expand_path(Dir.getwd)
- end
-
- def delete_dir(*dir)
- begin
- dir = path(*dir)
- pattern = "#{dir}/**/*"
- puts("analyzing dir #{pattern}")
- files = Dir.glob(pattern).sort.reverse
- files.each do |f|
- begin
- # FileTest.file?(f) fails on .whatever files
- File.delete(f)
- rescue
- # probably directory
- else
- puts("deleting file #{f}")
- end
- end
- files.each do |f|
- begin
- Dir.rmdir(f)
- rescue
- # strange
- else
- message("deleting path #{f}")
- end
- end
- begin
- Dir.rmdir(dir)
- rescue
- # strange
- else
- message("deleting parent #{dir}")
- end
- Dir.glob(pattern).sort.each do |f|
- warning("unable to delete #{f}")
- end
- rescue
- warning("unable to delete path #{File.expand_path(dir)} (#{$!})")
- else
- message("path #{File.expand_path(dir)} removed")
- end
- end
-
-
- def create_dir(*dir)
- begin
- dir = path(*dir)
- unless FileTest.directory?(dir) then
- File.makedirs(dir)
- else
- return
- end
- rescue
- error("unable to create path #{File.expand_path(dir)}")
- else
- message("path #{File.expand_path(dir)} created")
- end
- end
-
- def show_dir(delay=0)
- _puts_("\n")
- print Dir.getwd + ' '
- begin
- timeout(delay) do
- loop do
- print '.'
- sleep(1)
- end
- end
- rescue TimeoutError
- # ok
- end
- _puts_("\n\n")
- end
-
- def copy_file(from,to='.',exclude=[])
- to, ex = path(to), [exclude].flatten
- Dir.glob(path(from)).each do |file|
- tofile = to.sub(/[\.\*]$/o) do File.basename(file) end
- _do_copy_(file,tofile) unless ex.include?(File.extname(file))
- end
- end
-
- def clone_file(from,to)
- if from and to then
- to = File.join(File.basename(from),to) if File.basename(to).empty?
- _do_copy_(from,to)
- end
- end
-
- def copy_dir(from,to,pattern='*',exclude=[]) # recursive
- pattern = '*' if ! pattern or pattern.empty?
- if from and to and File.expand_path(from) != File.expand_path(to) then
- ex = [exclude].flatten
- Dir.glob("#{from}/**/#{pattern}").each do |file|
- unless ex.include?(File.extname(file)) then
- _do_copy_(file,File.join(to,file.sub(/^#{from}/, '')))
- end
- end
- end
- end
-
- def copy_path(from,to,pattern='*',exclude=[]) # non-recursive
- pattern = '*' if ! pattern or pattern.empty?
- if from and to and File.expand_path(from) != File.expand_path(to) then
- ex = [exclude].flatten
- Dir.glob("#{from}/#{pattern}").each do |file|
- unless ex.include?(File.extname(file)) then
- _do_copy_(file,File.join(to,file.sub(/^#{from}/, '')))
- end
- end
- end
- end
-
- def _do_copy_(file,tofile)
- if FileTest.file?(file) and File.expand_path(file) != File.expand_path(tofile) then
- begin
- create_dir(File.dirname(tofile))
- File.copy(file,tofile)
- rescue
- error("unable to copy #{file} to #{tofile}")
- else
- message("file #{file} copied to #{tofile}")
- end
- else
- puts("file #{file} is not copied")
- end
- end
-
- def rename_file(from,to)
- from, to = path(from), path(to)
- begin
- File.move(from,to)
- rescue
- error("unable to rename #{from} to #{to}")
- else
- message("#{from} renamed to #{to}")
- end
- end
-
- def delete_file(pattern)
- Dir.glob(path(pattern)).each do |file|
- _do_delete_(file)
- end
- end
-
- def delete_files(*files)
- [*files].flatten.each do |file|
- _do_delete_(file)
- end
- end
-
- def _do_delete_(file)
- if FileTest.file?(file) then
- begin
- File.delete(file)
- rescue
- error("unable to delete file #{file}")
- else
- message("file #{file} deleted")
- end
- else
- message("no file #{File.expand_path(file)}")
- end
- end
-
- def show_log(filename=nil)
- if filename then
- begin
- if f = File.open(filename,'w') then
- @log.each do |line|
- f.puts(line)
- end
- f.close
- end
- message("log data written to #{filename}")
- rescue
- error("unable to write log to #{filename}")
- end
- else
- @log.each do |line|
- _puts_(line)
- end
- end
- end
-
- def _puts_(str)
- begin
- STDOUT.puts( str)
- rescue
- STDERR.puts("error while writing '#{str}' to terminal")
- end
- end
-
- def puts(message)
- @log << message
- _puts_(message)
- end
-
- def error(message)
- puts("! #{message}")
- exit
- end
-
- def warning(message)
- puts("- #{message}")
- end
-
- def message(message)
- puts("+ #{message}")
- end
-
- def export_variable(variable,value)
- value = path(value) if value.class == Array
- ENV[variable] = value
- message("environment variable #{variable} set to #{value}")
- return value
- end
-
- def execute_command(*command)
- begin
- command = [*command].flatten.join(' ')
- message("running '#{command}'")
- _puts_("\n")
- ok = system(command)
- _puts_("\n")
- if true then # ok then
- message("finished '#{command}'")
- else
- error("error in running #{command}")
- end
- rescue
- error("unable to run #{command}")
- end
- end
-
- def pipe_command(*command)
- begin
- command = [*command].flatten.join(' ')
- message("running '#{command}'")
- result = `#{command}`
- _puts_("\n")
- _puts_(result)
- _puts_("\n")
- rescue
- error("unable to run #{command}")
- end
- end
-
- def execute_script(script)
- script = suffixed(script,'rb')
- script = path(script_path,File.basename(script)) unless found(script)
- if found(script) then
- begin
- message("loading script #{script}")
- load(script)
- rescue
- error("error in loading script #{script} (#{$!})")
- else
- message("script #{script} finished")
- end
- else
- warning("no script #{script}")
- end
- end
-
- def execute_binary(*command)
- command = [*command].flatten.join(' ').split(' ')
- command[0] = binary(command[0])
- execute_command(command)
- end
-
- def extend_path(pth)
- export_variable('PATH',"#{path(pth)}#{File::PATH_SEPARATOR}#{ENV['PATH']}")
- end
-
- def startup_path
- @startuppath
- end
-
- def current_path
- Dir.getwd
- end
-
- def script_path
- @ownpath
- end
-
- def push_path(newpath)
- newpath = File.expand_path(newpath)
- @paths.push(newpath)
- change_dir(newpath)
- end
-
- def pop_path
- change_dir(if @paths.length > 0 then @paths.pop else @startuppath end)
- end
-
- # runner = Runner.new
- # runner.texmfstart('texexec','--help')
-
- def texmfstart(name,args,verbose=false)
- command = ['texmfstart',"#{'--verbose' if verbose}",name,args].flatten.join(' ')
- system(command)
- end
-
-end
-
-class Job
-
- # copied from texmfstart and patched (message/error), different name
-
- def use_tree(tree)
- unless tree.empty? then
- begin
- setuptex = File.join(tree,'setuptex.tmf')
- if FileTest.file?(setuptex) then
- message("tex tree : #{setuptex}")
- ENV['TEXPATH'] = tree.sub(/\/+$/,'') # + '/'
- ENV['TMP'] = ENV['TMP'] || ENV['TEMP'] || ENV['TMPDIR'] || ENV['HOME']
- case RUBY_PLATFORM
- when /(mswin|bccwin|mingw|cygwin)/i then ENV['TEXOS'] = ENV['TEXOS'] || 'texmf-mswin'
- when /(linux)/i then ENV['TEXOS'] = ENV['TEXOS'] || 'texmf-linux'
- when /(darwin|rhapsody|nextstep)/i then ENV['TEXOS'] = ENV['TEXOS'] || 'texmf-macosx'
- # when /(netbsd|unix)/i then # todo
- else # todo
- end
- ENV['TEXMFOS'] = "#{ENV['TEXPATH']}/#{ENV['TEXOS']}"
- message("preset : TEXPATH => #{ENV['TEXPATH']}")
- message("preset : TEXOS => #{ENV['TEXOS']}")
- message("preset : TEXMFOS => #{ENV['TEXMFOS']}")
- message("preset : TMP => #{ENV['TMP']}")
- IO.readlines(File.join(tree,'setuptex.tmf')).each do |line|
- case line
- when /^[\#\%]/ then
- # comment
- when /^(.*?)\s+\=\s+(.*)\s*$/ then
- k, v = $1, $2
- ENV[k] = v.gsub(/\%(.*?)\%/) do
- ENV[$1] || ''
- end
- message("user set : #{k} => #{ENV[k]}")
- end
- end
- else
- warning("no setup file '#{setuptex}', tree not initialized") # no error
- end
- rescue
- warning("error in setup: #{$!}")
- end
- end
- end
-
-end
-
-Job::set_own_path($0)
-
-if Job::ownfile == 'runtools.rb' then
-
- begin
- script = ARGV.shift
- if script then
- script += '.rb' if File.extname(script).empty?
- fullname = File.expand_path(script)
- fullname = File.join(Job::ownpath,script) unless FileTest.file?(fullname)
- if FileTest.file?(fullname) then
- puts("loading script #{fullname}")
- Job::set_own_path(fullname)
- load(fullname)
- else
- puts("unknown script #{fullname}")
- end
- else
- puts("provide script name")
- end
- rescue
- puts("fatal error: #{$!}")
- end
-
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/texexec.rb b/Master/texmf-dist/scripts/context/ruby/texexec.rb
deleted file mode 100644
index 7f8298c0918..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/texexec.rb
+++ /dev/null
@@ -1,791 +0,0 @@
-#!/usr/bin/env ruby
-#encoding: ASCII-8BIT
-
-banner = ['TeXExec', 'version 6.2.1', '1997-2009', 'PRAGMA ADE/POD']
-
-$: << File.expand_path(File.dirname($0)) ; $: << File.join($:.last,'lib') ; $:.uniq!
-
-require 'fileutils'
-# require 'ftools' # needed ?
-
-require 'base/switch'
-require 'base/logger'
-require 'base/variables'
-require 'base/system'
-
-require 'base/state' # needed ?
-require 'base/file' # needed ?
-
-require 'base/tex'
-require 'base/texutil'
-require 'base/kpse'
-
-class Commands
-
- include CommandBase
-
- def make
- if job = TEX.new(logger) then
- prepare(job)
- # bonus, overloads language switch !
- job.setvariable('language','all') if @commandline.option('all')
- if @commandline.arguments.length > 0 then
- if @commandline.arguments.first == 'all' then
- job.setvariable('texformats',job.defaulttexformats)
- job.setvariable('mpsformats',job.defaultmpsformats)
- else
- job.setvariable('texformats',@commandline.arguments)
- job.setvariable('mpsformats',@commandline.arguments)
- end
- end
- job.makeformats
- job.inspect && Kpse.inspect if @commandline.option('verbose')
- seterror if job.error?
- end
- end
-
- def check
- if job = TEX.new(logger) then
- job.checkcontext
- job.inspect && Kpse.inspect if @commandline.option('verbose')
- end
- end
-
- def main
- if @commandline.arguments.length>0 then
- process
- else
- help
- end
- end
-
- def process
- if job = TEX.new(logger) then
- job.setvariable('files',@commandline.arguments)
- prepare(job)
- job.processtex
- job.inspect && Kpse.inspect if @commandline.option('verbose')
- seterror if job.error?
- end
- end
-
- def mptex
- if job = TEX.new(logger) then
- job.setvariable('files',@commandline.arguments)
- prepare(job)
- job.processmptex
- job.inspect && Kpse.inspect if @commandline.option('verbose')
- seterror if job.error?
- end
- end
-
- def mpxtex
- if job = TEX.new(logger) then
- job.setvariable('files',@commandline.arguments)
- prepare(job)
- job.processmpxtex
- job.inspect && Kpse.inspect if @commandline.option('verbose')
- seterror if job.error?
- end
- end
-
- def mpgraphic
- if job = TEX.new(logger) then
- job.setvariable('files',@commandline.arguments)
- prepare(job)
- job.processmpgraphic
- job.inspect && Kpse.inspect if @commandline.option('verbose')
- seterror if job.error?
- end
- end
-
- def mpstatic
- if job = TEX.new(logger) then
- job.setvariable('filename',@commandline.arguments.first)
- prepare(job)
- job.processmpstatic
- job.inspect && Kpse.inspect if @commandline.option('verbose')
- seterror if job.error?
- end
- end
-
- # hard coded goodies # to be redone as s-ctx-.. with vars passed as such
-
- def listing
- if job = TEX.new(logger) then
- prepare(job)
- job.cleanuptemprunfiles
- files = if @commandline.option('sort') then @commandline.arguments.sort else @commandline.arguments end
- if files.length > 0 then
- if f = File.open(job.tempfilename('tex'),'w') then
- backspace = @commandline.checkedoption('backspace', '1.5cm')
- topspace = @commandline.checkedoption('topspace', '1.5cm')
- pretty = @commandline.option('pretty')
- f << "% interface=english\n"
- f << "\\setupbodyfont[11pt,tt]\n"
- f << "\\setuplayout\n"
- f << " [topspace=#{topspace},backspace=#{backspace},\n"
- f << " header=0cm,footer=1.5cm,\n"
- f << " width=middle,height=middle]\n"
- f << "\\setuptyping[lines=yes]\n"
- f << "\\setuptyping[option=color]\n" if pretty
- f << "\\starttext\n";
- files.each do |filename|
- report("list file: #{filename}")
- cleanname = cleantexfilename(filename).downcase
- f << "\\page\n"
- f << "\\setupfootertexts[\\tttf #{cleanname}][\\tttf \\pagenumber]\n"
- f << "\\typefile{#{filename}}\n"
- end
- f << "\\stoptext\n"
- f.close
- job.setvariable('interface','english')
- job.setvariable('simplerun',true)
- # job.setvariable('nooptionfile',true)
- job.setvariable('files',[job.tempfilename])
- job.processtex
- else
- report('no files to list')
- end
- else
- report('no files to list')
- end
- job.cleanuptemprunfiles
- end
- end
-
- def figures
- # we replaced "texutil --figures ..."
- if job = TEX.new(logger) then
- prepare(job)
- job.cleanuptemprunfiles
- fast = @commandline.option('fast')
- files = if @commandline.option('sort') then @commandline.arguments.sort else @commandline.arguments end
- if fast or (files.length > 0) then
- if f = File.open(job.tempfilename('tex'),'w') then
- files.delete("texexec.pdf")
- # Kpse.runscript('rlxtools', ['--identify','--collect'], files.join(' ')) unless fast
- system("texmfstart rlxtools --identify --collect #{files.join(' ')}")
- figures = @commandline.checkedoption('method', 'a').downcase
- paperoffset = @commandline.checkedoption('paperoffset', '0pt')
- backspace = @commandline.checkedoption('backspace', '1.5cm')
- topspace = @commandline.checkedoption('topspace', '1.5cm')
- boxtype = @commandline.checkedoption('boxtype','')
- f << "% format=english\n";
- f << "\\usemodule[res-20]\n"
- f << "\\setuplayout\n";
- f << " [topspace=#{topspace},backspace=#{backspace},\n"
- f << " header=1.5cm,footer=0pt,\n";
- f << " width=middle,height=middle]\n";
- if @commandline.option('fullscreen') then
- f << "\\setupinteraction\n";
- f << " [state=start]\n";
- f << "\\setupinteractionscreen\n";
- f << " [option=max]\n";
- end
- boxtype += "box" unless boxtype.empty? || (boxtype =~ /box$/io)
- f << "\\starttext\n";
- f << "\\showexternalfigures[alternative=#{figures},offset=#{paperoffset},size=#{boxtype}]\n";
- f << "\\stoptext\n";
- f.close
- job.setvariable('interface','english')
- job.setvariable('simplerun',true)
- job.setvariable('files',[job.tempfilename])
- job.processtex
- # File.silentdelete('rlxtools.rli') unless job.getvariable('keep')
- else
- report('no figures to show')
- end
- else
- report('no figures to show')
- end
- job.cleanuptemprunfiles
- end
- end
-
- def modules
- if job = TEX.new(logger) then
- prepare(job)
- job.cleanuptemprunfiles
- files = if @commandline.option('sort') then @commandline.arguments.sort else @commandline.arguments end
- msuffixes = ['tex','mkii','mkiv','mp','pl','pm','rb']
- if files.length > 0 then
- files.each do |fname|
- fnames = Array.new
- if FileTest.file?(fname) then
- fnames << fname
- else
- msuffixes.each do |fsuffix|
- fnames << File.suffixed(fname,fsuffix)
- end
- end
- fnames.each do |ffname|
- if msuffixes.include?(File.splitname(ffname)[1]) && FileTest.file?(ffname) then
- if mod = File.open(job.tempfilename('tex'),'w') then
- if File.suffix(ffname) =~ /^(mkii|mkiv)$/o then
- markfile = $1
- else
- markfile = nil
- end
- # Kpse.runscript('ctxtools',['--document'],ffname)
- system("texmfstart ctxtools --document #{ffname}")
- if ted = File.silentopen(File.suffixed(ffname,'ted')) then
- firstline = ted.gets
- if firstline =~ /interface=/o then
- mod << firstline
- else
- mod << "% interface=en\n"
- end
- ted.close
- else
- mod << "% interface=en\n"
- end
- mod << "\\usemodule[mod-01]\n"
- mod << "\\def\\ModuleNumber{1}\n"
- mod << "\\starttext\n"
- # todo: global file too
- mod << "\\readlocfile{#{File.suffixed(ffname,'ted')}}{}{}\n"
- mod << "\\stoptext\n"
- mod.close
- job.setvariable('interface','english') # redundant
- # job.setvariable('simplerun',true)
- # job.setvariable('nooptionfile',true)
- job.setvariable('files',[job.tempfilename])
- result = File.unsuffixed(File.basename(ffname))
- if markfile then
- result = result+'-'+markfile
- end
- job.setvariable('result',result)
- job.processtex
- # ["dvi", "pdf","ps"].each do |s|
- # File.silentrename(job.tempfilename(s),File.suffixed(ffname,s));
- # end
- end
- end
- end
- end
- else
- report('no modules to process')
- end
- job.cleanuptemprunfiles
- end
- end
-
- def pdfsplit
- if job = TEX.new(logger) then
- prepare(job)
- job.cleanuptemprunfiles
- filename = File.expand_path(@commandline.arguments.first)
- if FileTest.file?(filename) then
- basename = filename.sub(/\..*?$/,'')
- tempfile = File.suffixed(job.tempfilename,'tex')
- if basename != filename then
- info = `pdfinfo #{filename}`
- if info =~ /Pages:\s*(\d+)/ then
- nofpages = $1.to_i
- result = @commandline.checkedoption('result','texexec')
- nofpages.times do |i|
- if f = File.open(tempfile,"w") then
- n = i + 1
- report("extracting page #{n}")
- f << "\\starttext\\startTEXpage\n"
- f << "\\externalfigure[#{filename}][object=no,page=#{n}]\n"
- f << "\\stopTEXpage\\stoptext\n"
- f.close
- job.setvariable('result',"#{result}-#{n}")
- job.setvariable('interface','english') # redundant
- job.setvariable('simplerun',true)
- job.setvariable('purge',true)
- job.setvariable('files',[tempfile])
- job.processtex
- end
- end
- end
- end
- end
- job.cleanuptemprunfiles
- end
- end
-
- def arrangeoutput
- if job = TEX.new(logger) then
- prepare(job)
- job.cleanuptemprunfiles
- files = if @commandline.option('sort') then @commandline.arguments.sort else @commandline.arguments end
- if files.length > 0 then
- if f = File.open(job.tempfilename('tex'),'w') then
- emptypages = @commandline.checkedoption('addempty', '')
- paperoffset = @commandline.checkedoption('paperoffset', '0cm')
- textwidth = @commandline.checkedoption('textwidth', '0cm')
- backspace = @commandline.checkedoption('backspace', '0cm')
- topspace = @commandline.checkedoption('topspace', '0cm')
- f << "\\definepapersize\n"
- f << " [offset=#{paperoffset}]\n"
- f << "\\setuplayout\n"
- f << " [backspace=#{backspace},\n"
- f << " topspace=#{topspace},\n"
- f << " marking=on,\n" if @commandline.option('marking')
- f << " width=middle,\n"
- f << " height=middle,\n"
- f << " location=middle,\n"
- f << " header=0pt,\n"
- f << " footer=0pt]\n"
- unless @commandline.option('noduplex') then
- f << "\\setuppagenumbering\n"
- f << " [alternative=doublesided]\n"
- end
- f << "\\starttext\n"
- files.each do |filename|
- report("arranging file #{filename}")
- f << "\\insertpages\n"
- f << " [#{filename}]\n"
- f << " [#{emptypages}]\n" unless emptypages.empty?
- f << " [width=#{textwidth}]\n"
- end
- f << "\\stoptext\n"
- f.close
- job.setvariable('interface','english')
- job.setvariable('simplerun',true)
- job.setvariable('arrange',true)
- # job.setvariable('nooptionfile',true)
- job.setvariable('files',[job.tempfilename])
- job.processtex
- else
- report('no files to arrange')
- end
- else
- report('no files to arrange')
- end
- job.cleanuptemprunfiles
- end
- end
-
- def selectoutput
- if job = TEX.new(logger) then
- prepare(job)
- job.cleanuptemprunfiles
- files = if @commandline.option('sort') then @commandline.arguments.sort else @commandline.arguments end
- if files.length > 0 then
- if f = File.open(job.tempfilename('tex'),'w') then
- selection = @commandline.checkedoption('selection', '')
- paperoffset = @commandline.checkedoption('paperoffset', '0cm')
- textwidth = @commandline.checkedoption('textwidth', '0cm')
- backspace = @commandline.checkedoption('backspace', '0cm')
- topspace = @commandline.checkedoption('topspace', '0cm')
- paperformat = @commandline.checkedoption('paperformat', 'A4*A4').split(/[\*x]/o)
- from, to = paperformat[0] || 'A4', paperformat[1] || paperformat[0] || 'A4'
- if from == 'fit' or to == 'fit' then
- f << "\\getfiguredimensions[#{files.first}]\n"
- if from == 'fit' then
- f << "\\expanded{\\definepapersize[from-fit][width=\\figurewidth,height=\\figureheight]}\n"
- from = 'from-fit'
- end
- if to == 'fit' then
- f << "\\expanded{\\definepapersize[to-fit][width=\\figurewidth,height=\\figureheight]}\n"
- to = 'to-fit'
- end
- end
- job.setvariable('paperformat','') # else overloaded later on
- f << "\\setuppapersize[#{from}][#{to}]\n"
- f << "\\definepapersize\n";
- f << " [offset=#{paperoffset}]\n";
- f << "\\setuplayout\n";
- f << " [backspace=#{backspace},\n";
- f << " topspace=#{topspace},\n";
- f << " marking=on,\n" if @commandline.option('marking')
- f << " width=middle,\n";
- f << " height=middle,\n";
- f << " location=middle,\n";
- f << " header=0pt,\n";
- f << " footer=0pt]\n";
- f << "\\setupexternalfigures\n";
- f << " [directory=]\n";
- f << "\\starttext\n";
- unless selection.empty? then
- f << "\\filterpages\n"
- f << " [#{files.first}][#{selection}][width=#{textwidth}]\n"
- end
- f << "\\stoptext\n"
- f.close
- job.setvariable('interface','english')
- job.setvariable('simplerun',true)
- # job.setvariable('nooptionfile',true)
- job.setvariable('files',[job.tempfilename])
- job.processtex
- else
- report('no files to selectt')
- end
- else
- report('no files to select')
- end
- job.cleanuptemprunfiles
- end
- end
-
- def copyoutput
- copyortrim(false,'copy')
- end
-
- def trimoutput
- copyortrim(true,'trim')
- end
-
- def copyortrim(trim=false,what='unknown')
- if job = TEX.new(logger) then
- prepare(job)
- job.cleanuptemprunfiles
- files = if @commandline.option('sort') then @commandline.arguments.sort else @commandline.arguments end
- if files.length > 0 then
- if f = File.open(job.tempfilename('tex'),'w') then
- scale = @commandline.checkedoption('scale')
- begin
- scale = (scale.to_f * 1000.0).to_i if scale.to_i < 10
- rescue
- scale = 1000
- end
- scale = scale.to_i
- paperoffset = @commandline.checkedoption('paperoffset', '0cm')
- f << "\\starttext\n"
- files.each do |filename|
- result = @commandline.checkedoption('result','texexec')
- begin
- if (filename !~ /^texexec/io) && (filename !~ /^#{result}/) then
- report("copying file: #{filename}")
- f << "\\getfiguredimensions\n"
- f << " [#{filename}]\n"
- f << " [scale=#{scale},\n"
- f << " page=1,\n"
- f << " size=trimbox\n" if trim
- f << "]\n"
- f << "\\definepapersize\n"
- f << " [copy]\n"
- f << " [width=\\figurewidth,\n"
- f << " height=\\figureheight]\n"
- f << "\\setuppapersize\n"
- f << " [copy][copy]\n"
- f << "\\setuplayout\n"
- f << " [page]\n"
- f << "\\setupexternalfigures\n"
- f << " [directory=]\n"
- f << "\\copypages\n"
- f << " [#{filename}]\n"
- f << " [scale=#{scale},\n"
- f << " marking=on,\n" if @commandline.option('markings')
- f << " size=trimbox,\n" if trim
- f << " offset=#{paperoffset}]\n"
- end
- rescue
- report("wrong specification")
- end
- end
- f << "\\stoptext\n"
- f.close
- job.setvariable('interface','english')
- job.setvariable('simplerun',true)
- # job.setvariable('nooptionfile',true)
- job.setvariable('files',[job.tempfilename])
- job.processtex
- else
- report("no files to #{what}")
- end
- else
- report("no files to #{what}")
- end
- job.cleanuptemprunfiles
- end
- end
-
- # todo: make this styles
-
- def combineoutput
- if job = TEX.new(logger) then
- prepare(job)
- job.cleanuptemprunfiles
- files = if @commandline.option('sort') then @commandline.arguments.sort else @commandline.arguments end
- if files.length > 0 then
- if f = File.open(job.tempfilename('tex'),'w') then
- paperoffset = @commandline.checkedoption('paperoffset', '0cm')
- combination = @commandline.checkedoption('combination','2*2').split(/[\*x]/o)
- paperformat = @commandline.checkedoption('paperformat', 'A4*A4').split(/[\*x]/o)
- bannerheight = @commandline.checkedoption('bannerheight', '')
- pdftitle = @commandline.checkedoption('pdftitle', '')
- nx, ny = combination[0] || '2', combination[1] || combination[0] || '2'
- from, to = paperformat[0] || 'A4', paperformat[1] || paperformat[0] || 'A4'
- f << "\\setuppapersize[#{from}][#{to}]\n"
- f << "\\setuplayout\n"
- f << " [topspace=#{paperoffset},backspace=#{paperoffset},\n"
- f << " header=0pt,footer=0pt,\n"
- f << " width=middle,height=middle]\n"
- if bannerheight.empty? then
- f << "\\setuplayout[footer=1cm]\n"
- else
- f << "\\definelayer[page][width=\\paperwidth,height=\\paperheight]\n"
- f << "\\setupbackgrounds[page][background=page]\n"
- end
- if @commandline.option('nobanner') then
- f << "\\setuplayout[footer=0cm]\n"
- f << "\\setupbackgrounds[page][background=]\n"
- end
- f << "\\setupexternalfigures[directory=]\n"
- if not pdftitle.empty? then
- f << "\\setupinteraction[state=start,title={#{pdftitle}}]\n"
- end
- f << "\\starttext\n"
- files.each do |filename|
- result = @commandline.checkedoption('result','texexec')
- if (filename !~ /^texexec/io) && (filename !~ /^#{result}/) then
- report("combination file: #{filename}")
- cleanname = cleantexfilename(filename).downcase
- bannerstring = "\\tttf #{cleanname}\\quad\\quad\\currentdate\\quad\\quad\\pagenumber"
- if bannerheight.empty? then
- f << "\\setupfootertexts\n"
- f << " [#{bannerstring}]\n"
- else
- # for the moment we lack a better hook
- f << "\\setuptexttexts\n"
- f << " [{\\setlayerframed[page][preset=middlebottom][frame=off,height=#{bannerheight}]{#{bannerstring}}}]\n"
- end
- f << "\\combinepages[#{filename}][nx=#{nx},ny=#{ny}]\n"
- f << "\\page\n"
- end
- end
- f << "\\stoptext\n"
- f.close
- job.setvariable('interface','english')
- job.setvariable('simplerun',true)
- # job.setvariable('nooptionfile',true)
- job.setvariable('files',[job.tempfilename])
- job.processtex
- else
- report('no files to list')
- end
- else
- report('no files to list')
- end
- job.cleanuptemprunfiles
- end
- end
-
- private
-
- def prepare(job)
-
- job.booleanvars.each do |k|
- job.setvariable(k,@commandline.option(k))
- end
- job.stringvars.each do |k|
- job.setvariable(k,@commandline.option(k)) unless @commandline.option(k).empty?
- end
- job.standardvars.each do |k|
- job.setvariable(k,@commandline.option(k)) unless @commandline.option(k).empty?
- end
- job.knownvars.each do |k|
- job.setvariable(k,@commandline.option(k)) unless @commandline.option(k).empty?
- end
-
-job.setvariable('given.backend',job.getvariable('backend'))
-
- if (str = @commandline.option('engine')) && ! str.standard? && ! str.empty? then
- job.setvariable('texengine',str)
- elsif @commandline.oneof('pdfetex','pdftex','pdf') then
- job.setvariable('texengine','pdftex')
- elsif @commandline.oneof('xetex','xtx') then
- job.setvariable('texengine','xetex')
- elsif @commandline.oneof('aleph') then
- job.setvariable('texengine','aleph')
- elsif @commandline.oneof('petex') then
- job.setvariable('texengine','petex')
- else
- job.setvariable('texengine','standard')
- end
-
- if (str = @commandline.option('backend')) && ! str.standard? && ! str.empty? then
- job.setvariable('backend',str)
- elsif @commandline.oneof('pdfetex','pdftex','pdf') then
- job.setvariable('backend','pdftex')
- elsif @commandline.oneof('dvipdfmx','dvipdfm','dpx','dpm') then
- job.setvariable('backend','dvipdfmx')
- elsif @commandline.oneof('xetex','xtx') then
- job.setvariable('backend','xetex')
- elsif @commandline.oneof('aleph') then
- job.setvariable('backend','dvipdfmx')
- elsif @commandline.oneof('petex') then
- job.setvariable('backend','dvipdfmx')
- elsif @commandline.oneof('dvips','ps') then
- job.setvariable('backend','dvips')
- elsif @commandline.oneof('xdv') then
- job.setvariable('backend','xdv')
- else
- case job.getvariable('texengine')
- when 'pdfetex' then job.setvariable('backend','pdftex')
- when 'pdftex' then job.setvariable('backend','pdftex')
- when 'xetex' then job.setvariable('backend','xetex')
- when 'petex' then job.setvariable('backend','dvipdfmx')
- when 'aleph' then job.setvariable('backend','dvipdfmx')
- else
- job.setvariable('backend','standard')
- end
- end
-
- if (str = @commandline.option('engine')) && ! str.standard? && ! str.empty? then
- job.setvariable('mpsengine',@commandline.option('engine'))
- else
- job.setvariable('mpsengine','standard')
- end
-
- end
-
- def cleantexfilename(filename)
- filename.gsub(/([\$\_\#])/) do "\\$1" end.gsub(/([\~])/) do "\\string$1" end
- end
-
-end
-
-# we will make this pluggable, i.e. load plugins from base/tex that
-# extend the class and may even add switches
-#
-# commandline.load_plugins('base/tex')
-#
-# maybe it's too slow so for a while keep the --pdf* in here
-
-logger = Logger.new(banner.shift)
-commandline = CommandLine.new
-
-commandline.registeraction('make', 'make formats')
-commandline.registeraction('check', 'check versions')
-commandline.registeraction('process', 'process file')
-commandline.registeraction('mptex', 'process mp file')
-commandline.registeraction('mpxtex', 'process mpx file')
-commandline.registeraction('mpgraphic', 'process mp file to stand-alone graphics')
-commandline.registeraction('mpstatic', 'process mp/ctx file to stand-alone graphics')
-
-commandline.registeraction('listing', 'list of file content')
-commandline.registeraction('figures', 'generate overview of figures')
-commandline.registeraction('modules', 'generate module documentation')
-commandline.registeraction('pdfarrange', 'impose pages (booklets)')
-commandline.registeraction('pdfselect', 'select pages from file(s)')
-commandline.registeraction('pdfcopy', 'copy pages from file(s)')
-commandline.registeraction('pdftrim', 'trim pages from file(s)')
-commandline.registeraction('pdfcombine', 'combine multiple pages')
-commandline.registeraction('pdfsplit', 'split file in pages')
-
-# compatibility switch
-
-class Commands
-
- include CommandBase
-
- alias pdfarrange :arrangeoutput
- alias pdfselect :selectoutput
- alias pdfcopy :copyoutput
- alias pdftrim :trimoutput
- alias pdfcombine :combineoutput
-
-end
-
-# so far for compatibility, will move to tex
-
-extrastringvars = [
- 'pages', 'background', 'backspace', 'topspace', 'boxtype', 'tempdir','bannerheight',
- 'printformat', 'method', 'scale', 'selection',
- 'combination', 'textwidth', 'addempty', 'logfile',
- 'startline', 'endline', 'startcolumn', 'endcolumn', 'scale'
-]
-
-extrabooleanvars = [
- 'centerpage', 'noduplex', 'color', 'pretty',
- 'fullscreen', 'screensaver', 'markings'
-]
-
-if job = TEX.new(logger) then
-
- job.setextrastringvars(extrastringvars)
- job.setextrabooleanvars(extrabooleanvars)
-
- job.booleanvars.each do |k|
- commandline.registerflag(k)
- end
- job.stringvars.each do |k|
- commandline.registervalue(k,'')
- end
- job.standardvars.each do |k|
- commandline.registervalue(k,'standard')
- end
- job.knownvars.each do |k|
- commandline.registervalue(k,'')
- end
-
-end
-
-class Commands
-
- alias saved_help help
-
- def wrap_help(title, vars)
- report("")
- report(title)
- report("")
- r, n = '', 0
- vars.sort.each do |s|
- if n == 5 then
- report(r)
- r, n = '', 1
- else
- n += 1
- end
- r << ' ' + s.to_s
- end
- report(r) unless r.empty?
- end
-
- def help
- saved_help
- if @commandline.option('all') then
- if job = TEX.new(logger) then
- wrap_help("boolean switches:", job.allbooleanvars)
- wrap_help("string switches:", job.allstringvars)
- end
- else
- report('')
- report('--help --all shows all switches')
- end
- end
-
-end
-
-# todo: register flags -> first one true
-
-commandline.registerflag('pdf')
-commandline.registerflag('pdftex')
-commandline.registerflag('pdfetex')
-
-commandline.registerflag('dvipdfmx')
-commandline.registerflag('dvipdfm')
-commandline.registerflag('dpx')
-commandline.registerflag('dpm')
-
-commandline.registerflag('dvips')
-commandline.registerflag('ps')
-
-commandline.registerflag('xetex')
-commandline.registerflag('xtx')
-commandline.registerflag('xdv')
-
-commandline.registerflag('aleph')
-
-commandline.registerflag('petex')
-
-commandline.registerflag('all')
-commandline.registerflag('fast')
-commandline.registerflag('sort')
-
-# generic
-
-commandline.registeraction('help')
-commandline.registeraction('version')
-
-commandline.registerflag('verbose')
-
-commandline.expand
-
-Commands.new(commandline,logger,banner).execute(commandline.action || 'main') # or just execute()
diff --git a/Master/texmf-dist/scripts/context/ruby/texmfstart.rb b/Master/texmf-dist/scripts/context/ruby/texmfstart.rb
deleted file mode 100755
index 6e508eeb9a5..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/texmfstart.rb
+++ /dev/null
@@ -1,1271 +0,0 @@
-#!/usr/bin/env ruby
-#encoding: ASCII-8BIT
-
-# We have removed the fast, server and client variants and no longer
-# provide the distributed 'serve trees' option. After all, we're now
-# using luatex.
-
-# program : texmfstart
-# copyright : PRAGMA Advanced Document Engineering
-# version : 1.9.0 - 2003/2006
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# info : j.hagen@xs4all.nl
-# www : www.pragma-pod.com / www.pragma-ade.com
-
-# no special requirements, i.e. no exa modules/classes used
-
-# texmfstart [switches] filename [optional arguments]
-#
-# ruby2exe texmfstart --help -> avoids stub test
-#
-# Of couse I can make this into a nice class, which i'll undoubtely will
-# do when I feel the need. In that case it will be part of a bigger game.
-
-# --locate => provides location
-# --exec => exec instead of system
-# --iftouched=a,b => only if timestamp a<>b
-# --ifchanged=a,b => only if checksum changed
-#
-# file: path: bin:
-
-# texmfstart --exec bin:scite *.tex
-
-# we don't depend on other libs
-
-$: << File.expand_path(File.dirname($0)) ; $: << File.join($:.last,'lib') ; $:.uniq!
-
-require "rbconfig"
-require "fileutils"
-
-require "digest/md5"
-
-# kpse_merge_start
-
-class File
- def File::makedirs(*x)
- FileUtils.makedirs(x)
- end
-end
-
-class String
-
- def split_path
- if self =~ /\;/o || self =~ /^[a-z]\:/io then
- self.split(";")
- else
- self.split(":")
- end
- end
-
-end
-
-class Array
-
- def join_path
- self.join(File::PATH_SEPARATOR)
- end
-
-end
-
-class File
-
- def File.locate_file(path,name)
- begin
- files = Dir.entries(path)
- if files.include?(name) then
- fullname = File.join(path,name)
- return fullname if FileTest.file?(fullname)
- end
- files.each do |p|
- fullname = File.join(path,p)
- if p != '.' and p != '..' and FileTest.directory?(fullname) and result = locate_file(fullname,name) then
- return result
- end
- end
- rescue
- # bad path
- end
- return nil
- end
-
- def File.glob_file(pattern)
- return Dir.glob(pattern).first
- end
-
-end
-
-# kpse_merge_file: 't:/ruby/base/kpsedirect.rb'
-
-class KpseDirect
-
- attr_accessor :progname, :format, :engine
-
- def initialize
- @progname, @format, @engine = '', '', ''
- end
-
- def expand_path(str)
- clean_name(`kpsewhich -expand-path=#{str}`.chomp)
- end
-
- def expand_var(str)
- clean_name(`kpsewhich -expand-var=#{str}`.chomp)
- end
-
- def find_file(str)
- clean_name(`kpsewhich #{_progname_} #{_format_} #{str}`.chomp)
- end
-
- def _progname_
- if @progname.empty? then '' else "-progname=#{@progname}" end
- end
- def _format_
- if @format.empty? then '' else "-format=\"#{@format}\"" end
- end
-
- private
-
- def clean_name(str)
- str.gsub(/\\/,'/')
- end
-
-end
-
-# kpse_merge_stop
-
-$mswindows = RbConfig::CONFIG['host_os'] =~ /mswin/
-$separator = File::PATH_SEPARATOR
-$version = "2.1.0"
-$ownpath = File.dirname($0)
-
-if $mswindows then
- require "win32ole"
- require "Win32API"
-end
-
-# exit if defined?(REQUIRE2LIB)
-
-$stdout.sync = true
-$stderr.sync = true
-
-$applications = Hash.new
-$suffixinputs = Hash.new
-$predefined = Hash.new
-$runners = Hash.new
-
-$suffixinputs['pl'] = 'PERLINPUTS'
-$suffixinputs['rb'] = 'RUBYINPUTS'
-$suffixinputs['py'] = 'PYTHONINPUTS'
-$suffixinputs['jar'] = 'JAVAINPUTS'
-$suffixinputs['pdf'] = 'PDFINPUTS'
-
-$predefined['texexec'] = 'texexec.rb'
-$predefined['texutil'] = 'texutil.rb'
-$predefined['texfont'] = 'texfont.pl'
-$predefined['texshow'] = 'texshow.pl'
-
-$predefined['makempy'] = 'makempy.pl'
-$predefined['mptopdf'] = 'mptopdf.pl'
-$predefined['pstopdf'] = 'pstopdf.rb'
-
-$predefined['examplex'] = 'examplex.rb'
-$predefined['concheck'] = 'concheck.rb'
-
-$predefined['runtools'] = 'runtools.rb'
-$predefined['textools'] = 'textools.rb'
-$predefined['tmftools'] = 'tmftools.rb'
-$predefined['ctxtools'] = 'ctxtools.rb'
-$predefined['rlxtools'] = 'rlxtools.rb'
-$predefined['pdftools'] = 'pdftools.rb'
-$predefined['mpstools'] = 'mpstools.rb'
-# $predefined['exatools'] = 'exatools.rb'
-$predefined['xmltools'] = 'xmltools.rb'
-# $predefined['mtxtools'] = 'mtxtools.rb'
-
-$predefined['newpstopdf'] = 'pstopdf.rb'
-$predefined['newtexexec'] = 'texexec.rb'
-$predefined['pdftrimwhite'] = 'pdftrimwhite.pl'
-
-$makelist = [
- # context
- 'texexec',
- 'texutil',
- 'texfont',
- # mp/ps
- 'pstopdf',
- 'mptopdf',
- 'makempy',
- # misc
- 'ctxtools',
- 'pdftools',
- 'xmltools',
- 'textools',
- 'mpstools',
- 'tmftools',
- 'exatools',
- 'runtools',
- 'rlxtools',
- 'pdftrimwhite',
- 'texfind',
- 'texshow'
- #
- # no 'mtxtools',
- # no, 'texmfstart'
-]
-
-$scriptlist = 'rb|pl|py|jar'
-$documentlist = 'pdf|ps|eps|htm|html'
-
-$editor = ENV['TEXMFSTART_EDITOR'] || ENV['EDITOR'] || ENV['editor'] || 'scite'
-
-$crossover = true # to other tex tools, else only local
-$kpse = nil
-
-def set_applications(page=1)
-
- $applications['unknown'] = ''
- $applications['ruby'] = $applications['rb'] = 'ruby'
- $applications['perl'] = $applications['pl'] = 'perl'
- $applications['python'] = $applications['py'] = 'python'
- $applications['java'] = $applications['jar'] = 'java'
-
- if $mswindows then
- $applications['pdf'] = ['',"pdfopen --page #{page} --file",'acroread']
- $applications['html'] = ['','netscape','mozilla','opera','iexplore']
- $applications['ps'] = ['','gview32','gv','gswin32','gs']
- else
- $applications['pdf'] = ["pdfopen --page #{page} --file",'acroread']
- $applications['html'] = ['netscape','mozilla','opera']
- $applications['ps'] = ['gview','gv','gs']
- end
-
- $applications['htm'] = $applications['html']
- $applications['eps'] = $applications['ps']
-
-end
-
-set_applications()
-
-def check_kpse
- if $kpse then
- # already done
- else
- $kpse = KpseDirect.new
- end
-end
-
-if $mswindows then
-
- GetShortPathName = Win32API.new('kernel32', 'GetShortPathName', ['P','P','N'], 'N')
- GetLongPathName = Win32API.new('kernel32', 'GetLongPathName', ['P','P','N'], 'N')
-
- def dowith_pathname (filename,filemethod)
- filename = filename.gsub(/\\/o,'/') # no gsub! because filename can be frozen
- case filename
- when /\;/o then
- # could be a path spec
- return filename
- when /\s+/o then
- # danger lurking
- buffer = ' ' * 260
- length = filemethod.call(filename,buffer,buffer.size)
- if length>0 then
- return buffer.slice(0..length-1)
- else
- # when the path or file does not exist, nothing is returned
- # so we try to handle the path separately from the basename
- basename = File.basename(filename)
- pathname = File.dirname(filename)
- length = filemethod.call(pathname,buffer,260)
- if length>0 then
- return buffer.slice(0..length-1) + '/' + basename
- else
- return filename
- end
- end
- else
- # no danger
- return filename
- end
- end
-
- def longpathname (filename)
- dowith_pathname(filename,GetLongPathName)
- end
-
- def shortpathname (filename)
- dowith_pathname(filename,GetShortPathName)
- end
-
-else
-
- def longpathname (filename)
- filename
- end
-
- def shortpathname (filename)
- filename
- end
-
-end
-
-class File
-
- @@update_eps = 1
-
- def File.needsupdate(oldname,newname)
- begin
- oldtime = File.stat(oldname).mtime.to_i
- newtime = File.stat(newname).mtime.to_i
- if newtime >= oldtime then
- return false
- elsif oldtime-newtime < @@update_eps then
- return false
- else
- return true
- end
- rescue
- return true
- end
- end
-
- def File.syncmtimes(oldname,newname)
- return
- begin
- if $mswindows then
- # does not work (yet) / gives future timestamp
- # t = File.mtime(oldname) # i'm not sure if the time is frozen, so we do it here
- # File.utime(0,t,oldname,newname)
- else
- t = File.mtime(oldname) # i'm not sure if the time is frozen, so we do it here
- File.utime(0,t,oldname,newname)
- end
- rescue
- end
- end
-
- def File.timestamp(name)
- begin
- "#{File.stat(name).mtime}"
- rescue
- return 'unknown'
- end
- end
-
-end
-
-def hashed (arr=[])
- arg = if arr.class == String then arr.split(' ') else arr.dup end
- hsh = Hash.new
- if arg.length > 0
- hsh['arguments'] = ''
- done = false
- arg.each do |s|
- if done then
- if s =~ /\s/ then
- kvl = s.split('=')
- if kvl[1] and kvl[1] !~ /^[\"\']/ then
- hsh['arguments'] += ' ' + kvl[0] + "=" + '"' + kvl[1] + '"'
- elsif s =~ /\s/ then
- hsh['arguments'] += ' "' + s + '"'
- else
- hsh['arguments'] += ' ' + s
- end
- else
- hsh['arguments'] += ' ' + s
- end
- else
- kvl = s.split('=')
- if kvl[0].sub!(/^\-+/,'') then
- hsh[kvl[0]] = if kvl.length > 1 then kvl[1] else true end
- else
- hsh['file'] = s
- done = true
- end
- end
- end
- end
- return hsh
-end
-
-
-def launch(filename)
- if $browser && $mswindows then
- filename = filename.gsub(/\.[\/\\]/) do
- Dir.getwd + '/'
- end
- report("launching #{filename}")
- ie = WIN32OLE.new("InternetExplorer.Application")
- ie.visible = true
- ie.navigate(filename)
- return true
- else
- return false
- end
-end
-
-# env|environment
-# rel|relative
-# loc|locate|kpse|path|file
-
-def quoted(str)
- if str =~ /^\"/ then
- return str
- elsif str =~ / / then
- return "\"#{str}\""
- else
- return str
- end
-end
-
-def expanded(arg) # no "other text files", too restricted
- arg.gsub(/(env|environment)\:([a-zA-Z\-\_\.0-9]+)/o) do
- method, original, resolved = $1, $2, ''
- if resolved = ENV[original] then
- report("environment variable #{original} expands to #{resolved}") unless $report
- quoted(resolved)
- else
- report("environment variable #{original} cannot be resolved") unless $report
- quoted(original)
- end
- end . gsub(/(rel|relative)\:([a-zA-Z\-\_\.0-9]+)/o) do
- method, original, resolved = $1, $2, ''
- ['.','..','../..'].each do |r|
- if FileTest.file?(File.join(r,original)) then
- resolved = File.join(r,original)
- break
- end
- end
- if resolved.empty? then
- quoted(original)
- else
- quoted(resolved)
- end
- end . gsub(/(kpse|loc|locate|file|path)\:([a-zA-Z\-\_\.0-9]+)/o) do
- method, original, resolved = $1, $2, ''
- if $program && ! $program.empty? then
- # pstrings = ["-progname=#{$program}"]
- pstrings = [$program]
- else
- # pstrings = ['','-progname=context']
- pstrings = ['','context']
- end
- # auto suffix with texinputs as fall back
- if ENV["_CTX_K_V_#{original}_"] then
- resolved = ENV["_CTX_K_V_#{original}_"]
- report("environment provides #{original} as #{resolved}") unless $report
- quoted(resolved)
- else
- check_kpse
- pstrings.each do |pstr|
- if resolved.empty? then
- # command = "kpsewhich #{pstr} #{original}"
- # report("running #{command}")
- report("locating '#{original}' in program space '#{pstr}'")
- begin
- # resolved = `#{command}`.chomp
- $kpse.progname = pstr
- $kpse.format = ''
- resolved = $kpse.find_file(original).gsub(/\\/,'/')
- rescue
- resolved = ''
- end
- end
- # elsewhere in the tree
- if resolved.empty? then
- # command = "kpsewhich #{pstr} -format=\"other text files\" #{original}"
- # report("running #{command}")
- report("locating '#{original}' in program space '#{pstr}' using format 'other text files'")
- begin
- # resolved = `#{command}`.chomp
- $kpse.progname = pstr
- $kpse.format = 'other text files'
- resolved = $kpse.find_file(original).gsub(/\\/,'/')
- rescue
- resolved = ''
- end
- end
- end
- if resolved.empty? then
- original = File.dirname(original) if method =~ /path/
- report("#{original} is not resolved") unless $report
- ENV["_CTX_K_V_#{original}_"] = original if $crossover
- quoted(original)
- else
- resolved = File.dirname(resolved) if method =~ /path/
- report("#{original} is resolved to #{resolved}") unless $report
- ENV["_CTX_K_V_#{original}_"] = resolved if $crossover
- quoted(resolved)
- end
- end
- end
-end
-
-def changeddir?(path)
- if path.empty? then
- return true
- else
- oldpath = File.expand_path(path)
- begin
- Dir.chdir(path) if not path.empty?
- rescue
- report("unable to change to directory: #{path}")
- else
- report("changed to directory: #{path}")
- end
- newpath = File.expand_path(Dir.getwd)
- return oldpath == newpath
- end
-end
-
-def runcommand(command)
- if $locate then
- command = command.split(' ').collect do |c|
- if c =~ /\//o then
- begin
- cc = File.expand_path(c)
- c = cc if FileTest.file?(cc)
- rescue
- end
- end
- c
- end . join(' ')
- print command # to stdout and no newline
- elsif $execute then
- report("using 'exec' instead of 'system' call: #{command}")
- exec(command) if changeddir?($path)
- else
- report("using 'system' call: #{command}")
- system(command) if changeddir?($path)
- end
-end
-
-def join_command(args)
- args[0] = $runners[args[0]] || args[0]
- [args].join(' ')
-end
-
-def runoneof(application,fullname,browserpermitted)
- if browserpermitted && launch(fullname) then
- return true
- else
- fullname = quoted(fullname) # added because MM ran into problems
- report("starting #{$filename}") unless $report
- output("\n") if $report && $verbose
- applications = $applications[application.downcase]
- if ! applications then
- output("problems with determining application type")
- return true
- elsif applications.class == Array then
- if $report then
- output(join_command([fullname,expanded($arguments)]))
- return true
- else
- applications.each do |a|
- return true if runcommand(join_command([a,fullname,expanded($arguments)]))
- end
- end
- elsif applications.empty? then
- if $report then
- output(join_command([fullname,expanded($arguments)]))
- return true
- else
- return runcommand(join_command([fullname,expanded($arguments)]))
- end
- else
- if $report then
- output(join_command([applications,fullname,expanded($arguments)]))
- return true
- else
- return runcommand(join_command([applications,fullname,expanded($arguments)]))
- end
- end
- return false
- end
-end
-
-def report(str)
- $stdout.puts(str) if $verbose
-end
-
-def output(str)
- $stdout.puts(str)
-end
-
-def usage
- print "version : #{$version} - 2003/2006 - www.pragma-ade.com\n"
- print("\n")
- print("usage : texmfstart [switches] filename [optional arguments]\n")
- print("\n")
- print("switches : --verbose --report --browser --direct --execute --locate --iftouched --ifchanged\n")
- print(" --program --file --page --arguments --batch --edit --report --clear\n")
- print(" --make --lmake --wmake --path --stubpath --indirect --before --after\n")
- print(" --tree --autotree --environment --showenv\n")
- print("\n")
- print("example : texmfstart pstopdf.rb cow.eps\n")
- print(" texmfstart --locate examplex.rb\n")
- print(" texmfstart --execute examplex.rb\n")
- print(" texmfstart --browser examplap.pdf\n")
- print(" texmfstart showcase.pdf\n")
- print(" texmfstart --page=2 --file=showcase.pdf\n")
- print(" texmfstart --program=yourtex yourscript.rb arg-1 arg-2\n")
- print(" texmfstart --direct xsltproc kpse:somefile.xsl somefile.xml\n")
- print(" texmfstart --direct ruby rel:wn-cleanup-1.rb oldfile.xml newfile.xml\n")
- print(" texmfstart bin:xsltproc env:somepreset path:somefile.xsl somefile.xml\n")
- print(" texmfstart --iftouched=normal,lowres downsample.rb normal lowres\n")
- print(" texmfstart --ifchanged=somefile.dat --direct processit somefile.dat\n")
- print(" texmfstart bin:scite kpse:texmf.cnf\n")
- print(" texmfstart --exec bin:scite *.tex\n")
- print(" texmfstart --edit texmf.cnf\n")
- print(" texmfstart --edit kpse:texmf.cnf\n")
- print(" texmfstart --serve\n")
- print("\n")
- print(" texmfstart --stubpath=/usr/local/bin [--make --remove] --verbose all\n")
- print(" texmfstart --stubpath=auto [--make --remove] all\n")
- print("\n")
- check_kpse
-end
-
-# somehow registration does not work out (at least not under windows)
-# the . is also not accepted by unix as seperator
-
-def tag(name)
- if $crossover then "_CTX_K_S_#{name}_" else "TEXMFSTART.#{name}" end
-end
-
-def registered?(filename)
- return ENV[tag(filename)] != nil
-end
-
-def registered(filename)
- return ENV[tag(filename)] || 'unknown'
-end
-
-def register(filename,fullname)
- if fullname && ! fullname.empty? then # && FileTest.file?(fullname)
- ENV[tag(filename)] = fullname
- report("registering '#{filename}' as '#{fullname}'")
- return true
- else
- return false
- end
-end
-
-def find(filename,program)
- begin
- filename = filename.sub(/script:/o, '') # so we have bin: and script: and nothing
- if $predefined.key?(filename) then
- report("expanding '#{filename}' to '#{$predefined[filename]}'")
- filename = $predefined[filename]
- end
- if registered?(filename) then
- report("already located '#{filename}'")
- return registered(filename)
- end
- # create suffix list
- if filename =~ /^(.*)\.(.+)$/ then
- filename = $1
- suffixlist = [$2]
- else
- suffixlist = [$scriptlist.split('|'),$documentlist.split('|')].flatten
- end
- # first we honor a given path
- if filename =~ /[\\\/]/ then
- report("trying to honor '#{filename}'")
- suffixlist.each do |suffix|
- fullname = filename+'.'+suffix
- if FileTest.file?(fullname) && register(filename,fullname)
- return shortpathname(fullname)
- end
- end
- end
- filename.sub!(/^.*[\\\/]/, '')
- # next we look at the current path and the callerpath
- pathlist = [ ]
- progpath = $applications[suffixlist[0]]
- threadok = registered("THREAD") !~ /unknown/
- pathlist << ['.','current']
- pathlist << [$ownpath,'caller'] if $ownpath != '.'
- pathlist << ["#{$ownpath}/../#{progpath}",'caller'] if progpath
- pathlist << [registered("THREAD"),'thread'] if threadok
- pathlist << ["#{registered("THREAD")}/../#{progpath}",'thread'] if progpath && threadok
- pathlist.each do |p|
- if p && ! p.empty? && ! (p[0] == 'unknown') then
- suffixlist.each do |suffix|
- fname = "#{filename}.#{suffix}"
- fullname = File.expand_path(File.join(p[0],fname))
- report("locating '#{fname}' in #{p[1]} path '#{p[0]}'")
- if FileTest.file?(fullname) && register(filename,fullname) then
- report("'#{fname}' located in #{p[1]} path")
- return shortpathname(fullname)
- end
- end
- end
- end
- # now we consult environment settings
- fullname = nil
- check_kpse
- $kpse.progname = program
- suffixlist.each do |suffix|
- begin
- break unless $suffixinputs[suffix]
- environment = ENV[$suffixinputs[suffix]] || ENV[$suffixinputs[suffix]+".#{$program}"]
- if ! environment || environment.empty? then
- begin
- # environment = `kpsewhich -expand-path=\$#{$suffixinputs[suffix]}`.chomp
- environment = $kpse.expand_path("\$#{$suffixinputs[suffix]}")
- rescue
- environment = nil
- else
- if environment && ! environment.empty? then
- report("using kpsewhich variable #{$suffixinputs[suffix]}")
- end
- end
- elsif environment && ! environment.empty? then
- report("using environment variable #{$suffixinputs[suffix]}")
- end
- if environment && ! environment.empty? then
- environment.split($separator).each do |e|
- e.strip!
- e = '.' if e == '\.' # somehow . gets escaped
- e += '/' unless e =~ /[\\\/]$/
- fullname = e + filename + '.' + suffix
- report("testing '#{fullname}'")
- if FileTest.file?(fullname) then
- break
- else
- fullname = nil
- end
- end
- end
- rescue
- report("environment string '#{$suffixinputs[suffix]}' cannot be used to locate '#{filename}'")
- fullname = nil
- else
- return shortpathname(fullname) if register(filename,fullname)
- end
- end
- return shortpathname(fullname) if register(filename,fullname)
- # then we fall back on kpsewhich
- suffixlist.each do |suffix|
- # TDS script scripts location as per 2004
- if suffix =~ /(#{$scriptlist})/ then
- begin
- report("using 'kpsewhich' to locate '#{filename}' in suffix space '#{suffix}' (1)")
- # fullname = `kpsewhich -progname=#{program} -format=texmfscripts #{filename}.#{suffix}`.chomp
- $kpse.format = 'texmfscripts'
- fullname = $kpse.find_file("#{filename}.#{suffix}").gsub(/\\/,'/')
- rescue
- report("kpsewhich cannot locate '#{filename}' in suffix space '#{suffix}' (1)")
- fullname = nil
- else
- return shortpathname(fullname) if register(filename,fullname)
- end
- end
- # old TDS location: .../texmf/context/...
- begin
- report("using 'kpsewhich' to locate '#{filename}' in suffix space '#{suffix}' (2)")
- # fullname = `kpsewhich -progname=#{program} -format="other text files" #{filename}.#{suffix}`.chomp
- $kpse.format = 'other text files'
- fullname = $kpse.find_file("#{filename}.#{suffix}").gsub(/\\/,'/')
- rescue
- report("kpsewhich cannot locate '#{filename}' in suffix space '#{suffix}' (2)")
- fullname = nil
- else
- return shortpathname(fullname) if register(filename,fullname)
- end
- end
- return shortpathname(fullname) if register(filename,fullname)
- # let's take a look at the path
- paths = ENV['PATH'].split($separator)
- suffixlist.each do |s|
- paths.each do |p|
- suffixedname = "#{filename}.#{s}"
- report("checking #{p} for #{filename}")
- if FileTest.file?(File.join(p,suffixedname)) then
- fullname = File.join(p,suffixedname)
- return shortpathname(fullname) if register(filename,fullname)
- end
- end
- end
- # bad luck, we need to search the tree ourselves
- if (suffixlist.length == 1) && (suffixlist.first =~ /(#{$documentlist})/) then
- report("aggressively locating '#{filename}' in document trees")
- begin
- # texroot = `kpsewhich -expand-var=$SELFAUTOPARENT`.chomp
- texroot = $kpse.expand_var("$SELFAUTOPARENT")
- rescue
- texroot = ''
- else
- texroot.sub!(/[\\\/][^\\\/]*?$/, '')
- end
- if not texroot.empty? then
- sffxlst = suffixlist.join(',')
- begin
- report("locating '#{filename}' in document tree '#{texroot}/doc*'")
- if (result = Dir.glob("#{texroot}/doc*/**/#{filename}.{#{sffxlst}}")) && result && result[0] && FileTest.file?(result[0]) then
- fullname = result[0]
- end
- rescue
- report("locating '#{filename}.#{suffixlist.join('|')}' in tree '#{texroot}' aborted")
- end
- end
- return shortpathname(fullname) if register(filename,fullname)
- end
- report("aggressively locating '#{filename}' in tex trees")
- begin
- # textrees = `kpsewhich -expand-var=$TEXMF`.chomp
- textrees = $kpse.expand_var("$TEXMF")
- rescue
- textrees = ''
- end
- if not textrees.empty? then
- textrees.gsub!(/[\{\}\!]/, '')
- textrees = textrees.split(',')
- if (suffixlist.length == 1) && (suffixlist.first =~ /(#{$documentlist})/) then
- speedup = ['doc**','**']
- else
- speedup = ['**']
- end
- sffxlst = suffixlist.join(',')
- speedup.each do |speed|
- textrees.each do |tt|
- tt.gsub!(/[\\\/]$/, '')
- if FileTest.directory?(tt) then
- begin
- report("locating '#{filename}' in tree '#{tt}/#{speed}/#{filename}.{#{sffxlst}}'")
- if (result = Dir.glob("#{tt}/#{speed}/#{filename}.{#{sffxlst}}")) && result && result[0] && FileTest.file?(result[0]) then
- fullname = result[0]
- break
- end
- rescue
- report("locating '#{filename}' in tree '#{tt}' aborted")
- next
- end
- end
- end
- break if fullname && ! fullname.empty?
- end
- end
- if register(filename,fullname) then
- return shortpathname(fullname)
- else
- return ''
- end
- rescue
- error, trace = $!, $@.join("\n")
- report("fatal error: #{error}\n#{trace}")
- # report("fatal error")
- end
-end
-
-def run(fullname)
- if ! fullname || fullname.empty? then
- output("the file '#{$filename}' is not found")
- elsif FileTest.file?(fullname) then
- begin
- case fullname
- when /\.(#{$scriptlist})$/i then
- return runoneof($1,fullname,false)
- when /\.(#{$documentlist})$/i then
- return runoneof($1,fullname,true)
- else
- return runoneof('unknown',fullname,false)
- end
- rescue
- report("starting '#{$filename}' in program space '#{$program}' fails (#{$!})")
- end
- else
- report("the file '#{$filename}' in program space '#{$program}' is not accessible")
- end
- return false
-end
-
-def direct(fullname)
- begin
- return runcommand([fullname.sub(/^(bin|binary)\:/, ''),expanded($arguments)].join(' '))
- rescue
- return false
- end
-end
-
-def edit(filename)
- begin
- return runcommand([$editor,expanded(filename),expanded($arguments)].join(' '))
- rescue
- return false
- end
-end
-
-def make(filename,windows=false,linux=false,remove=false)
- basename = File.basename(filename).gsub(/\.[^.]+?$/, '')
- if $stubpath == 'auto' then
- basename = File.dirname($0) + '/' + basename
- else
- basename = $stubpath + '/' + basename unless $stubpath.empty?
- end
- if filename == 'texmfstart' then
- program = 'ruby'
- command = 'kpsewhich --format=texmfscripts --progname=context texmfstart.rb'
- filename = `#{command}`.chomp.gsub(/\\/, '/')
- if filename.empty? then
- report("failure: #{command}")
- return
- elsif not remove then
- if windows then
- ['bat','cmd','exe'].each do |suffix|
- if FileTest.file?("#{basename}.#{suffix}") then
- report("windows stub '#{basename}.#{suffix}' skipped (already present)")
- return
- end
- end
- elsif linux && FileTest.file?(basename) then
- report("unix stub '#{basename}' skipped (already present)")
- return
- end
- end
- else
- program = nil
- if filename =~ /[\\\/]/ && filename =~ /\.(#{$scriptlist})$/ then
- program = $applications[$1]
- end
- filename = "\"#{filename}\"" if filename =~ /\s/
- program = 'texmfstart' if $indirect || ! program || program.empty?
- end
- begin
- callname = $predefined[filename.sub(/\.*?$/,'')] || filename
- if remove then
- if windows && (File.delete(basename+'.bat') rescue false) then
- report("windows stub '#{basename}.bat' removed (calls #{callname})")
- elsif linux && (File.delete(basename) rescue false) then
- report("unix stub '#{basename}' removed (calls #{callname})")
- end
- else
- if windows && f = open(basename+'.bat','w') then
- f.binmode
- f.write("@echo off\015\012")
- f.write("#{program} #{callname} %*\015\012")
- f.close
- report("windows stub '#{basename}.bat' made (calls #{callname})")
- elsif linux && f = open(basename,'w') then
- f.binmode
- f.write("#!/bin/sh\012")
- f.write("#{program} #{callname} \"$@\"\012")
- f.close
- report("unix stub '#{basename}' made (calls #{callname})")
- end
- end
- rescue
- report("failed to make stub '#{basename}' #{$!}")
- return false
- else
- return true
- end
-end
-
-def process(&block)
- if $iftouched then
- files = $directives['iftouched'].split(',')
- oldname, newname = files[0], files[1]
- if oldname && newname && File.needsupdate(oldname,newname) then
- report("file #{oldname}: #{File.timestamp(oldname)}")
- report("file #{newname}: #{File.timestamp(newname)}")
- report("file is touched, processing started")
- yield
- File.syncmtimes(oldname,newname)
- else
- report("file #{oldname} is untouched")
- end
- elsif $ifchanged then
- filename = $directives['ifchanged']
- checkname = filename + ".md5"
- oldchecksum, newchecksum = "old", "new"
- begin
- newchecksum = Digest::MD5.hexdigest(IO.read(filename)).upcase
- rescue
- newchecksum = "new"
- else
- begin
- oldchecksum = IO.read(checkname).chomp
- rescue
- oldchecksum = "old"
- end
- end
- if $verbose then
- report("old checksum #{filename}: #{oldchecksum}")
- report("new checksum #{filename}: #{newchecksum}")
- end
- if oldchecksum != newchecksum then
- report("file is changed, processing started")
- begin
- File.open(checkname,'w') do |f|
- f << newchecksum
- end
- rescue
- end
- yield
- else
- report("file #{filename} is unchanged")
- end
- else
- yield
- end
-end
-
-def checkenvironment(tree)
- report('')
- ENV['TMP'] = ENV['TMP'] || ENV['TEMP'] || ENV['TMPDIR'] || ENV['HOME']
- case RUBY_PLATFORM
- when /(mswin|bccwin|mingw|cygwin)/i then ENV['TEXOS'] = ENV['TEXOS'] || 'texmf-mswin'
- when /(linux)/i then ENV['TEXOS'] = ENV['TEXOS'] || 'texmf-linux'
- when /(darwin|rhapsody|nextstep)/i then ENV['TEXOS'] = ENV['TEXOS'] || 'texmf-macosx'
- # when /(netbsd|unix)/i then # todo
- else # todo
- end
- ENV['TEXOS'] = "#{ENV['TEXOS'].sub(/^[\\\/]*/, '').sub(/[\\\/]*$/, '')}"
- ENV['TEXPATH'] = tree.sub(/\/+$/,'') # + '/'
- ENV['TEXMFOS'] = "#{ENV['TEXPATH']}/#{ENV['TEXOS']}"
- report('')
- report("preset : TEXPATH => #{ENV['TEXPATH']}")
- report("preset : TEXOS => #{ENV['TEXOS']}")
- report("preset : TEXMFOS => #{ENV['TEXMFOS']}")
- report("preset : TMP => #{ENV['TMP']}")
- report('')
-end
-
-def loadfile(filename)
- begin
- IO.readlines(filename).each do |line|
- case line.chomp
- when /^[\#\%]/ then
- # comment
- when /^(.*?)\s*(\>|\=|\<)\s*(.*)\s*$/ then
- # = assign | > prepend | < append
- key, how, value = $1, $2, $3
- begin
- # $SAFE = 0
- value.gsub!(/\%(.*?)\%/) do
- ENV[$1] || ''
- end
- # value.gsub!(/\;/,$separator) if key =~ /PATH/i then
- case how
- when '=', '<<' then ENV[key] = value
- when '?', '??' then ENV[key] = ENV[key] || value
- when '<', '+=' then ENV[key] = (ENV[key] || '') + $separator + value
- when '>', '=+' then ENV[key] = value + $separator + (ENV[key] ||'')
- end
- rescue
- report("user set failed : #{key} (#{$!})")
- else
- report("user set : #{key} => #{ENV[key]}")
- end
- end
- end
- rescue
- report("error in reading file '#{filename}'")
- end
-end
-
-def loadtree(tree)
- begin
- unless tree.empty? then
- if File.directory?(tree) then
- setuptex = File.join(tree,'setuptex.tmf')
- else
- setuptex = tree.dup
- end
- if FileTest.file?(setuptex) then
- report("tex tree definition: #{setuptex}")
- checkenvironment(File.dirname(setuptex))
- loadfile(setuptex)
- else
- report("no setup file '#{setuptex}'")
- end
- end
- rescue
- # maybe tree is empty or boolean (no arg given)
- end
-end
-
-def loadenvironment(environment)
- begin
- unless environment.empty? then
- filename = if $path.empty? then environment else File.expand_path(File.join($path,environment)) end
- if FileTest.file?(filename) then
- report("environment : #{environment}")
- loadfile(filename)
- else
- report("no environment file '#{environment}'")
- end
- end
- rescue
- report("problem while loading '#{environment}'")
- end
-end
-
-def show_environment
- if $showenv then
- keys = ENV.keys.sort
- size = 0
- keys.each do |k|
- size = k.size if k.size > size
- end
- report('')
- keys.each do |k|
- report("#{k.rjust(size)} => #{ENV[k]}")
- end
- report('')
- end
-end
-
-def execute(arguments) # br global
-
- arguments = arguments.split(/\s+/) if arguments.class == String
- $directives = hashed(arguments)
-
- $help = $directives['help'] || false
- $batch = $directives['batch'] || false
- $filename = $directives['file'] || ''
- $program = $directives['program'] || 'context'
- $direct = $directives['direct'] || false
- $edit = $directives['edit'] || false
- $page = $directives['page'] || 1
- $browser = $directives['browser'] || false
- $report = $directives['report'] || false
- $verbose = $directives['verbose'] || false
- $arguments = $directives['arguments'] || ''
- $execute = $directives['execute'] || $directives['exec'] || false
- $locate = $directives['locate'] || false
-
- $autotree = if $directives['autotree'] then (ENV['TEXMFSTART_TREE'] || ENV['TEXMFSTARTTREE'] || '') else '' end
-
- $path = $directives['path'] || ''
- $tree = $directives['tree'] || $autotree || ''
- $environment = $directives['environment'] || ''
-
- $make = $directives['make'] || false
- $remove = $directives['remove'] || $directives['delete'] || false
- $unix = $directives['unix'] || false
- $windows = $directives['windows'] || $directives['mswin'] || false
- $stubpath = $directives['stubpath'] || ''
- $indirect = $directives['indirect'] || false
-
- $before = $directives['before'] || ''
- $after = $directives['after'] || ''
-
- $iftouched = $directives['iftouched'] || false
- $ifchanged = $directives['ifchanged'] || false
-
- $openoffice = $directives['oo'] || false
-
- $crossover = false if $directives['clear']
-
- $showenv = $directives['showenv'] || false
- $verbose = true if $showenv
-
- $serve = $directives['serve'] || false
-
- $verbose = true if (ENV['_CTX_VERBOSE_'] =~ /(y|yes|t|true|on)/io) && ! $locate && ! $report
-
- set_applications($page)
-
- # private:
-
- $selfmerge = $directives['selfmerge'] || false
- $selfcleanup = $directives['selfclean'] || $directives['selfcleanup'] || false
-
- ENV['_CTX_VERBOSE_'] = 'yes' if $verbose
-
- if $openoffice then
- if ENV['OOPATH'] then
- if FileTest.directory?(ENV['OOPATH']) then
- report("using open office python")
- if $mswindows then
- $applications['python'] = $applications['py'] = "\"#{File.join(ENV['OOPATH'],'program','python.bat')}\""
- else
- $applications['python'] = $applications['py'] = File.join(ENV['OOPATH'],'python')
- end
- report("python path #{$applications['python']}")
- else
- report("environment variable 'OOPATH' does not exist")
- end
- else
- report("environment variable 'OOPATH' is not set")
- end
- end
-
- if $selfmerge then
- output("ruby libraries are cleaned up") if SelfMerge::cleanup
- output("ruby libraries are merged") if SelfMerge::merge
- return true
- elsif $selfcleanup then
- output("ruby libraries are cleaned up") if SelfMerge::cleanup
- return true
- elsif $help || ! $filename || $filename.empty? then
- usage
- loadtree($tree)
- loadenvironment($environment)
- show_environment()
- return true
- elsif $batch && $filename && ! $filename.empty? then
- # todo, take commands from file and avoid multiple starts and checks
- return false
- else
- report("texmfstart version #{$version}")
- loadtree($tree)
- loadenvironment($environment)
- show_environment()
- if $make || $remove then
- if $filename == 'all' then
- makelist = $makelist
- else
- makelist = [$filename]
- end
- makelist.each do |filename|
- if $windows then
- make(filename,true,false,$remove)
- elsif $unix then
- make(filename,false,true,$remove)
- else
- make(filename,$mswindows,!$mswindows,$remove)
- end
- end
- return true # guess
- elsif $browser && $filename =~ /^http\:\/\// then
- return launch($filename)
- else
- begin
- process do
- if $direct || $filename =~ /^bin\:/ then
- return direct($filename)
- elsif $edit && ! $editor.empty? then
- return edit($filename)
- else # script: or no prefix
- command = find(shortpathname($filename),$program)
- if command then
- register("THREAD",File.dirname(File.expand_path(command)))
- return run(command)
- else
- report('unable to locate program')
- return false
- end
- end
- end
- rescue
- report('fatal error in starting process')
- return false
- end
- end
- end
-
-end
-
-if execute(ARGV) then
- report("\nexecution was successful") if $verbose
- exit(0)
-else
- report("\nexecution failed") if $verbose
- exit(1)
-end
diff --git a/Master/texmf-dist/scripts/context/ruby/textools.rb b/Master/texmf-dist/scripts/context/ruby/textools.rb
deleted file mode 100644
index a5858c5caf5..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/textools.rb
+++ /dev/null
@@ -1,1033 +0,0 @@
-#!/usr/bin/env ruby
-
-# program : textools
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# This script will harbor some handy manipulations on tex
-# related files.
-
-banner = ['TeXTools', 'version 1.3.1', '2002/2006', 'PRAGMA ADE/POD']
-
-$: << File.expand_path(File.dirname($0)) ; $: << File.join($:.last,'lib') ; $:.uniq!
-
-require 'base/switch'
-require 'base/logger'
-
-require 'fileutils'
-# require 'ftools'
-
-# Remark
-#
-# The fixtexmftrees feature does not realy belong in textools, but
-# since it looks like no measures will be taken to make texlive (and
-# tetex) downward compatible with respect to fonts installed by
-# users, we provide this fixer. This option also moves script files
-# to their new location (only for context) in the TDS. Beware: when
-# locating scripts, the --format switch in kpsewhich should now use
-# 'texmfscripts' instead of 'other text files' (texmfstart is already
-# aware of this). Files will only be moved when --force is given. Let
-# me know if more fixes need to be made.
-
-class Commands
-
- include CommandBase
-
- def tpmmake
- if filename = @commandline.argument('first') then
- filename = File.join('tpm',filename) unless filename =~ /^tpm[\/\\]/
- filename += '.tpm' unless filename =~ /\.tpm$/
- if FileTest.file?(filename) then
- data = IO.read(filename) rescue ''
- data, fn, n = calculate_tpm(data,"TPM:RunFiles")
- data, fm, m = calculate_tpm(data,"TPM:DocFiles")
- data = replace_tpm(data,"TPM:Size",n+m)
- report("total size #{n+m}")
- begin
- File.open(filename, 'w') do |f|
- f << data
- end
- rescue
- report("unable to save '#{filename}'")
- else
- report("file '#{filename}' is updated")
- filename = File.basename(filename).sub(/\..*$/,'')
- zipname = sprintf("%s-%04i.%02i.%02i%s",filename,Time.now.year,Time.now.month,Time.now.day,'.zip')
- File.delete(zipname) rescue true
- report("zipping file '#{zipname}'")
- system("zip -r -9 -q #{zipname} #{[fn,fm].flatten.join(' ')}")
- end
- else
- report("no file '#{filename}'")
- end
- end
- end
-
- def calculate_tpm(data, tag='')
- size, ok = 0, Array.new
- data.gsub!(/<#{tag}.*>(.*?)<\/#{tag}>/m) do
- content = $1
- files = content.split(/\s+/)
- files.each do |file|
- unless file =~ /^\s*$/ then
- if FileTest.file?(file) then
- report("found file #{file}")
- size += FileTest.size(file) rescue 0
- ok << file
- else
- report("missing file #{file}")
- end
- end
- end
- "<#{tag} size=\"#{size}\">#{content}</#{tag}>"
- end
- [data, ok, size]
- end
-
- def replace_tpm(data, tag='', txt='')
- data.gsub(/(<#{tag}.*>)(.*?)(<\/#{tag}>)/m) do
- $1 + txt.to_s + $3
- end
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- def hidemapnames
- report('hiding FontNames in map files')
- xidemapnames(true)
- end
-
- def videmapnames
- report('unhiding FontNames in map files')
- xidemapnames(false)
- end
-
- def removemapnames
-
- report('removing FontNames from map files')
-
- if files = findfiles('map') then
- report
- files.sort.each do |fn|
- gn = fn # + '.nonames'
- hn = fn + '.original'
- begin
- if FileTest.file?(fn) && ! FileTest.file?(hn) then
- if File.rename(fn,hn) then
- if (fh = File.open(hn,'r')) && (gh = File.open(gn,'w')) then
- report("processing #{fn}")
- while str = fh.gets do
- str.sub!(/^([^\%]+?)(\s+)([^\"\<\s]*?)(\s)/) do
- $1 + $2 + " "*$3.length + $4
- end
- gh.puts(str)
- end
- fh.close
- gh.close
- else
- report("no permissions to handle #{fn}")
- end
- else
- report("unable to rename #{fn} to #{hn}")
- end
- else
- report("not processing #{fn} due to presence of #{hn}")
- end
- rescue
- report("error in handling #{fn}")
- end
- end
- end
-
- end
-
- def restoremapnames
-
- report('restoring FontNames in map files')
-
- if files = findfiles('map') then
- report
- files.sort.each do |fn|
- hn = fn + '.original'
- begin
- if FileTest.file?(hn) then
- File.delete(fn) if FileTest.file?(fn)
- report("#{fn} restored") if File.rename(hn,fn)
- else
- report("no original found for #{fn}")
- end
- rescue
- report("error in restoring #{fn}")
- end
- end
- end
-
- end
-
- def findfile
-
- report('locating file in texmf tree')
-
- # ! not in tree
- # ? fuzzy
- # . in tree
- # > in tree and used
-
- if filename = @commandline.argument('first') then
- if filename && ! filename.empty? then
- report
- used = kpsefile(filename) || pathfile(filename)
- if paths = texmfroots then
- found, prefered = false, false
- paths.each do |p|
- if files = texmffiles(p,filename) then
- found = true
- files.each do |f|
- # unreadable: report("#{if f == used then '>' else '.' end} #{f}")
- if f == used then
- prefered = true
- report("> #{f}")
- else
- report(". #{f}")
- end
- end
- end
- end
- if prefered then
- report("! #{used}") unless found
- else
- report("> #{used}")
- end
- elsif used then
- report("? #{used}")
- else
- report('no file found')
- end
- else
- report('no file specified')
- end
- else
- report('no file specified')
- end
-
- end
-
- def unzipfiles
-
- report('g-unzipping files')
-
- if files = findfiles('gz') then
- report
- files.each do |f|
- begin
- system("gunzip -d #{f}")
- rescue
- report("unable to unzip file #{f}")
- else
- report("file #{f} is unzipped")
- end
- end
- end
-
- end
-
- def fixafmfiles
-
- report('fixing afm files')
-
- if files = findfiles('afm') then
- report
- ok = false
- files.each do |filename|
- if filename =~ /\.afm$/io then
- if f = File.open(filename) then
- result = ''
- done = false
- while str = f.gets do
- str.chomp!
- str.strip!
- if str.empty? then
- # skip
- elsif (str.length > 200) && (str =~ /^(comment|notice)\s(.*)\s*$/io) then
- done = true
- tag, words, len = $1, $2.split(' '), 0
- result += tag
- while words.size > 0 do
- str = words.shift
- len += str.length + 1
- result += ' ' + str
- if len > (70 - tag.length) then
- result += "\n"
- result += tag if words.size > 0
- len = 0
- end
- end
- result += "\n" if len>0
- else
- result += str + "\n"
- end
- end
- f.close
- if done then
- ok = true
- begin
- if File.rename(filename,filename+'.original') then
- if FileTest.file?(filename) then
- report("something to fix in #{filename} but error in renaming (3)")
- elsif f = File.open(filename,'w') then
- f.puts(result)
- f.close
- report('file', filename, 'has been fixed')
- else
- report("something to fix in #{filename} but error in opening (4)")
- File.rename(filename+'.original',filename) # gamble
- end
- else
- report("something to fix in #{filename} but error in renaming (2)")
- end
- rescue
- report("something to fix in #{filename} but error in renaming (1)")
- end
- else
- report("nothing to fix in #{filename}")
- end
- else
- report("error in opening #{filename}")
- end
- end
- end
- report('no files match the pattern') unless ok
- end
-
- end
-
- def mactodos
-
- report('fixing mac newlines')
-
- if files = findfiles('tex') then
- report
- files.each do |filename|
- begin
- report("converting file #{filename}")
- tmpfilename = filename + '.tmp'
- if f = File.open(filename) then
- if g = File.open(tmpfilename, 'w')
- while str = f.gets do
- g.puts(str.gsub(/\r/,"\n"))
- end
- if f.close && g.close && FileTest.file?(tmpfilename) then
- File.delete(filename)
- File.rename(tmpfilename,filename)
- end
- else
- report("unable to open temporary file #{tmpfilename}")
- end
- else
- report("unable to open #{filename}")
- end
- rescue
- report("problems with fixing #{filename}")
- end
- end
- end
-
- end
-
- def fixtexmftrees
-
- if paths = @commandline.argument('first') then
- paths = [paths] if ! paths.empty?
- end
- paths = texmfroots if paths.empty?
-
- if paths then
-
- moved = 0
- force = @commandline.option('force')
-
- report
- report("checking TDS 2003 => TDS 2004 : map files")
- # report
-
- # move [map,enc] files from /texmf/[dvips,pdftex,dvipdfmx] -> /texmf/fonts/[*]
-
- ['map','enc'].each do |suffix|
- paths.each do |path|
- ['dvips','pdftex','dvipdfmx'].each do |program|
- report
- report("checking #{suffix} files for #{program} on #{path}")
- report
- moved += movefiles("#{path}/#{program}","#{path}/fonts/#{suffix}/#{program}",suffix) do
- # nothing
- end
- end
- end
- end
-
- report
- report("checking TDS 2003 => TDS 2004 : scripts")
- # report
-
- # move [rb,pl,py] files from /texmf/someplace -> /texmf/scripts/someplace
-
- ['rb','pl','py'].each do |suffix|
- paths.each do |path|
- ['context'].each do |program|
- report
- report("checking #{suffix} files for #{program} on #{path}")
- report
- moved += movefiles("#{path}/#{program}","#{path}/scripts/#{program}",suffix) do |f|
- f.gsub!(/\/(perl|ruby|python)tk\//o) do
- "/#{$1}/"
- end
- end
- end
- end
- end
-
- begin
- if moved>0 then
- report
- if force then
- system('mktexlsr')
- report
- report("#{moved} files moved")
- else
- report("#{moved} files will be moved")
- end
- else
- report('no files need to be moved')
- end
- rescue
- report('you need to run mktexlsr')
- end
-
- end
-
- end
-
- def replacefile
-
- report('replace file')
-
- if newname = @commandline.argument('first') then
- if newname && ! newname.empty? then
- report
- report("replacing #{newname}")
- report
- oldname = kpsefile(File.basename(newname))
- force = @commandline.option('force')
- if oldname && ! oldname.empty? then
- oldname = File.expand_path(oldname)
- newname = File.expand_path(newname)
- report("old: #{oldname}")
- report("new: #{newname}")
- report
- if newname == oldname then
- report('unable to replace itself')
- elsif force then
- begin
- File.copy(newname,oldname)
- rescue
- report('error in replacing the old file')
- end
- else
- report('the old file will be replaced (use --force)')
- end
- else
- report('nothing to replace')
- end
- else
- report('no file specified')
- end
- else
- report('no file specified')
- end
-
- end
-
- private # general
-
- def texmfroots
- begin
- paths = `kpsewhich -expand-path=\$TEXMF`.chomp
- rescue
- else
- return paths.split(/#{File::PATH_SEPARATOR}/) if paths && ! paths.empty?
- end
- return nil
- end
-
- def texmffiles(root, filename)
- begin
- files = Dir.glob("#{root}/**/#{filename}")
- rescue
- else
- return files if files && files.length>0
- end
- return nil
- end
-
- def pathfile(filename)
- used = nil
- begin
- if ! filename || filename.empty? then
- return nil
- else
- ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
- if FileTest.file?(File.join(path,filename)) then
- used = File.join(path,filename)
- break
- end
- end
- end
- rescue
- used = nil
- else
- used = nil if used && used.empty?
- end
- return used
- end
-
- def kpsefile(filename)
- used = nil
- begin
- if ! filename || filename.empty? then
- return nil
- else
- used = `kpsewhich #{filename}`.chomp
- end
- if used && used.empty? then
- used = `kpsewhich -progname=context #{filename}`.chomp
- end
- if used && used.empty? then
- used = `kpsewhich -format=texmfscripts #{filename}`.chomp
- end
- if used && used.empty? then
- used = `kpsewhich -progname=context -format=texmfscripts #{filename}`.chomp
- end
- if used && used.empty? then
- used = `kpsewhich -format="other text files" #{filename}`.chomp
- end
- if used && used.empty? then
- used = `kpsewhich -progname=context -format="other text files" #{filename}`.chomp
- end
- rescue
- used = nil
- else
- used = nil if used && used.empty?
- end
- return used
- end
-
- def downcasefilenames
-
- report('downcase filenames')
-
- force = @commandline.option('force')
-
- # if @commandline.option('recurse') then
- # files = Dir.glob('**/*')
- # else
- # files = Dir.glob('*')
- # end
- # if files && files.length>0 then
-
- if files = findfiles() then
- files.each do |oldname|
- if FileTest.file?(oldname) then
- newname = oldname.downcase
- if oldname != newname then
- if force then
- begin
- File.rename(oldname,newname)
- rescue
- report("#{oldname} == #{oldname}\n")
- else
- report("#{oldname} => #{newname}\n")
- end
- else
- report("(#{oldname} => #{newname})\n")
- end
- end
- end
- end
- end
- end
-
- def stripformfeeds
-
- report('strip formfeeds')
-
- force = @commandline.option('force')
-
- if files = findfiles() then
- files.each do |filename|
- if FileTest.file?(filename) then
- begin
- data = IO.readlines(filename).join('')
- rescue
- else
- if data.gsub!(/\n*\f\n*/io,"\n\n") then
- if force then
- if f = open(filename,'w') then
- report("#{filename} is stripped\n")
- f.puts(data)
- f.close
- else
- report("#{filename} cannot be stripped\n")
- end
- else
- report("#{filename} will be stripped\n")
- end
- end
- end
- end
- end
- end
- end
-
- public
-
- def showfont
-
- file = @commandline.argument('first')
-
- if file.empty? then
- report('provide filename')
- else
- file.sub!(/\.afm$/,'')
- begin
- report("analyzing afm file #{file}.afm")
- file = `kpsewhich #{file}.afm`.chomp
- rescue
- report('unable to run kpsewhich')
- return
- end
-
- names = Array.new
-
- if FileTest.file?(file) then
- File.new(file).each do |line|
- if line.match(/^C\s*([\-\d]+)\s*\;.*?\s*N\s*(.+?)\s*\;/o) then
- names.push($2)
- end
- end
- ranges = names.size
- report("number of glyphs: #{ranges}")
- ranges = ranges/256 + 1
- report("number of subsets: #{ranges}")
- file = File.basename(file).sub(/\.afm$/,'')
- tex = File.open("textools.tex",'w')
- map = File.open("textools.map",'w')
- tex.puts("\\starttext\n")
- tex.puts("\\loadmapfile[textools.map]\n")
- for i in 1..ranges do
- rfile = "#{file}-range-#{i}"
- report("generating enc file #{rfile}.enc")
- flushencoding("#{rfile}", (i-1)*256, i*256-1, names)
- # catch console output
- report("generating tfm file #{rfile}.tfm")
- mapline = `afm2tfm #{file}.afm -T #{rfile}.enc #{rfile}.tfm`
- # more robust replacement
- mapline = "#{rfile} <#{rfile}.enc <#{file}.pfb"
- # final entry in map file
- mapline = "#{mapline} <#{file}.pfb"
- map.puts("#{mapline}\n")
- tex.puts("\\showfont[#{rfile}][unknown]\n")
- end
- tex.puts("\\stoptext\n")
- report("generating map file textools.map")
- report("generating tex file textools.tex")
- map.close
- tex.close
- else
- report("invalid file #{file}")
- end
- end
-
- end
-
- @@knownchars = Hash.new
-
- @@knownchars['ae'] = 'aeligature' ; @@knownchars['oe'] = 'oeligature'
- @@knownchars['AE'] = 'AEligature' ; @@knownchars['OE'] = 'OEligature'
-
- @@knownchars['acute' ] = 'textacute'
- @@knownchars['breve' ] = 'textbreve'
- @@knownchars['caron' ] = 'textcaron'
- @@knownchars['cedilla' ] = 'textcedilla'
- @@knownchars['circumflex' ] = 'textcircumflex'
- @@knownchars['diaeresis' ] = 'textdiaeresis'
- @@knownchars['dotaccent' ] = 'textdotaccent'
- @@knownchars['grave' ] = 'textgrave'
- @@knownchars['hungarumlaut'] = 'texthungarumlaut'
- @@knownchars['macron' ] = 'textmacron'
- @@knownchars['ogonek' ] = 'textogonek'
- @@knownchars['ring' ] = 'textring'
- @@knownchars['tilde' ] = 'texttilde'
-
- @@knownchars['cent' ] = 'textcent'
- @@knownchars['currency'] = 'textcurrency'
- @@knownchars['euro' ] = 'texteuro'
- @@knownchars['florin' ] = 'textflorin'
- @@knownchars['sterling'] = 'textsterling'
- @@knownchars['yen' ] = 'textyen'
-
- @@knownchars['brokenbar'] = 'textbrokenbar'
- @@knownchars['bullet' ] = 'textbullet'
- @@knownchars['dag' ] = 'textdag'
- @@knownchars['ddag' ] = 'textddag'
- @@knownchars['degree' ] = 'textdegree'
- @@knownchars['div' ] = 'textdiv'
- @@knownchars['ellipsis' ] = 'textellipsis'
- @@knownchars['fraction' ] = 'textfraction'
- @@knownchars['lognot' ] = 'textlognot'
- @@knownchars['minus' ] = 'textminus'
- @@knownchars['mu' ] = 'textmu'
- @@knownchars['multiply' ] = 'textmultiply'
- @@knownchars['pm' ] = 'textpm'
-
- def encmake
- afmfile = @commandline.argument('first')
- encoding = @commandline.argument('second') || 'dummy'
- if afmfile && FileTest.file?(afmfile) then
- chars = Array.new
- IO.readlines(afmfile).each do |line|
- if line =~ /C\s+(\d+).*?N\s+([a-zA-Z\-\.]+?)\s*;/ then
- chars[$1.to_i] = $2
- end
- end
- if f = File.open(encoding+'.enc','w') then
- f << "% Encoding file, generated by textools.rb from #{afmfile}\n"
- f << "\n"
- f << "/#{encoding.gsub(/[^a-zA-Z]/,'')}encoding [\n"
- 256.times do |i|
- f << " /#{chars[i] || '.notdef'} % #{i}\n"
- end
- f << "] def\n"
- f.close
- end
- if f = File.open('enco-'+encoding+'.tex','w') then
- f << "% ConTeXt file, generated by textools.rb from #{afmfile}\n"
- f << "\n"
- f << "\\startencoding[#{encoding}]\n\n"
- 256.times do |i|
- if str = chars[i] then
- tmp = str.gsub(/dieresis/,'diaeresis')
- if chr = @@knownchars[tmp] then
- f << " \\definecharacter #{chr} #{i}\n"
- elsif tmp.length > 5 then
- f << " \\definecharacter #{tmp} #{i}\n"
- end
- end
- end
- f << "\n\\stopencoding\n"
- f << "\n\\endinput\n"
- f.close
- end
- end
- end
-
- private
-
- def flushencoding (file, from, to, names)
- n = 0
- out = File.open("#{file}.enc",'w')
- out.puts("/#{file.gsub(/\-/,'')} [\n")
- for i in from..to do
- if names[i] then
- n += 1
- out.puts("/#{names[i]}\n")
- else
- out.puts("/.notdef\n")
- end
- end
- out.puts("] def\n")
- out.close
- return n
- end
-
- private # specific
-
- def movefiles(from_path,to_path,suffix,&block)
- obsolete = 'obsolete'
- force = @commandline.option('force')
- moved = 0
- if files = texmffiles(from_path, "*.#{suffix}") then
- files.each do |filename|
- newfilename = filename.sub(/^#{from_path}/, to_path)
- yield(newfilename) if block
- if FileTest.file?(newfilename) then
- begin
- File.rename(filename,filename+'.obsolete') if force
- rescue
- report("#{filename} cannot be made obsolete") if force
- else
- if force then
- report("#{filename} is made obsolete")
- else
- report("#{filename} will become obsolete")
- end
- end
- else
- begin
- File.makedirs(File.dirname(newfilename)) if force
- rescue
- end
- begin
- File.copy(filename,newfilename) if force
- rescue
- report("#{filename} cannot be copied to #{newfilename}")
- else
- begin
- File.delete(filename) if force
- rescue
- report("#{filename} cannot be deleted") if force
- else
- if force then
- report("#{filename} is moved to #{newfilename}")
- moved += 1
- else
- report("#{filename} will be moved to #{newfilename}")
- end
- end
- end
- end
- end
- else
- report('no matches found')
- end
- return moved
- end
-
- def xidemapnames(hide)
-
- filter = /^([^\%]+?)(\s+)([^\"\<\s]*?)(\s)/
- banner = '% textools:nn '
-
- if files = findfiles('map') then
- report
- files.sort.each do |fn|
- if fn.has_suffix?('map') then
- begin
- lines = IO.read(fn)
- report("processing #{fn}")
- if f = File.open(fn,'w') then
- skip = false
- if hide then
- lines.each do |str|
- if skip then
- skip = false
- elsif str =~ /#{banner}/ then
- skip = true
- elsif str =~ filter then
- f.puts(banner+str)
- str.sub!(filter) do
- $1 + $2 + " "*$3.length + $4
- end
- end
- f.puts(str)
- end
- else
- lines.each do |str|
- if skip then
- skip = false
- elsif str.sub!(/#{banner}/, '') then
- f.puts(str)
- skip = true
- else
- f.puts(str)
- end
- end
- end
- f.close
- end
- rescue
- report("error in handling #{fn}")
- end
- end
- end
- end
-
- end
-
- public
-
- def updatetree
-
- nocheck = @commandline.option('nocheck')
- merge = @commandline.option('merge')
- delete = @commandline.option('delete')
- force = @commandline.option('force')
- root = @commandline.argument('first').gsub(/\\/,'/')
- path = @commandline.argument('second').gsub(/\\/,'/')
-
- if FileTest.directory?(root) then
- report("scanning #{root}")
- rootfiles = Dir.glob("#{root}/**/*")
- else
- report("provide source root")
- return
- end
- if rootfiles.size > 0 then
- report("#{rootfiles.size} files")
- else
- report("no files")
- return
- end
- rootfiles.collect! do |rf|
- rf.gsub(/\\/o, '/').sub(/#{root}\//o, '')
- end
- rootfiles = rootfiles.delete_if do |rf|
- FileTest.directory?(File.join(root,rf))
- end
-
- if FileTest.directory?(path) then
- report("scanning #{path}")
- pathfiles = Dir.glob("#{path}/**/*")
- else
- report("provide destination root")
- return
- end
- if pathfiles.size > 0 then
- report("#{pathfiles.size} files")
- else
- report("no files")
- return
- end
- pathfiles.collect! do |pf|
- pf.gsub(/\\/o, '/').sub(/#{path}\//o, '')
- end
- pathfiles = pathfiles.delete_if do |pf|
- FileTest.directory?(File.join(path,pf))
- end
-
- root = File.expand_path(root)
- path = File.expand_path(path)
-
- donepaths = Hash.new
- copiedfiles = Hash.new
-
- # update existing files, assume similar paths
-
- report("")
- pathfiles.each do |f| # destination
- p = File.join(path,f)
- if rootfiles.include?(f) then
- r = File.join(root,f)
- if p != r then
- if nocheck or File.mtime(p) < File.mtime(r) then
- copiedfiles[File.expand_path(p)] = true
- report("updating '#{r}' to '#{p}'")
- begin
- begin File.makedirs(File.dirname(p)) if force ; rescue ; end
- File.copy(r,p) if force
- rescue
- report("updating failed")
- end
- else
- report("not updating '#{r}'")
- end
- end
- end
- end
-
- # merging non existing files
-
- report("")
- rootfiles.each do |f|
- donepaths[File.dirname(f)] = true
- r = File.join(root,f)
- if not pathfiles.include?(f) then
- p = File.join(path,f)
- if p != r then
- if merge then
- copiedfiles[File.expand_path(p)] = true
- report("merging '#{r}' to '#{p}'")
- begin
- begin File.makedirs(File.dirname(p)) if force ; rescue ; end
- File.copy(r,p) if force
- rescue
- report("merging failed")
- end
- else
- report("not merging '#{r}'")
- end
- end
- end
- end
-
- # deleting obsolete files
-
- report("")
- donepaths.keys.sort.each do |d|
- pathfiles = Dir.glob("#{path}/#{d}/**/*")
- pathfiles.each do |p|
-# puts(File.dirname(p))
-# if donepaths[File.dirname(p)] then
- r = File.join(root,d,File.basename(p))
- if FileTest.file?(p) and not FileTest.file?(r) and not copiedfiles.key?(File.expand_path(p)) then
- if delete then
- report("deleting '#{p}'")
- begin
- File.delete(p) if force
- rescue
- report("deleting failed")
- end
- else
- report("not deleting '#{p}'")
- end
- end
- end
-# end
- end
-
- end
-
-end
-
-logger = Logger.new(banner.shift)
-commandline = CommandLine.new
-
-commandline.registeraction('removemapnames' , '[pattern] [--recurse]')
-commandline.registeraction('restoremapnames' , '[pattern] [--recurse]')
-commandline.registeraction('hidemapnames' , '[pattern] [--recurse]')
-commandline.registeraction('videmapnames' , '[pattern] [--recurse]')
-commandline.registeraction('findfile' , 'filename [--recurse]')
-commandline.registeraction('unzipfiles' , '[pattern] [--recurse]')
-commandline.registeraction('fixafmfiles' , '[pattern] [--recurse]')
-commandline.registeraction('mactodos' , '[pattern] [--recurse]')
-commandline.registeraction('fixtexmftrees' , '[texmfroot] [--force]')
-commandline.registeraction('replacefile' , 'filename [--force]')
-commandline.registeraction('updatetree' , 'fromroot toroot [--force --nocheck --merge --delete]')
-commandline.registeraction('downcasefilenames', '[--recurse] [--force]') # not yet documented
-commandline.registeraction('stripformfeeds' , '[--recurse] [--force]') # not yet documented
-commandline.registeraction('showfont' , 'filename')
-commandline.registeraction('encmake' , 'afmfile encodingname')
-
-commandline.registeraction('tpmmake' , 'tpm file (run in texmf root)')
-
-commandline.registeraction('help')
-commandline.registeraction('version')
-
-commandline.registerflag('recurse')
-commandline.registerflag('force')
-commandline.registerflag('merge')
-commandline.registerflag('delete')
-commandline.registerflag('nocheck')
-
-commandline.expand
-
-Commands.new(commandline,logger,banner).send(commandline.action || 'help')
diff --git a/Master/texmf-dist/scripts/context/ruby/texutil.rb b/Master/texmf-dist/scripts/context/ruby/texutil.rb
deleted file mode 100644
index ee0fc1e5e40..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/texutil.rb
+++ /dev/null
@@ -1,93 +0,0 @@
-banner = ['TeXUtil ', 'version 9.1.0', '1997-2005', 'PRAGMA ADE/POD']
-
-$: << File.expand_path(File.dirname($0)) ; $: << File.join($:.last,'lib') ; $:.uniq!
-
-require 'base/switch'
-require 'base/logger'
-require 'base/file'
-require 'base/texutil'
-
-class Commands
-
- include CommandBase
-
- def references
- filename = @commandline.argument('first')
- if not filename.empty? and FileTest.file?(File.suffixed(filename,'tuo')) then
- if tu = TeXUtil::Converter.new(logger) and tu.loaded(filename) then
- tu.saved if tu.processed
- end
- end
- end
-
- def main
- if @commandline.arguments.length>0 then
- references
- else
- help
- end
- end
-
- def purgefiles
- system("texmfstart ctxtools --purge #{@commandline.arguments.join(' ')}")
- end
-
- def purgeallfiles
- system("texmfstart ctxtools --purge --all #{@commandline.arguments.join(' ')}")
- end
-
- def documentation
- system("texmfstart ctxtools --document #{@commandline.arguments.join(' ')}")
- end
-
- def analyzefile
- system("texmfstart pdftools --analyze #{@commandline.arguments.join(' ')}")
- end
-
- def filterpages # obsolete
- system("texmfstart ctxtools --purge #{@commandline.arguments.join(' ')}")
- end
-
- def figures
- report("this code is not yet converted from perl to ruby")
- end
-
- def logfile
- report("this code is not yet converted from perl to ruby")
- end
-
-end
-
-logger = Logger.new(banner.shift)
-commandline = CommandLine.new
-
-# main feature
-
-commandline.registeraction('references', 'convert tui file into tuo file')
-
-# todo features
-
-commandline.registeraction('figures', 'generate figure dimensions file')
-commandline.registeraction('logfile', 'filter essential log messages')
-
-# backward compatibility features
-
-commandline.registeraction('purgefiles', 'remove most temporary files')
-commandline.registeraction('purgeallfiles', 'remove all temporary files')
-commandline.registeraction('documentation', 'generate documentation file from source')
-commandline.registeraction('analyzefile', 'analyze pdf file')
-
-# old feature, not needed any longer due to extension of pdftex
-
-commandline.registeraction('filterpages')
-
-# generic features
-
-commandline.registeraction('help')
-commandline.registeraction('version')
-
-commandline.registerflag('verbose')
-
-commandline.expand
-
-Commands.new(commandline,logger,banner).send(commandline.action || 'main')
diff --git a/Master/texmf-dist/scripts/context/ruby/tmftools.rb b/Master/texmf-dist/scripts/context/ruby/tmftools.rb
deleted file mode 100644
index 626ef1f4a33..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/tmftools.rb
+++ /dev/null
@@ -1,165 +0,0 @@
-#!/usr/bin/env ruby
-
-# program : tmftools
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2005
-# author : Hans Hagen
-#
-# project : ConTeXt
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# The script based alternative is not slower than the kpse one.
-# Loading is a bit faster when the log file is used.
-
-# todo: create database
-
-# tmftools [some of the kpsewhich switches]
-
-# tmftools --analyze
-# tmftools --analyze > kpsewhat.log
-# tmftools --analyze --strict > kpsewhat.log
-# tmftools --analyze --delete --force "texmf-local/fonts/.*/somename"
-# tmftools --serve
-
-# the real thing
-
-banner = ['TMFTools', 'version 1.1.0 (experimental, no help yet)', '2005/2006', 'PRAGMA ADE/POD']
-
-$: << File.expand_path(File.dirname($0)) ; $: << File.join($:.last,'lib') ; $:.uniq!
-
-require 'base/switch'
-require 'base/logger'
-
-class Commands
-
- include CommandBase
-
- def init_kpse
- # require 'base/kpseremote'
- # if KpseRemote::available? then
- if ENV['KPSEMETHOD'] && ENV['KPSEPORT'] then
- require 'base/kpseremote'
- k = KpseRemote.new
- else
- k = nil
- end
- if k && k.okay? then
- k.progname = @commandline.option('progname')
- k.engine = @commandline.option('engine')
- k.format = @commandline.option('format')
- else
- require 'base/kpsefast'
- k = KpseFast.new
- k.rootpath = @commandline.option('rootpath')
- k.treepath = @commandline.option('treepath')
- k.progname = @commandline.option('progname')
- k.engine = @commandline.option('engine')
- k.format = @commandline.option('format')
- k.diskcache = @commandline.option('diskcache')
- k.renewcache = @commandline.option('renewcache')
- k.load_cnf
- k.expand_variables
- k.load_lsr
- end
- return k
- end
-
- def serve
- if ENV['KPSEMETHOD'] && ENV['KPSEPORT'] then
- require 'base/kpseremote'
- begin
- KpseRemote::start_server
- rescue
- end
- end
- end
-
- def reload
- begin
- init_kpse.load
- rescue
- end
- end
-
- def main
- if option = @commandline.option('expand-braces') and not option.empty? then
- puts init_kpse.expand_braces(option)
- elsif option = @commandline.option('expand-path') and not option.empty? then
- puts init_kpse.expand_path(option)
- elsif option = @commandline.option('expand-var') and not option.empty? then
- if option == '*' then
- init_kpse.list_expansions()
- else
- puts init_kpse.expand_var(option)
- end
- elsif option = @commandline.option('show-path') and not option.empty? then
- puts init_kpse.show_path(option)
- elsif option = @commandline.option('var-value') and not option.empty? then
- if option == '*' then
- init_kpse.list_variables()
- else
- puts init_kpse.expand_var(option)
- end
- elsif @commandline.arguments.size > 0 then
- kpse = init_kpse
- @commandline.arguments.each do |option|
- puts kpse.find_file(option)
- end
- else
- help
- end
- end
-
- def analyze
- pattern = @commandline.argument('first')
- strict = @commandline.option('strict')
- sort = @commandline.option('sort')
- delete = @commandline.option('delete') and @commandline.option('force')
- init_kpse.analyze_files(pattern, strict, sort, delete)
- end
-
-end
-
-logger = Logger.new(banner.shift)
-commandline = CommandLine.new
-
-# kpsewhich compatible options
-
-commandline.registervalue('expand-braces','')
-commandline.registervalue('expand-path','')
-commandline.registervalue('expand-var','')
-commandline.registervalue('show-path','')
-commandline.registervalue('var-value','')
-
-commandline.registervalue('engine','')
-commandline.registervalue('progname','')
-commandline.registervalue('format','')
-
-# additional goodies
-
-commandline.registervalue('rootpath','')
-commandline.registervalue('treepath','')
-commandline.registervalue('sort','')
-
-commandline.registerflag('diskcache')
-commandline.registerflag('renewcache')
-commandline.registerflag('strict')
-commandline.registerflag('delete')
-commandline.registerflag('force')
-
-commandline.registeraction('analyze', "[--strict --sort --rootpath --treepath]\n[--delete [--force]] [pattern]")
-
-# general purpose options
-
-commandline.registerflag('verbose')
-commandline.registeraction('help')
-commandline.registeraction('version')
-
-commandline.registeraction('reload', 'reload file database')
-commandline.registeraction('serve', 'act as kpse server')
-
-commandline.expand
-
-Commands.new(commandline,logger,banner).send(commandline.action || 'main')
diff --git a/Master/texmf-dist/scripts/context/ruby/xmltools.rb b/Master/texmf-dist/scripts/context/ruby/xmltools.rb
deleted file mode 100644
index c28df200dd6..00000000000
--- a/Master/texmf-dist/scripts/context/ruby/xmltools.rb
+++ /dev/null
@@ -1,656 +0,0 @@
-#!/usr/bin/env ruby
-
-# program : xmltools
-# copyright : PRAGMA Advanced Document Engineering
-# version : 2002-2005
-# author : Hans Hagen
-#
-# project : ConTeXt / eXaMpLe
-# concept : Hans Hagen
-# info : j.hagen@xs4all.nl
-# www : www.pragma-ade.com
-
-# todo : use kpse lib
-
-# This script will harbor some handy manipulations on tex
-# related files.
-
-banner = ['XMLTools', 'version 1.2.2', '2002/2007', 'PRAGMA ADE/POD']
-
-$: << File.expand_path(File.dirname($0)) ; $: << File.join($:.last,'lib') ; $:.uniq!
-
-require 'base/switch'
-require 'base/logger'
-
-class String
-
- def astring(n=10)
- gsub(/(\d+)/o) do $1.to_s.rjust(n) end.gsub(/ /o, '0')
- end
-
- def xstring
- if self =~ /\'/o then
- "\"#{self.gsub(/\"/, '&quot;')}\""
- else
- "\'#{self}\'"
- end
- end
-
-end
-
-class Array
-
- def asort(n=10)
- sort {|x,y| x.astring(n) <=> y.astring(n)}
- end
-
-end
-
-class Commands
-
- include CommandBase
-
- def dir
-
- @xmlns = "xmlns='http://www.pragma-ade.com/rlg/xmldir.rng'"
-
- pattern = @commandline.option('pattern')
- recurse = @commandline.option('recurse')
- stripname = @commandline.option('stripname')
- longname = @commandline.option('longname')
- url = @commandline.option('url')
- outputfile = @commandline.option('output')
- root = @commandline.option('root')
-
- def generate(output,files,url,root,longname)
-
- class << output
- def xputs(str,n=0)
- puts("#{' '*n}#{str}")
- end
- end
-
- dirname = ''
- output.xputs("<?xml version='1.0'?>\n\n")
- if ! root || root.empty? then
- rootatt = @xmlns
- else
- rootatt = " #{@xmlns} root='#{root}'"
- end
- rootatt += " timestamp='#{Time.now}'"
- if url.empty? then
- output.xputs("<files #{rootatt}>\n")
- else
- output.xputs("<files url='#{url}'#{rootatt}>\n")
- end
- files.each do |f|
- bn, dn = File.basename(f), File.dirname(f)
- if dirname != dn then
- output.xputs("</directory>\n", 2) if dirname != ''
- output.xputs("<directory name='#{dn}'>\n", 2)
- dirname = dn
- end
- if longname && dn != '.' then
- output.xputs("<file name='#{dn}/#{bn}'>\n", 4)
- else
- output.xputs("<file name='#{bn}'>\n", 4)
- end
- output.xputs("<base>#{bn.sub(/\..*$/,'')}</base>\n", 6)
- if File.stat(f).file? then
- bt = bn.sub(/^.*\./,'')
- if bt != bn then
- output.xputs("<type>#{bt}</type>\n", 6)
- end
- output.xputs("<size>#{File.stat(f).size}</size>\n", 6)
- permissions = ''
- permissions << 'r' if File.readable?(f)
- permissions << 'w' if File.writable?(f)
- permissions << 'x' if File.executable?(f)
- output.xputs("<permissions>#{permissions}</permissions>\n", 6) unless permissions.empty?
- end
- output.xputs("<date>#{File.stat(f).mtime.strftime("%Y-%m-%d %H:%M")}</date>\n", 6)
- output.xputs("</file>\n", 4)
- end
- output.xputs("</directory>\n", 2) if dirname != ''
- output.xputs("</files>\n")
-
- end
-
- if pattern.empty? then
- report('provide --pattern=')
- return
- end
-
- unless outputfile.empty? then
- begin
- output = File.open(outputfile,'w')
- rescue
- report("unable to open #{outputfile}")
- return
- end
- else
- report('provide --output')
- return
- end
-
- if stripname && pattern.class == String && ! pattern.empty? then
- pattern = File.dirname(pattern)
- end
-
- pattern = '*' if pattern.empty?
-
- unless root.empty? then
- unless FileTest.directory?(root) then
- report("unknown root #{root}")
- return
- end
- begin
- Dir.chdir(root)
- rescue
- report("unable to change to root #{root}")
- return
- end
- end
-
- generate(output, globbed(pattern, recurse), url, root, longname)
-
- output.close if output
-
- end
-
- alias ls :dir
-
- def mmlpages
-
- file = @commandline.argument('first')
- eps = @commandline.option('eps')
- jpg = @commandline.option('jpg')
- png = @commandline.option('png')
- style = @commandline.option('style')
- modes = @commandline.option('modes')
-
- file = file.sub(/\.xml/io, '')
- long = "#{file}-mmlpages"
- if FileTest.file?(file+'.xml') then
- style = "--arg=\"style=#{style}\"" unless style.empty?
- modes = "--mode=#{modes}" unless modes.empty?
- if system("texmfstart texexec --batch --pdf --once --result=#{long} --use=mmlpag #{style} #{modes} #{file}.xml") then
- if eps then
- if f = open("#{file}-mmlpages.txt") then
- while line = f.gets do
- data = Hash.new
- if fields = line.split then
- fields.each do |fld|
- key, value = fld.split('=')
- data[key] = value if key && value
- end
- if data.key?('p') then
- page = data['p']
- name = "#{long}-#{page.to_i-1}"
- if eps then
- report("generating eps file #{name}")
- if system("pdftops -eps -f #{page} -l #{page} #{long}.pdf #{name}.eps") then
- if data.key?('d') then
- if epsfile = IO.read("#{name}.eps") then
- epsfile.sub!(/^(\%\%BoundingBox:.*?$)/i) do
- newline = $1 + "\n%%Baseline: #{data['d']}\n"
- if data.key?('w') && data.key?('h') then
- newline += "%%PositionWidth: #{data['w']}\n"
- newline += "%%PositionHeight: #{data['h']}\n"
- newline += "%%PositionDepth: #{data['d']}"
- end
- newline
- end
- if g = File.open("#{name}.eps",'wb') then
- g.write(epsfile)
- g.close
- end
- end
- end
- else
- report("error in generating eps from #{name}")
- end
- end
- end
- end
- end
- f.close
- else
- report("missing data log file #{file}")
- end
- end
- if png then
- report("generating png file for #{long}")
- system("imagemagick #{long}.pdf #{long}-%d.png")
- end
- if jpg then
- report("generating jpg files for #{long}")
- system("imagemagick #{long}.pdf #{long}-%d.jpg")
- end
- else
- report("error in processing file #{file}")
- end
- system("texmfstart ctxtools --purge")
- else
- report("error in processing file #{file}")
- end
-
- end
-
- def analyze
-
- file = @commandline.argument('first')
- result = @commandline.option('output')
- utf = @commandline.option('utf')
- process = @commandline.option('process')
-
- if FileTest.file?(file) then
- if data = IO.read(file) then
- if data =~ /<?xml.*?version\=/ then
- report("xml file #{file} loaded")
- elements = Hash.new
- attributes = Hash.new
- entities = Hash.new
- chars = Hash.new
- unicodes = Hash.new
- names = Hash.new
- data.scan(/<([^>\s\/\!\?]+)([^>]*?)>/o) do
- element, attributelist = $1, $2
- if elements.key?(element) then
- elements[element] += 1
- else
- elements[element] = 1
- end
- attributelist.scan(/\s*([^\=]+)\=([\"\'])(.*?)(\2)/) do
- key, value = $1, $3
- attributes[element] = Hash.new unless attributes.key?(element)
- attributes[element][key] = Hash.new unless attributes[element].key?(key)
- if attributes[element][key].key?(value) then
- attributes[element][key][value] += 1
- else
- attributes[element][key][value] = 1
- end
- end
- end
- data.scan(/\&([^\;]+)\;/o) do
- entity = $1
- if entities.key?(entity) then
- entities[entity] += 1
- else
- entities[entity] = 1
- end
- end
- if utf then
- data.scan(/(\w)/u) do
- chars[$1] = (chars[$1] || 0) + 1
- end
- if chars.size > 0 then
- begin
- # todo : use kpse lib
- filename, ownpath, foundpath = 'contextnames.txt', File.dirname($0), ''
- begin
- foundpath = File.dirname(`kpsewhich -progname=context -format=\"other text files\" #{filename}`.chomp)
- rescue
- foundpath = '.'
- else
- foundpath = '.' if foundpath.empty?
- end
- [foundpath,ownpath,File.join(ownpath,'../../../context/data')].each do |path|
- fullname = File.join(path,filename)
- if FileTest.file?(fullname) then
- report("loading '#{fullname}'")
- # rough scan, we assume no valid lines after comments
- IO.read(fullname).scan(/^([0-9A-F][0-9A-F][0-9A-F][0-9A-F])\s*\;\s*(.*?)\s*\;\s*(.*?)\s*\;\s*(.*?)\s*$/) do
- names[$1.hex.to_i.to_s] = [$2,$3,$4]
- end
- break
- end
- end
- rescue
- end
- end
- end
- result = file.gsub(/\..*?$/, '') + '.xlg' if result.empty?
- if f = File.open(result,'w') then
- report("saving report in #{result}")
- f.puts "<?xml version='1.0'?>\n"
- f.puts "<document>\n"
- if entities.length>0 then
- total = 0
- entities.each do |k,v|
- total += v
- end
- f.puts " <entities n=#{total.to_s.xstring}>\n"
- entities.keys.asort.each do |entity|
- f.puts " <entity name=#{entity.xstring} n=#{entities[entity].to_s.xstring}/>\n"
- end
- f.puts " </entities>\n"
- end
- if utf && (chars.size > 0) then
- total = 0
- chars.each do |k,v|
- total += v
- end
- f.puts " <characters n=#{total.to_s.xstring}>\n"
- chars.each do |k,v|
- if k.length > 1 then
- begin
- u = k.unpack('U')
- unicodes[u] = (unicodes[u] || 0) + v
- rescue
- report("invalid utf codes")
- end
- end
- end
- unicodes.keys.sort.each do |u|
- ustr = u.to_s
- if names[ustr] then
- f.puts " <character number=#{ustr.xstring} pname=#{names[ustr][0].xstring} cname=#{names[ustr][1].xstring} uname=#{names[ustr][2].xstring} n=#{unicodes[u].to_s.xstring}/>\n"
- else
- f.puts " <character number=#{ustr.xstring} n=#{unicodes[u].to_s.xstring}/>\n"
- end
- end
- f.puts " </characters>\n"
- end
- if elements.length>0 then
- f.puts " <elements>\n"
- elements.keys.sort.each do |element|
- if attributes.key?(element) then
- f.puts " <element name=#{element.xstring} n=#{elements[element].to_s.xstring}>\n"
- if attributes.key?(element) then
- attributes[element].keys.asort.each do |attribute|
- f.puts " <attribute name=#{attribute.xstring}>\n"
- if attribute =~ /id$/o then
- nn = 0
- attributes[element][attribute].keys.asort.each do |value|
- nn += attributes[element][attribute][value].to_i
- end
- f.puts " <instance value=#{"*".xstring} n=#{nn.to_s.xstring}/>\n"
- else
- attributes[element][attribute].keys.asort.each do |value|
- f.puts " <instance value=#{value.xstring} n=#{attributes[element][attribute][value].to_s.xstring}/>\n"
- end
- end
- f.puts " </attribute>\n"
- end
- end
- f.puts " </element>\n"
- else
- f.puts " <element name=#{element.xstring} n=#{elements[element].to_s.xstring}/>\n"
- end
- end
- f.puts " </elements>\n"
- end
- f.puts "</document>\n"
- f.close
- if process then
- system("texmfstart texexec --purge --pdf --use=xml-analyze #{result}")
- end
- else
- report("unable to open file '#{result}'")
- end
- else
- report("invalid xml file '#{file}'")
- end
- else
- report("unable to load file '#{file}'")
- end
- else
- report("unknown file '#{file}'")
- end
- end
-
- def filter
-
- require "rexml/document"
-
- element = @commandline.option('element')
- files = @commandline.arguments
- result = "xmltools.xlg"
-
- if element.empty? then
- report("provide element using --element")
- elsif files.length == 0 then
- report("provide filename(s)")
- else
- begin
- File.open(result,'w') do |f|
- f << "<?xml version='1.0'?>\n\n"
- f << "<xlg:document>\n\n"
- total = 0
- files.sort.each do |file|
- begin
- report("loading: #{file}")
- data = REXML::Document.new(IO.read(file))
- rescue
- report("error: invalid xml")
- else
- found = 0
- report("filtering: #{element}")
- REXML::XPath.each(data,"//#{element}") do |table|
- str = table.to_s
- if str.length > 0 then
- total += 1
- found += 1
- report("found: #{total} / #{found} / #{str.length} bytes")
- f << "<xlg:file name='#{file}'>\n\n" unless found > 1
- f << "<xlg:filtered n='#{total}' m='#{found}'>"
- f << "#{str.gsub(/^\s*/m,'').gsub(/\s*$/m,'')}"
- f << "</xlg:filtered>\n\n"
- end
- end
- f << "</xlg:file>\n\n" if found > 0
- end
- end
- f << "</xlg:document>\n"
- end
- report("result: #{result}")
- rescue
- report("error in opening #{result}")
- end
- end
-
- end
-
- def enhance
- oldname = @commandline.argument('first')
- newname = @commandline.argument('second')
- verbose = @commandline.option('verbose')
- # todo: options, maybe a config file
- if ! newname || newname.empty? then
- newname = oldname + ".prep"
- end
- if FileTest.file?(oldname) then
- report("") if verbose
- data = IO.read(oldname)
- elements = Array.new
- preamble = ""
- done = false
- data.sub!(/^(.*?)\s*(<[a-z])/moi) do
- preamble = $1
- $2
- end
- # hide elements
- data.gsub!(/<([^>]*?)>/moi) do
- elements << $1
- "<#{elements.length}>"
- end
- # abc[-/]def
- data.gsub!(/([a-z]{3,})([\/\-\(\)]+)([a-z]{3,})/moi) do
- done = true
- report("compound: #{$1}#{$2}#{$3}") if verbose
- "#{$1}<compound token='#{$2}'/>#{$3}"
- end
- # (abcd
- # data.gsub!(/(\()([a-z]{4,})/moi) do
- # done = true
- # report("compound: #{$1}#{$2}") if verbose
- # "<compound token='#{$1}'/>#{$2}"
- # end
- # abcd)
- # data.gsub!(/(\()([a-z]{4,})/moi) do
- # done = true
- # report("compound: #{$1}#{$2}") if verbose
- # "#{$2}<compound token='#{$2}'/>"
- # end
- # roll back elements
- data.gsub!(/<(\d+)>/moi) do
- "<#{elements.shift}>"
- end
- File.open(newname,'wb') do |f|
- f << preamble
- f << "\n"
- f << data
- end
- if verbose then
- if done then
- report("")
- report(oldname," converted to ",newname)
- else
- report(oldname," copied to ",newname)
- end
- end
- end
- end
-
- def cleanup # todo, share loading/saving with previous
-
- file = @commandline.argument('first')
- force = @commandline.option('force')
- verbose = @commandline.option('verbose')
-
- if FileTest.file?(file) then
- if data = IO.read(file) then
- if data =~ /<?xml.*?version\=/ then
- data = doxmlcleanup(data,verbose)
- result = if force then file else file.gsub(/\..*?$/, '') + '.xlg' end
- begin
- if f = File.open(result,'w') then
- f << data
- f.close
- end
- rescue
- report("unable to open file '#{result}'")
- end
- else
- report("invalid xml file '#{file}'")
- end
- else
- report("unable to load file '#{file}'")
- end
- else
- report("unknown file '#{file}'")
- end
-
- end
-
- def doxmlreport(str,verbose=false)
- if verbose then
- result = str
- report(result)
- return result
- else
- return str
- end
- end
-
- def doxmlcleanup(data="",verbose=false)
-
- # remove funny spaces (looks cleaner)
- #
- # data = "<whatever ></whatever ><whatever />"
-
- data.gsub!(/\<(\/*\w+)\s*(\/*)>/o) do
- "<#{$1}#{$2}>"
- end
-
- # remove funny ampersands
- #
- # data = "<x> B&W </x>"
-
- data.gsub!(/\&([^\<\>\&]*?)\;/mo) do
- "<entity name='#{$1}'/>"
- end
- data.gsub!(/\&/o) do
- doxmlreport("&amp;",verbose)
- end
- data.gsub!(/\<entity name=\'(.*?)\'\/\>/o) do
- doxmlreport("&#{$1};",verbose)
- end
-
- # remove funny < >
- #
- # data = "<x> < 5% </x>"
-
- data.gsub!(/<([^>].*?)>/o) do
- tag = $1
- case tag
- when /^\//o then
- "<#{tag}>" # funny tag but ok
- when /\/$/o then
- "<#{tag}>" # funny tag but ok
- when /</o then
- doxmlreport("&lt;#{tag}>",verbose)
- else
- "<#{tag}>"
- end
- end
-
- # remove funny < >
- #
- # data = "<x> > 5% </x>"
-
- data.gsub!(/<([^>].*?)>([^\>\<]*?)>/o) do
- doxmlreport("<#{$1}>#{$2}&gt;",verbose)
- end
-
- return data
- end
-
- # puts doxmlcleanup("<whatever ></whatever ><whatever />")
- # puts doxmlcleanup("<x> B&W </x>")
- # puts doxmlcleanup("<x> < 5% </x>")
- # puts doxmlcleanup("<x> > 5% </x>")
-
-end
-
-logger = Logger.new(banner.shift)
-commandline = CommandLine.new
-
-commandline.registeraction('dir', 'generate directory listing')
-commandline.registeraction('mmlpages','generate graphic from mathml')
-commandline.registeraction('analyze', 'report entities and elements [--utf --process]')
-commandline.registeraction('cleanup', 'cleanup xml file [--force]')
-commandline.registeraction('enhance', 'enhance xml file (partial)')
-commandline.registeraction('filter', 'filter elements from xml file [element=]')
-
-# commandline.registeraction('dir', 'filename --pattern= --output= [--recurse --stripname --longname --url --root]')
-# commandline.registeraction('mmlpages','filename [--eps --jpg --png --style= --mode=]')
-
-commandline.registeraction('ls')
-
-commandline.registeraction('help')
-commandline.registeraction('version')
-
-commandline.registerflag('stripname')
-commandline.registerflag('longname')
-commandline.registerflag('recurse')
-commandline.registerflag('verbose')
-
-commandline.registervalue('pattern')
-commandline.registervalue('element')
-commandline.registervalue('url')
-commandline.registervalue('output')
-commandline.registervalue('root')
-
-commandline.registerflag('eps')
-commandline.registerflag('png')
-commandline.registerflag('jpg')
-commandline.registerflag('utf')
-commandline.registerflag('process')
-commandline.registervalue('style')
-commandline.registervalue('modes')
-
-commandline.expand
-
-Commands.new(commandline,logger,banner).send(commandline.action || 'help')
diff --git a/Master/texmf-dist/scripts/context/stubs/install/first-setup.bat b/Master/texmf-dist/scripts/context/stubs/install/first-setup.bat
deleted file mode 100755
index f388b0ac0f3..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/install/first-setup.bat
+++ /dev/null
@@ -1,87 +0,0 @@
-@echo off
-
-setlocal
-
-:fetch
-
-set OWNPATH=%~dp0
-set PATH=%OWNPATH%bin;%PATH%
-set PLATFORM=mswin
-
-set CYGWIN=nontsec
-
-if defined ProgramFiles(x86) (
- set PLATFORM=win64
-) else (
- if "%PROCESSOR_ARCHITEW6432%"=="AMD64" set PLATFORM=win64
-)
-
-REM ~ copy /y bin\mtx-update.lua bin\x.lua
-
-if "%PLATFORM%" == "win64" goto update-win64
-
-:update-win32
-
-rsync -av --exclude 'rsync.exe' --exclude 'cygwin1.dll' --exclude 'cygiconv-2.dll' rsync://contextgarden.net/minimals/setup/mswin/bin/ bin
-
-goto update
-
-:update-win64
-
-rsync -av --exclude 'rsync.exe' --exclude 'cygwin1.dll' --exclude 'cygiconv-2.dll' rsync://contextgarden.net/minimals/setup/win64/bin/ bin
-
-goto update
-
-:update
-
-REM ~ copy /y bin\x.lua bin\mtx-update.lua
-
-REM --mingw --nofiledatabase --engine=luatex
-
-mtxrun --script ./bin/mtx-update.lua --update --force --make --engine=all --context=beta --texroot="%OWNPATH%tex" %*
-
-echo.
-echo.
-echo When you want to use context, you need to initialize the tree with:
-echo.
-echo %OWNPATH%tex\setuptex.bat %OWNPATH%tex
-echo.
-echo You can associate this command with a shortcut to the cmd prompt.
-echo.
-echo Alternatively you can add %OWNPATH%tex\texmf-%PLATFORM%\bin to your PATH
-echo variable.
-echo.
-echo If you run from an editor you can specify the full path to mtxrun.exe:
-echo.
-echo. %OWNPATH%tex\texmf-%PLATFORM%\bin\mtxrun.exe --autogenerate --script context --autopdf ...
-echo.
-
-:ruby
-
-echo okay > ok.log
-
-ruby -e "File.delete('ok.log')"
-
-if not exist "ok.log" goto end
-
-echo.
-echo The distribution has been downloaded but if you want to run pdfTeX and/or XeTeX you
-echo need to run this script with the following directive:
-echo.
-echo --platform=all
-echo.
-echo You then also need to install Ruby in order to be able to use texexec. After
-echo installing Ruby you can run this script again which will give you the formats
-echo needed, or you can run:
-echo.
-echo texexec --make --pdftex
-echo texexec --make --xetex
-echo.
-
-:okay
-
-del /q ok.log
-
-:end
-
-endlocal
diff --git a/Master/texmf-dist/scripts/context/stubs/install/first-setup.sh b/Master/texmf-dist/scripts/context/stubs/install/first-setup.sh
deleted file mode 100755
index 83af6a97e67..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/install/first-setup.sh
+++ /dev/null
@@ -1,173 +0,0 @@
-#!/bin/sh
-
-# Takes the same arguments as mtx-update
-
-# you may change this if you want ...
-CONTEXTROOT="$PWD/tex"
-
-# suggested by Tobias Florek to check for rsync
-if [ ! -x "`which rsync`" ]; then
- echo "You need to install rsync first."
- exit 1
-fi
-
-system=`uname -s`
-cpu=`uname -m`
-
-case "$system" in
- # linux
- Linux)
- if command -v ldd >/dev/null && ldd --version 2>&1 | grep -E '^musl' >/dev/null
- then
- libc=musl
- else
- libc=glibc
- fi
- case "$cpu" in
- i*86)
- case "$libc" in
- glibc) platform="linux" ;;
- musl) platform="linuxmusl" ;;
- esac ;;
- x86_64|ia64)
- case "$libc" in
- glibc) platform="linux-64" ;;
- musl) platform="linuxmusl-64" ;;
- esac ;;
-
- # a little bit of cheating with ppc64 (won't work on Gentoo)
- ppc|ppc64) platform="linux-ppc" ;;
-
- # we currently support just mipsel, but Debian is lying (reports mips64)
- # we need more hacks to fix the situation, this is just a temporary solution
- mips|mips64|mipsel|mips64el) platform="linux-mipsel" ;;
-
- armv7l) platform="linux-armhf"
- # machine id output by uname(1) is insufficent to determine whether this
- # is a soft or hard float system so we check ourselves.
- # a) binutils, this should work almost everywhere
- if $(which readelf >/dev/null 2>&1); then
- readelf -A /proc/self/exe | grep -q '^ \+Tag_ABI_VFP_args'
- if [ $? != 0 ]; then
- platform="linux-armel"
- fi
- # b) debian-specific fallback
- elif $(which dpkg >/dev/null 2>&1); then
- if [ "$(dpkg --print-architecture)" = armel ]; then
- platform="linux-armel"
- fi
- fi
- # else go with hard fp
- ;;
-
- *) platform="unknown" ;;
- esac ;;
- # Mac OS X
- Darwin)
- case "$cpu" in
- i*86) platform="osx-intel" ;;
- x86_64) platform="osx-64" ;;
- ppc*|powerpc|power*|Power*) platform="osx-ppc" ;;
- *) platform="unknown" ;;
- esac ;;
- # FreeBSD
- FreeBSD|freebsd)
- case "$cpu" in
- i*86) platform="freebsd" ;;
- amd64) platform="freebsd-amd64" ;;
- *) platform="unknown" ;;
- esac ;;
- # kFreeBSD (debian)
- GNU/kFreeBSD)
- case "$cpu" in
- #i*86) platform="kfreebsd-i386" ;;
- #x86_64|amd64) platform="kfreebsd-amd64" ;;
- *) platform="unknown" ;;
- esac ;;
- # OpenBSD
- OpenBSD)
- version=`uname -r`
- case "$cpu" in
- i*86) platform="openbsd${version}" ;;
- amd64) platform="openbsd${version}-amd64" ;;
- *) platform="unknown" ;;
- esac ;;
- # cygwin
- CYGWIN*)
- case "$cpu" in
- i*86) platform="mswin" ;; # cygwin
- # Pavneet Arora. 20190924. For Cygwin 64-bit platform should be win64.
- x86_64|ia64) platform="win64" ;; # cygwin-64
- *) platform="unknown" ;;
- esac ;;
- # UWIN
- UWIN*)
- case "$cpu" in
- i*86) platform="mswin" ;;
- *) platform="unknown" ;;
- esac ;;
- # SunOS/Solaris
- SunOS)
- case "$cpu" in
- sparc) platform="solaris-sparc" ;;
- i86pc) platform="solaris-intel" ;;
- *) platform="unknown" ;;
- esac ;;
- *) platform="unknown"
-esac
-
-# temporary patch for 64-bit Leopard with 32-bit kernel
-if test "$platform" = "osx-intel"; then
- # if running Snow Leopard or later
- # better: /usr/bin/sw_vers -productVersion
- if test `uname -r|cut -f1 -d"."` -ge 10 ; then
- # if working on 64-bit hardware
- if test `sysctl -n hw.cpu64bit_capable` = 1; then
- # snowleopard32=TRUE
- platform="osx-64"
- fi
- fi
-fi
-
-if test "$platform" = "unknown" ; then
- echo "Error: your system \"$system $cpu\" is not supported yet."
- echo "Please report to the ConTeXt mailing-list (ntg-context@ntg.nl)"
- exit
-elif test "$platform" = "linux-ppc" ; then
- echo "Error: support for your system \"$platform\" has been dropped."
- echo "Please ask on to the ConTeXt mailing-list if you still need it (ntg-context@ntg.nl)"
- exit
-fi
-
-# if you want to enforce some specific platform
-# (when 'uname' doesn't agree with true architecture), uncomment and modify next line:
-# platform=linux
-
-# download or rsync the latest scripts first
-rsync -rlptv rsync://contextgarden.net/minimals/setup/$platform/bin .
-
-# use native windows binaries on cygwin
-# Pavneet Arora. 20190924.
-# ..Commented out the following section entirely.
-#if test "$platform" = "cygwin" ; then
-# platform=mswin
-#fi
-
-# download or update the distribution
-# you may remove the --context=beta switch if you want to use "current"
-# you can use --engine=luatex if you want just mkiv
-env PATH="$PWD/bin:$CONTEXTROOT/texmf-$platform/bin:$PATH" MTX_PLATFORM="$platform" \
-./bin/mtxrun --script ./bin/mtx-update.lua --force --update --make --context=beta --engine=luatex --platform="$platform" --texroot="$CONTEXTROOT" $@
-echo "./bin/mtxrun --script ./bin/mtx-update.lua --force --update --make --context=beta --engine=luatex --platform=\"$platform\" --texroot=\"$CONTEXTROOT\" $@"
-
-echo
-echo "When you want to use context, you need to initialize the tree by typing:"
-echo
-echo " . $CONTEXTROOT/setuptex"
-echo
-echo "in your shell or add"
-echo " \"$CONTEXTROOT/texmf-$platform/bin\""
-echo "to PATH variable if you want to set it permanently."
-echo "This can usually be done in .bashrc, .bash_profile"
-echo "(or whatever file is used to initialize your shell)."
-echo
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/context.exe b/Master/texmf-dist/scripts/context/stubs/mswin/context.exe
deleted file mode 100755
index 0e7882cf926..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/context.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/contextjit.exe b/Master/texmf-dist/scripts/context/stubs/mswin/contextjit.exe
deleted file mode 100755
index 0e7882cf926..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/contextjit.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/ctxtools.exe b/Master/texmf-dist/scripts/context/stubs/mswin/ctxtools.exe
deleted file mode 100755
index 0e7882cf926..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/ctxtools.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/luatools.exe b/Master/texmf-dist/scripts/context/stubs/mswin/luatools.exe
deleted file mode 100755
index 0e7882cf926..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/luatools.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/mtxrun.dll b/Master/texmf-dist/scripts/context/stubs/mswin/mtxrun.dll
deleted file mode 100755
index 3c4481c319d..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/mtxrun.dll
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/mtxrun.exe b/Master/texmf-dist/scripts/context/stubs/mswin/mtxrun.exe
deleted file mode 100755
index 0e7882cf926..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/mtxrun.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/mtxrun.lua b/Master/texmf-dist/scripts/context/stubs/mswin/mtxrun.lua
deleted file mode 100644
index 6fc17adb022..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/mtxrun.lua
+++ /dev/null
@@ -1,27376 +0,0 @@
-#!/usr/bin/env texlua
-
-if not modules then modules = { } end modules ['mtxrun'] = {
- version = 1.001,
- comment = "runner, lua replacement for texmfstart.rb",
- author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright = "PRAGMA ADE / ConTeXt Development Team",
- license = "see context related readme files"
-}
-
--- one can make a stub:
-
--- mtxrun :
---
--- #!/bin/sh
--- env LUATEXDIR=/....../texmf/scripts/context/lua luatex --luaonly mtxrun.lua "$@"
-
--- mtxrun.cmd :
---
--- @luatex --luaonly %~d0%~p0mtxrun.lua %*
-
--- filename : mtxrun.lua
--- comment : companion to context.tex
--- author : Hans Hagen, PRAGMA-ADE, Hasselt NL
--- copyright: PRAGMA ADE / ConTeXt Development Team
--- license : see context related readme files
-
--- This script is based on texmfstart.rb but does not use kpsewhich to locate files.
--- Although kpse is a library it never came to opening up its interface to other
--- programs (esp scripting languages) and so we do it ourselves. The lua variant
--- evolved out of an experimental ruby one. Interesting is that using a scripting
--- language instead of c does not have a speed penalty. Actually the lua variant is
--- more efficient, especially when multiple calls to kpsewhich are involved. The lua
--- library also gives way more control.
-
--- When libraries used here are updates you can run
---
--- mtxrun --selfmerge
---
--- to update the embedded code. After that you might need to run
---
--- mtxrun --selfupdate
---
--- to copy the new script (from scripts/context/lua) to location where
--- binaries are expected. If you want to remove the embedded code you can run
---
--- mtxxun --selfclean
-
--- to be done / considered
---
--- support for --exec or make it default
--- support for jar files (or maybe not, never used, too messy)
--- support for $RUBYINPUTS cum suis (if still needed)
--- remember for subruns: _CTX_K_V_#{original}_
--- remember for subruns: _CTX_K_S_#{original}_
--- remember for subruns: TEXMFSTART.#{original} [tex.rb texmfstart.rb]
-
--- begin library merge
-
-
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-bit32"] = package.loaded["l-bit32"] or true
-
--- original size: 3607, stripped down to: 3009
-
-if not modules then modules={} end modules ['l-bit32']={
- version=1.001,
- license="the same as regular Lua",
- source="bitwise.lua, v 1.24 2014/12/26 17:20:53 roberto",
- comment="drop-in for bit32, adapted a bit by Hans Hagen",
-}
-if bit32 then
-elseif utf8 then
- load ([[
-local select = select -- instead of: arg = { ... }
-bit32 = {
- bnot = function (a)
- return ~a & 0xFFFFFFFF
- end,
- band = function (x, y, z, ...)
- if not z then
- return ((x or -1) & (y or -1)) & 0xFFFFFFFF
- else
- local res = x & y & z
- for i=1,select("#",...) do
- res = res & select(i,...)
- end
- return res & 0xFFFFFFFF
- end
- end,
- bor = function (x, y, z, ...)
- if not z then
- return ((x or 0) | (y or 0)) & 0xFFFFFFFF
- else
- local res = x | y | z
- for i=1,select("#",...) do
- res = res | select(i,...)
- end
- return res & 0xFFFFFFFF
- end
- end,
- bxor = function (x, y, z, ...)
- if not z then
- return ((x or 0) ~ (y or 0)) & 0xFFFFFFFF
- else
- local res = x ~ y ~ z
- for i=1,select("#",...) do
- res = res ~ select(i,...)
- end
- return res & 0xFFFFFFFF
- end
- end,
- btest = function (x, y, z, ...)
- if not z then
- return (((x or -1) & (y or -1)) & 0xFFFFFFFF) ~= 0
- else
- local res = x & y & z
- for i=1,select("#",...) do
- res = res & select(i,...)
- end
- return (res & 0xFFFFFFFF) ~= 0
- end
- end,
- lshift = function (a, b)
- return ((a & 0xFFFFFFFF) << b) & 0xFFFFFFFF
- end,
- rshift = function (a, b)
- return ((a & 0xFFFFFFFF) >> b) & 0xFFFFFFFF
- end,
- arshift = function (a, b)
- a = a & 0xFFFFFFFF
- if b <= 0 or (a & 0x80000000) == 0 then
- return (a >> b) & 0xFFFFFFFF
- else
- return ((a >> b) | ~(0xFFFFFFFF >> b)) & 0xFFFFFFFF
- end
- end,
- lrotate = function (a ,b)
- b = b & 31
- a = a & 0xFFFFFFFF
- a = (a << b) | (a >> (32 - b))
- return a & 0xFFFFFFFF
- end,
- rrotate = function (a, b)
- b = -b & 31
- a = a & 0xFFFFFFFF
- a = (a << b) | (a >> (32 - b))
- return a & 0xFFFFFFFF
- end,
- extract = function (a, f, w)
- return (a >> f) & ~(-1 << (w or 1))
- end,
- replace = function (a, v, f, w)
- local mask = ~(-1 << (w or 1))
- return ((a & ~(mask << f)) | ((v & mask) << f)) & 0xFFFFFFFF
- end,
-}
- ]] ) ()
-elseif bit then
- load ([[
-local band, bnot, rshift, lshift = bit.band, bit.bnot, bit.rshift, bit.lshift
-bit32 = {
- arshift = bit.arshift,
- band = band,
- bnot = bnot,
- bor = bit.bor,
- bxor = bit.bxor,
- btest = function(...)
- return band(...) ~= 0
- end,
- extract = function(a,f,w)
- return band(rshift(a,f),2^(w or 1)-1)
- end,
- lrotate = bit.rol,
- lshift = lshift,
- replace = function(a,v,f,w)
- local mask = 2^(w or 1)-1
- return band(a,bnot(lshift(mask,f)))+lshift(band(v,mask),f)
- end,
- rrotate = bit.ror,
- rshift = rshift,
-}
- ]] ) ()
-else
- xpcall(function() local _,t=require("bit32") if t then bit32=t end return end,function() end)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-lua"] = package.loaded["l-lua"] or true
-
--- original size: 6405, stripped down to: 2865
-
-if not modules then modules={} end modules ['l-lua']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local next,type,tonumber=next,type,tonumber
-LUAMAJORVERSION,LUAMINORVERSION=string.match(_VERSION,"^[^%d]+(%d+)%.(%d+).*$")
-LUAMAJORVERSION=tonumber(LUAMAJORVERSION) or 5
-LUAMINORVERSION=tonumber(LUAMINORVERSION) or 1
-LUAVERSION=LUAMAJORVERSION+LUAMINORVERSION/10
-if LUAVERSION<5.2 and jit then
- MINORVERSION=2
- LUAVERSION=5.2
-end
-if not lpeg then
- lpeg=require("lpeg")
-end
-if loadstring then
- local loadnormal=load
- function load(first,...)
- if type(first)=="string" then
- return loadstring(first,...)
- else
- return loadnormal(first,...)
- end
- end
-else
- loadstring=load
-end
-if not ipairs then
- local function iterate(a,i)
- i=i+1
- local v=a[i]
- if v~=nil then
- return i,v
- end
- end
- function ipairs(a)
- return iterate,a,0
- end
-end
-if not pairs then
- function pairs(t)
- return next,t
- end
-end
-if not table.unpack then
- table.unpack=_G.unpack
-elseif not unpack then
- _G.unpack=table.unpack
-end
-if not package.loaders then
- package.loaders=package.searchers
-end
-local print,select,tostring=print,select,tostring
-local inspectors={}
-function setinspector(kind,inspector)
- inspectors[kind]=inspector
-end
-function inspect(...)
- for s=1,select("#",...) do
- local value=select(s,...)
- if value==nil then
- print("nil")
- else
- local done=false
- local kind=type(value)
- local inspector=inspectors[kind]
- if inspector then
- done=inspector(value)
- if done then
- break
- end
- end
- for kind,inspector in next,inspectors do
- done=inspector(value)
- if done then
- break
- end
- end
- if not done then
- print(tostring(value))
- end
- end
- end
-end
-local dummy=function() end
-function optionalrequire(...)
- local ok,result=xpcall(require,dummy,...)
- if ok then
- return result
- end
-end
-local flush=io.flush
-if flush then
- local execute=os.execute if execute then function os.execute(...) flush() return execute(...) end end
- local exec=os.exec if exec then function os.exec (...) flush() return exec (...) end end
- local spawn=os.spawn if spawn then function os.spawn (...) flush() return spawn (...) end end
- local popen=io.popen if popen then function io.popen (...) flush() return popen (...) end end
-end
-FFISUPPORTED=type(ffi)=="table" and ffi.os~="" and ffi.arch~="" and ffi.load
-if not FFISUPPORTED then
- local okay;okay,ffi=pcall(require,"ffi")
- FFISUPPORTED=type(ffi)=="table" and ffi.os~="" and ffi.arch~="" and ffi.load
-end
-if not FFISUPPORTED then
- ffi=nil
-elseif not ffi.number then
- ffi.number=tonumber
-end
-if LUAVERSION>5.3 then
-end
-if status and os.setenv then
- os.setenv("engine",string.lower(status.luatex_engine or "unknown"))
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-macro"] = package.loaded["l-macro"] or true
-
--- original size: 10130, stripped down to: 5990
-
-if not modules then modules={} end modules ['l-macros']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local S,P,R,V,C,Cs,Cc,Ct,Carg=lpeg.S,lpeg.P,lpeg.R,lpeg.V,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Ct,lpeg.Carg
-local lpegmatch=lpeg.match
-local concat=table.concat
-local format,sub,match=string.format,string.sub,string.match
-local next,load,type=next,load,type
-local newline=S("\n\r")^1
-local continue=P("\\")*newline
-local whitespace=S(" \t\n\r")
-local spaces=S(" \t")+continue
-local nametoken=R("az","AZ","__","09")
-local name=nametoken^1
-local body=((continue/""+1)-newline)^1
-local lparent=P("(")
-local rparent=P(")")
-local noparent=1-(lparent+rparent)
-local nested=P { lparent*(noparent+V(1))^0*rparent }
-local escaped=P("\\")*P(1)
-local squote=P("'")
-local dquote=P('"')
-local quoted=dquote*(escaped+(1-dquote))^0*dquote+squote*(escaped+(1-squote))^0*squote
-local arguments=lparent*Ct((Cs((nested+(quoted+1-S("),")))^1)+S(", "))^0)*rparent
-local macros=lua.macros or {}
-lua.macros=macros
-local patterns={}
-local definitions={}
-local resolve
-local subparser
-local report_lua=function(...)
- if logs and logs.reporter then
- report_lua=logs.reporter("system","lua")
- report_lua(...)
- else
- print(format(...))
- end
-end
-local safeguard=P("local")*whitespace^1*name*(whitespace+P("="))
-resolve=safeguard+C(C(name)*(arguments^-1))/function(raw,s,a)
- local d=definitions[s]
- if d then
- if a then
- local n=#a
- local p=patterns[s][n]
- if p then
- local d=d[n]
- for i=1,n do
- a[i]=lpegmatch(subparser,a[i]) or a[i]
- end
- return lpegmatch(p,d,1,a) or d
- else
- return raw
- end
- else
- return d[0] or raw
- end
- elseif a then
- for i=1,#a do
- a[i]=lpegmatch(subparser,a[i]) or a[i]
- end
- return s.."("..concat(a,",")..")"
- else
- return raw
- end
-end
-subparser=Cs((resolve+P(1))^1)
-local enddefine=P("#enddefine")/""
-local beginregister=(C(name)*(arguments+Cc(false))*C((1-enddefine)^1)*enddefine)/function(k,a,v)
- local n=0
- if a then
- n=#a
- local pattern=P(false)
- for i=1,n do
- pattern=pattern+(P(a[i])*Carg(1))/function(t) return t[i] end
- end
- pattern=Cs((pattern+P(1))^1)
- local p=patterns[k]
- if not p then
- p={ [0]=false,false,false,false,false,false,false,false,false }
- patterns[k]=p
- end
- p[n]=pattern
- end
- local d=definitions[k]
- if not d then
- d={ a=a,[0]=false,false,false,false,false,false,false,false,false }
- definitions[k]=d
- end
- d[n]=lpegmatch(subparser,v) or v
- return ""
-end
-local register=(Cs(name)*(arguments+Cc(false))*spaces^0*Cs(body))/function(k,a,v)
- local n=0
- if a then
- n=#a
- local pattern=P(false)
- for i=1,n do
- pattern=pattern+(P(a[i])*Carg(1))/function(t) return t[i] end
- end
- pattern=Cs((pattern+P(1))^1)
- local p=patterns[k]
- if not p then
- p={ [0]=false,false,false,false,false,false,false,false,false }
- patterns[k]=p
- end
- p[n]=pattern
- end
- local d=definitions[k]
- if not d then
- d={ a=a,[0]=false,false,false,false,false,false,false,false,false }
- definitions[k]=d
- end
- d[n]=lpegmatch(subparser,v) or v
- return ""
-end
-local unregister=(C(name)*spaces^0*(arguments+Cc(false)))/function(k,a)
- local n=0
- if a then
- n=#a
- local p=patterns[k]
- if p then
- p[n]=false
- end
- end
- local d=definitions[k]
- if d then
- d[n]=false
- end
- return ""
-end
-local begindefine=(P("begindefine")*spaces^0/"")*beginregister
-local define=(P("define" )*spaces^0/"")*register
-local undefine=(P("undefine" )*spaces^0/"")*unregister
-local parser=Cs((((P("#")/"")*(define+begindefine+undefine)*(newline^0/"") )+resolve+P(1) )^0 )
-function macros.reset()
- definitions={}
- patterns={}
-end
-function macros.showdefinitions()
- for name,list in table.sortedhash(definitions) do
- local arguments=list.a
- if arguments then
- arguments="("..concat(arguments,",")..")"
- else
- arguments=""
- end
- print("macro: "..name..arguments)
- for i=0,#list do
- local l=list[i]
- if l then
- print(" "..l)
- end
- end
- end
-end
-function macros.resolvestring(str)
- return lpegmatch(parser,str) or str
-end
-function macros.resolving()
- return next(patterns)
-end
-local function reload(path,name,data)
- local only=match(name,".-([^/]+)%.lua")
- if only and only~="" then
- local name=path.."/"..only
- local f=io.open(name,"wb")
- f:write(data)
- f:close()
- local f=loadfile(name)
- os.remove(name)
- return f
- end
-end
-local function reload(path,name,data)
- if path and path~="" then
- local only=string.match(name,".-([^/]+)%.lua")
- if only and only~="" then
- local name=path.."/"..only.."-macro.lua"
- local f=io.open(name,"wb")
- if f then
- f:write(data)
- f:close()
- local l=loadfile(name)
- os.remove(name)
- return l
- end
- end
- end
- return load(data,name)
-end
-local function loaded(name,trace,detail)
- local f=io.open(name,"rb")
- if not f then
- return false,format("file '%s' not found",name)
- end
- local c=f:read("*a")
- if not c then
- return false,format("file '%s' is invalid",name)
- end
- f:close()
- local n=lpegmatch(parser,c)
- if trace then
- if #n~=#c then
- report_lua("macros expanded in '%s' (%i => %i bytes)",name,#c,#n)
- if detail then
- report_lua()
- report_lua(n)
- report_lua()
- end
- elseif detail then
- report_lua("no macros expanded in '%s'",name)
- end
- end
- return reload(lfs and lfs.currentdir(),name,n)
-end
-macros.loaded=loaded
-function required(name,trace)
- local filename=file.addsuffix(name,"lua")
- local fullname=resolvers and resolvers.findfile(filename) or filename
- if not fullname or fullname=="" then
- return false
- end
- local codeblob=package.loaded[fullname]
- if codeblob then
- return codeblob
- end
- local code,message=loaded(fullname,macros,trace,trace)
- if type(code)=="function" then
- code=code()
- else
- report_lua("error when loading '%s'",fullname)
- return false,message
- end
- if code==nil then
- code=false
- end
- package.loaded[fullname]=code
- return code
-end
-macros.required=required
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-sandbox"] = package.loaded["l-sandbox"] or true
-
--- original size: 9604, stripped down to: 6394
-
-if not modules then modules={} end modules ['l-sandbox']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local global=_G
-local next=next
-local unpack=unpack or table.unpack
-local type=type
-local tprint=texio and texio.write_nl or print
-local tostring=tostring
-local format=string.format
-local concat=table.concat
-local sort=table.sort
-local gmatch=string.gmatch
-local gsub=string.gsub
-local requiem=require
-sandbox={}
-local sandboxed=false
-local overloads={}
-local skiploads={}
-local initializers={}
-local finalizers={}
-local originals={}
-local comments={}
-local trace=false
-local logger=false
-local blocked={}
-local function report(...)
- tprint("sandbox ! "..format(...))
-end
-sandbox.report=report
-function sandbox.setreporter(r)
- report=r
- sandbox.report=r
-end
-function sandbox.settrace(v)
- trace=v
-end
-function sandbox.setlogger(l)
- logger=type(l)=="function" and l or false
-end
-local function register(func,overload,comment)
- if type(func)=="function" then
- if type(overload)=="string" then
- comment=overload
- overload=nil
- end
- local function f(...)
- if sandboxed then
- local overload=overloads[f]
- if overload then
- if logger then
- local result={ overload(func,...) }
- logger {
- comment=comments[f] or tostring(f),
- arguments={... },
- result=result[1] and true or false,
- }
- return unpack(result)
- else
- return overload(func,...)
- end
- else
- end
- else
- return func(...)
- end
- end
- if comment then
- comments[f]=comment
- if trace then
- report("registering function: %s",comment)
- end
- end
- overloads[f]=overload or false
- originals[f]=func
- return f
- end
-end
-local function redefine(func,comment)
- if type(func)=="function" then
- skiploads[func]=comment or comments[func] or "unknown"
- if overloads[func]==false then
- overloads[func]=nil
- end
- end
-end
-sandbox.register=register
-sandbox.redefine=redefine
-function sandbox.original(func)
- return originals and originals[func] or func
-end
-function sandbox.overload(func,overload,comment)
- comment=comment or comments[func] or "?"
- if type(func)~="function" then
- if trace then
- report("overloading unknown function: %s",comment)
- end
- elseif type(overload)~="function" then
- if trace then
- report("overloading function with bad overload: %s",comment)
- end
- elseif overloads[func]==nil then
- if trace then
- report("function is not registered: %s",comment)
- end
- elseif skiploads[func] then
- if trace then
- report("function is not skipped: %s",comment)
- end
- else
- if trace then
- report("overloading function: %s",comment)
- end
- overloads[func]=overload
- end
- return func
-end
-local function whatever(specification,what,target)
- if type(specification)~="table" then
- report("%s needs a specification",what)
- elseif type(specification.category)~="string" or type(specification.action)~="function" then
- report("%s needs a category and action",what)
- elseif not sandboxed then
- target[#target+1]=specification
- elseif trace then
- report("already enabled, discarding %s",what)
- end
-end
-function sandbox.initializer(specification)
- whatever(specification,"initializer",initializers)
-end
-function sandbox.finalizer(specification)
- whatever(specification,"finalizer",finalizers)
-end
-function require(name)
- local n=gsub(name,"^.*[\\/]","")
- local n=gsub(n,"[%.].*$","")
- local b=blocked[n]
- if b==false then
- return nil
- elseif b then
- if trace then
- report("using blocked: %s",n)
- end
- return b
- else
- if trace then
- report("requiring: %s",name)
- end
- return requiem(name)
- end
-end
-function blockrequire(name,lib)
- if trace then
- report("preventing reload of: %s",name)
- end
- blocked[name]=lib or _G[name] or false
-end
-function sandbox.enable()
- if not sandboxed then
- debug={
- traceback=debug.traceback,
- }
- for i=1,#initializers do
- initializers[i].action()
- end
- for i=1,#finalizers do
- finalizers[i].action()
- end
- local nnot=0
- local nyes=0
- local cnot={}
- local cyes={}
- local skip={}
- for k,v in next,overloads do
- local c=comments[k]
- if v then
- if c then
- cyes[#cyes+1]=c
- else
- nyes=nyes+1
- end
- else
- if c then
- cnot[#cnot+1]=c
- else
- nnot=nnot+1
- end
- end
- end
- for k,v in next,skiploads do
- skip[#skip+1]=v
- end
- if #cyes>0 then
- sort(cyes)
- report("overloaded known: %s",concat(cyes," | "))
- end
- if nyes>0 then
- report("overloaded unknown: %s",nyes)
- end
- if #cnot>0 then
- sort(cnot)
- report("not overloaded known: %s",concat(cnot," | "))
- end
- if nnot>0 then
- report("not overloaded unknown: %s",nnot)
- end
- if #skip>0 then
- sort(skip)
- report("not overloaded redefined: %s",concat(skip," | "))
- end
- initializers=nil
- finalizers=nil
- originals=nil
- sandboxed=true
- end
-end
-blockrequire("lfs",lfs)
-blockrequire("io",io)
-blockrequire("os",os)
-blockrequire("ffi",ffi)
-local function supported(library)
- local l=_G[library]
- return l
-end
-loadfile=register(loadfile,"loadfile")
-if supported("lua") then
- lua.openfile=register(lua.openfile,"lua.openfile")
-end
-if supported("io") then
- io.open=register(io.open,"io.open")
- io.popen=register(io.popen,"io.popen")
- io.lines=register(io.lines,"io.lines")
- io.output=register(io.output,"io.output")
- io.input=register(io.input,"io.input")
-end
-if supported("os") then
- os.execute=register(os.execute,"os.execute")
- os.spawn=register(os.spawn,"os.spawn")
- os.exec=register(os.exec,"os.exec")
- os.rename=register(os.rename,"os.rename")
- os.remove=register(os.remove,"os.remove")
-end
-if supported("lfs") then
- lfs.chdir=register(lfs.chdir,"lfs.chdir")
- lfs.mkdir=register(lfs.mkdir,"lfs.mkdir")
- lfs.rmdir=register(lfs.rmdir,"lfs.rmdir")
- lfs.isfile=register(lfs.isfile,"lfs.isfile")
- lfs.isdir=register(lfs.isdir,"lfs.isdir")
- lfs.attributes=register(lfs.attributes,"lfs.attributes")
- lfs.dir=register(lfs.dir,"lfs.dir")
- lfs.lock_dir=register(lfs.lock_dir,"lfs.lock_dir")
- lfs.touch=register(lfs.touch,"lfs.touch")
- lfs.link=register(lfs.link,"lfs.link")
- lfs.setmode=register(lfs.setmode,"lfs.setmode")
- lfs.readlink=register(lfs.readlink,"lfs.readlink")
- lfs.shortname=register(lfs.shortname,"lfs.shortname")
- lfs.symlinkattributes=register(lfs.symlinkattributes,"lfs.symlinkattributes")
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-package"] = package.loaded["l-package"] or true
-
--- original size: 12566, stripped down to: 8937
-
-if not modules then modules={} end modules ['l-package']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,unpack=type,unpack
-local gsub,format,find=string.gsub,string.format,string.find
-local insert,remove=table.insert,table.remove
-local P,S,Cs,lpegmatch=lpeg.P,lpeg.S,lpeg.Cs,lpeg.match
-local package=package
-local searchers=package.searchers or package.loaders
-local filejoin=file and file.join or function(path,name) return path.."/"..name end
-local isreadable=file and file.is_readable or function(name) local f=io.open(name) if f then f:close() return true end end
-local addsuffix=file and file.addsuffix or function(name,suffix) return name.."."..suffix end
-local function cleanpath(path)
- return path
-end
-local pattern=Cs((((1-S("\\/"))^0*(S("\\/")^1/"/"))^0*(P(".")^1/"/"+P(1))^1)*-1)
-local function lualibfile(name)
- return lpegmatch(pattern,name) or name
-end
-local offset=luarocks and 1 or 0
-local helpers=package.helpers or {
- cleanpath=cleanpath,
- lualibfile=lualibfile,
- trace=false,
- report=function(...) print(format(...)) end,
- builtin={
- ["preload table"]=searchers[1+offset],
- ["path specification"]=searchers[2+offset],
- ["cpath specification"]=searchers[3+offset],
- ["all in one fallback"]=searchers[4+offset],
- },
- methods={},
- sequence={
- "reset loaded",
- "already loaded",
- "preload table",
- "qualified path",
- "lua extra list",
- "lib extra list",
- "path specification",
- "cpath specification",
- "all in one fallback",
- "not loaded",
- }
-}
-package.helpers=helpers
-local methods=helpers.methods
-local builtin=helpers.builtin
-local extraluapaths={}
-local extralibpaths={}
-local checkedfiles={}
-local luapaths=nil
-local libpaths=nil
-local oldluapath=nil
-local oldlibpath=nil
-local nofextralua=-1
-local nofextralib=-1
-local nofpathlua=-1
-local nofpathlib=-1
-local function listpaths(what,paths)
- local nofpaths=#paths
- if nofpaths>0 then
- for i=1,nofpaths do
- helpers.report("using %s path %i: %s",what,i,paths[i])
- end
- else
- helpers.report("no %s paths defined",what)
- end
- return nofpaths
-end
-local function getextraluapaths()
- if helpers.trace and #extraluapaths~=nofextralua then
- nofextralua=listpaths("extra lua",extraluapaths)
- end
- return extraluapaths
-end
-local function getextralibpaths()
- if helpers.trace and #extralibpaths~=nofextralib then
- nofextralib=listpaths("extra lib",extralibpaths)
- end
- return extralibpaths
-end
-local function getluapaths()
- local luapath=package.path or ""
- if oldluapath~=luapath then
- luapaths=file.splitpath(luapath,";")
- oldluapath=luapath
- nofpathlua=-1
- end
- if helpers.trace and #luapaths~=nofpathlua then
- nofpathlua=listpaths("builtin lua",luapaths)
- end
- return luapaths
-end
-local function getlibpaths()
- local libpath=package.cpath or ""
- if oldlibpath~=libpath then
- libpaths=file.splitpath(libpath,";")
- oldlibpath=libpath
- nofpathlib=-1
- end
- if helpers.trace and #libpaths~=nofpathlib then
- nofpathlib=listpaths("builtin lib",libpaths)
- end
- return libpaths
-end
-package.luapaths=getluapaths
-package.libpaths=getlibpaths
-package.extraluapaths=getextraluapaths
-package.extralibpaths=getextralibpaths
-local hashes={
- lua={},
- lib={},
-}
-local function registerpath(tag,what,target,...)
- local pathlist={... }
- local cleanpath=helpers.cleanpath
- local trace=helpers.trace
- local report=helpers.report
- local hash=hashes[what]
- local function add(path)
- local path=cleanpath(path)
- if not hash[path] then
- target[#target+1]=path
- hash[path]=true
- if trace then
- report("registered %s path %s: %s",tag,#target,path)
- end
- else
- if trace then
- report("duplicate %s path: %s",tag,path)
- end
- end
- end
- for p=1,#pathlist do
- local path=pathlist[p]
- if type(path)=="table" then
- for i=1,#path do
- add(path[i])
- end
- else
- add(path)
- end
- end
-end
-local function pushpath(tag,what,target,path)
- local path=helpers.cleanpath(path)
- insert(target,1,path)
- if helpers.trace then
- helpers.report("pushing %s path in front: %s",tag,path)
- end
-end
-local function poppath(tag,what,target)
- local path=remove(target,1)
- if helpers.trace then
- if path then
- helpers.report("popping %s path from front: %s",tag,path)
- else
- helpers.report("no %s path to pop",tag)
- end
- end
-end
-helpers.registerpath=registerpath
-function package.extraluapath(...)
- registerpath("extra lua","lua",extraluapaths,...)
-end
-function package.pushluapath(path)
- pushpath("extra lua","lua",extraluapaths,path)
-end
-function package.popluapath()
- poppath("extra lua","lua",extraluapaths)
-end
-function package.extralibpath(...)
- registerpath("extra lib","lib",extralibpaths,...)
-end
-function package.pushlibpath(path)
- pushpath("extra lib","lib",extralibpaths,path)
-end
-function package.poplibpath()
- poppath("extra lib","lua",extralibpaths)
-end
-local function loadedaslib(resolved,rawname)
- local base=gsub(rawname,"%.","_")
- local init="luaopen_"..gsub(base,"%.","_")
- local data={ resolved,init,"" }
- checkedfiles[#checkedfiles+1]=data
- if helpers.trace then
- helpers.report("calling loadlib with '%s' with init '%s'",resolved,init)
- end
- local a,b,c=package.loadlib(resolved,init)
- if not a and type(b)=="string" then
- data[3]=string.fullstrip(b or "unknown error")
- end
- return a,b,c
-end
-helpers.loadedaslib=loadedaslib
-local function loadedbypath(name,rawname,paths,islib,what)
- local trace=helpers.trace
- for p=1,#paths do
- local path=paths[p]
- local resolved=filejoin(path,name)
- if trace then
- helpers.report("%s path, identifying '%s' on '%s'",what,name,path)
- end
- if isreadable(resolved) then
- if trace then
- helpers.report("%s path, '%s' found on '%s'",what,name,resolved)
- end
- if islib then
- return loadedaslib(resolved,rawname)
- else
- return loadfile(resolved)
- end
- end
- end
-end
-helpers.loadedbypath=loadedbypath
-local function loadedbyname(name,rawname)
- if find(name,"^/") or find(name,"^[a-zA-Z]:/") then
- local trace=helpers.trace
- if trace then
- helpers.report("qualified name, identifying '%s'",what,name)
- end
- if isreadable(name) then
- if trace then
- helpers.report("qualified name, '%s' found",what,name)
- end
- return loadfile(name)
- end
- end
-end
-helpers.loadedbyname=loadedbyname
-methods["reset loaded"]=function(name)
- checkedfiles={}
- return false
-end
-methods["already loaded"]=function(name)
- return package.loaded[name]
-end
-methods["preload table"]=function(name)
- local f=builtin["preload table"]
- if f then
- return f(name)
- end
-end
-methods["qualified path"]=function(name)
- return loadedbyname(addsuffix(lualibfile(name),"lua"),name)
-end
-methods["lua extra list"]=function(name)
- return loadedbypath(addsuffix(lualibfile(name),"lua"),name,getextraluapaths(),false,"lua")
-end
-methods["lib extra list"]=function(name)
- return loadedbypath(addsuffix(lualibfile(name),os.libsuffix),name,getextralibpaths(),true,"lib")
-end
-methods["path specification"]=function(name)
- local f=builtin["path specification"]
- if f then
- getluapaths()
- return f(name)
- end
-end
-methods["cpath specification"]=function(name)
- local f=builtin["cpath specification"]
- if f then
- getlibpaths()
- return f(name)
- end
-end
-methods["all in one fallback"]=function(name)
- local f=builtin["all in one fallback"]
- if f then
- return f(name)
- end
-end
-methods["not loaded"]=function(name)
- if helpers.trace then
- helpers.report("unable to locate '%s'",name or "?")
- for i=1,#checkedfiles do
- helpers.report("checked file '%s', initializer '%s', message '%s'",unpack(checkedfiles[i]))
- end
- end
- return nil
-end
-local level=0
-local used={}
-helpers.traceused=false
-function helpers.loaded(name)
- local sequence=helpers.sequence
- level=level+1
- for i=1,#sequence do
- local method=sequence[i]
- local lookup=method and methods[method]
- if type(lookup)=="function" then
- if helpers.trace then
- helpers.report("%s, level '%s', method '%s', name '%s'","locating",level,method,name)
- end
- local result,rest=lookup(name)
- if type(result)=="function" then
- if helpers.trace then
- helpers.report("%s, level '%s', method '%s', name '%s'","found",level,method,name)
- end
- if helpers.traceused then
- used[#used+1]={ level=level,name=name }
- end
- level=level-1
- return result,rest
- end
- end
- end
- level=level-1
- return nil
-end
-function helpers.showused()
- local n=#used
- if n>0 then
- helpers.report("%s libraries loaded:",n)
- helpers.report()
- for i=1,n do
- local u=used[i]
- helpers.report("%i %a",u.level,u.name)
- end
- helpers.report()
- end
-end
-function helpers.unload(name)
- if helpers.trace then
- if package.loaded[name] then
- helpers.report("unloading, name '%s', %s",name,"done")
- else
- helpers.report("unloading, name '%s', %s",name,"not loaded")
- end
- end
- package.loaded[name]=nil
-end
-table.insert(searchers,1,helpers.loaded)
-if context then
- package.path=""
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-lpeg"] = package.loaded["l-lpeg"] or true
-
--- original size: 38703, stripped down to: 19489
-
-if not modules then modules={} end modules ['l-lpeg']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-lpeg=require("lpeg")
-local lpeg=lpeg
-if not lpeg.print then function lpeg.print(...) print(lpeg.pcode(...)) end end
-local type,next,tostring=type,next,tostring
-local byte,char,gmatch,format=string.byte,string.char,string.gmatch,string.format
-local floor=math.floor
-local P,R,S,V,Ct,C,Cs,Cc,Cp,Cmt=lpeg.P,lpeg.R,lpeg.S,lpeg.V,lpeg.Ct,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Cp,lpeg.Cmt
-local lpegtype,lpegmatch,lpegprint=lpeg.type,lpeg.match,lpeg.print
-if setinspector then
- setinspector("lpeg",function(v) if lpegtype(v) then lpegprint(v) return true end end)
-end
-lpeg.patterns=lpeg.patterns or {}
-local patterns=lpeg.patterns
-local anything=P(1)
-local endofstring=P(-1)
-local alwaysmatched=P(true)
-patterns.anything=anything
-patterns.endofstring=endofstring
-patterns.beginofstring=alwaysmatched
-patterns.alwaysmatched=alwaysmatched
-local sign=S('+-')
-local zero=P('0')
-local digit=R('09')
-local digits=digit^1
-local octdigit=R("07")
-local octdigits=octdigit^1
-local lowercase=R("az")
-local uppercase=R("AZ")
-local underscore=P("_")
-local hexdigit=digit+lowercase+uppercase
-local hexdigits=hexdigit^1
-local cr,lf,crlf=P("\r"),P("\n"),P("\r\n")
-local newline=P("\r")*(P("\n")+P(true))+P("\n")
-local escaped=P("\\")*anything
-local squote=P("'")
-local dquote=P('"')
-local space=P(" ")
-local period=P(".")
-local comma=P(",")
-local utfbom_32_be=P('\000\000\254\255')
-local utfbom_32_le=P('\255\254\000\000')
-local utfbom_16_be=P('\254\255')
-local utfbom_16_le=P('\255\254')
-local utfbom_8=P('\239\187\191')
-local utfbom=utfbom_32_be+utfbom_32_le+utfbom_16_be+utfbom_16_le+utfbom_8
-local utftype=utfbom_32_be*Cc("utf-32-be")+utfbom_32_le*Cc("utf-32-le")+utfbom_16_be*Cc("utf-16-be")+utfbom_16_le*Cc("utf-16-le")+utfbom_8*Cc("utf-8")+alwaysmatched*Cc("utf-8")
-local utfstricttype=utfbom_32_be*Cc("utf-32-be")+utfbom_32_le*Cc("utf-32-le")+utfbom_16_be*Cc("utf-16-be")+utfbom_16_le*Cc("utf-16-le")+utfbom_8*Cc("utf-8")
-local utfoffset=utfbom_32_be*Cc(4)+utfbom_32_le*Cc(4)+utfbom_16_be*Cc(2)+utfbom_16_le*Cc(2)+utfbom_8*Cc(3)+Cc(0)
-local utf8next=R("\128\191")
-patterns.utfbom_32_be=utfbom_32_be
-patterns.utfbom_32_le=utfbom_32_le
-patterns.utfbom_16_be=utfbom_16_be
-patterns.utfbom_16_le=utfbom_16_le
-patterns.utfbom_8=utfbom_8
-patterns.utf_16_be_nl=P("\000\r\000\n")+P("\000\r")+P("\000\n")
-patterns.utf_16_le_nl=P("\r\000\n\000")+P("\r\000")+P("\n\000")
-patterns.utf_32_be_nl=P("\000\000\000\r\000\000\000\n")+P("\000\000\000\r")+P("\000\000\000\n")
-patterns.utf_32_le_nl=P("\r\000\000\000\n\000\000\000")+P("\r\000\000\000")+P("\n\000\000\000")
-patterns.utf8one=R("\000\127")
-patterns.utf8two=R("\194\223")*utf8next
-patterns.utf8three=R("\224\239")*utf8next*utf8next
-patterns.utf8four=R("\240\244")*utf8next*utf8next*utf8next
-patterns.utfbom=utfbom
-patterns.utftype=utftype
-patterns.utfstricttype=utfstricttype
-patterns.utfoffset=utfoffset
-local utf8char=patterns.utf8one+patterns.utf8two+patterns.utf8three+patterns.utf8four
-local validutf8char=utf8char^0*endofstring*Cc(true)+Cc(false)
-local utf8character=P(1)*R("\128\191")^0
-patterns.utf8=utf8char
-patterns.utf8char=utf8char
-patterns.utf8character=utf8character
-patterns.validutf8=validutf8char
-patterns.validutf8char=validutf8char
-local eol=S("\n\r")
-local spacer=S(" \t\f\v")
-local whitespace=eol+spacer
-local nonspacer=1-spacer
-local nonwhitespace=1-whitespace
-patterns.eol=eol
-patterns.spacer=spacer
-patterns.whitespace=whitespace
-patterns.nonspacer=nonspacer
-patterns.nonwhitespace=nonwhitespace
-local stripper=spacer^0*C((spacer^0*nonspacer^1)^0)
-local fullstripper=whitespace^0*C((whitespace^0*nonwhitespace^1)^0)
-local collapser=Cs(spacer^0/""*nonspacer^0*((spacer^0/" "*nonspacer^1)^0))
-local nospacer=Cs((whitespace^1/""+nonwhitespace^1)^0)
-local b_collapser=Cs(whitespace^0/""*(nonwhitespace^1+whitespace^1/" ")^0)
-local m_collapser=Cs((nonwhitespace^1+whitespace^1/" ")^0)
-local e_collapser=Cs((whitespace^1*endofstring/""+nonwhitespace^1+whitespace^1/" ")^0)
-local x_collapser=Cs((nonwhitespace^1+whitespace^1/"" )^0)
-local b_stripper=Cs(spacer^0/""*(nonspacer^1+spacer^1/" ")^0)
-local m_stripper=Cs((nonspacer^1+spacer^1/" ")^0)
-local e_stripper=Cs((spacer^1*endofstring/""+nonspacer^1+spacer^1/" ")^0)
-local x_stripper=Cs((nonspacer^1+spacer^1/"" )^0)
-patterns.stripper=stripper
-patterns.fullstripper=fullstripper
-patterns.collapser=collapser
-patterns.nospacer=nospacer
-patterns.b_collapser=b_collapser
-patterns.m_collapser=m_collapser
-patterns.e_collapser=e_collapser
-patterns.x_collapser=x_collapser
-patterns.b_stripper=b_stripper
-patterns.m_stripper=m_stripper
-patterns.e_stripper=e_stripper
-patterns.x_stripper=x_stripper
-patterns.lowercase=lowercase
-patterns.uppercase=uppercase
-patterns.letter=patterns.lowercase+patterns.uppercase
-patterns.space=space
-patterns.tab=P("\t")
-patterns.spaceortab=patterns.space+patterns.tab
-patterns.newline=newline
-patterns.emptyline=newline^1
-patterns.equal=P("=")
-patterns.comma=comma
-patterns.commaspacer=comma*spacer^0
-patterns.period=period
-patterns.colon=P(":")
-patterns.semicolon=P(";")
-patterns.underscore=underscore
-patterns.escaped=escaped
-patterns.squote=squote
-patterns.dquote=dquote
-patterns.nosquote=(escaped+(1-squote))^0
-patterns.nodquote=(escaped+(1-dquote))^0
-patterns.unsingle=(squote/"")*patterns.nosquote*(squote/"")
-patterns.undouble=(dquote/"")*patterns.nodquote*(dquote/"")
-patterns.unquoted=patterns.undouble+patterns.unsingle
-patterns.unspacer=((patterns.spacer^1)/"")^0
-patterns.singlequoted=squote*patterns.nosquote*squote
-patterns.doublequoted=dquote*patterns.nodquote*dquote
-patterns.quoted=patterns.doublequoted+patterns.singlequoted
-patterns.digit=digit
-patterns.digits=digits
-patterns.octdigit=octdigit
-patterns.octdigits=octdigits
-patterns.hexdigit=hexdigit
-patterns.hexdigits=hexdigits
-patterns.sign=sign
-patterns.cardinal=digits
-patterns.integer=sign^-1*digits
-patterns.unsigned=digit^0*period*digits
-patterns.float=sign^-1*patterns.unsigned
-patterns.cunsigned=digit^0*comma*digits
-patterns.cpunsigned=digit^0*(period+comma)*digits
-patterns.cfloat=sign^-1*patterns.cunsigned
-patterns.cpfloat=sign^-1*patterns.cpunsigned
-patterns.number=patterns.float+patterns.integer
-patterns.cnumber=patterns.cfloat+patterns.integer
-patterns.cpnumber=patterns.cpfloat+patterns.integer
-patterns.oct=zero*octdigits
-patterns.octal=patterns.oct
-patterns.HEX=zero*P("X")*(digit+uppercase)^1
-patterns.hex=zero*P("x")*(digit+lowercase)^1
-patterns.hexadecimal=zero*S("xX")*hexdigits
-patterns.hexafloat=sign^-1*zero*S("xX")*(hexdigit^0*period*hexdigits+hexdigits*period*hexdigit^0+hexdigits)*(S("pP")*sign^-1*hexdigits)^-1
-patterns.decafloat=sign^-1*(digit^0*period*digits+digits*period*digit^0+digits)*S("eE")*sign^-1*digits
-patterns.propername=(uppercase+lowercase+underscore)*(uppercase+lowercase+underscore+digit)^0*endofstring
-patterns.somecontent=(anything-newline-space)^1
-patterns.beginline=#(1-newline)
-patterns.longtostring=Cs(whitespace^0/""*((patterns.quoted+nonwhitespace^1+whitespace^1/""*(endofstring+Cc(" ")))^0))
-local function anywhere(pattern)
- return (1-P(pattern))^0*P(pattern)
-end
-lpeg.anywhere=anywhere
-function lpeg.instringchecker(p)
- p=anywhere(p)
- return function(str)
- return lpegmatch(p,str) and true or false
- end
-end
-function lpeg.splitter(pattern,action)
- if action then
- return (((1-P(pattern))^1)/action+1)^0
- else
- return (Cs((1-P(pattern))^1)+1)^0
- end
-end
-function lpeg.tsplitter(pattern,action)
- if action then
- return Ct((((1-P(pattern))^1)/action+1)^0)
- else
- return Ct((Cs((1-P(pattern))^1)+1)^0)
- end
-end
-local splitters_s,splitters_m,splitters_t={},{},{}
-local function splitat(separator,single)
- local splitter=(single and splitters_s[separator]) or splitters_m[separator]
- if not splitter then
- separator=P(separator)
- local other=C((1-separator)^0)
- if single then
- local any=anything
- splitter=other*(separator*C(any^0)+"")
- splitters_s[separator]=splitter
- else
- splitter=other*(separator*other)^0
- splitters_m[separator]=splitter
- end
- end
- return splitter
-end
-local function tsplitat(separator)
- local splitter=splitters_t[separator]
- if not splitter then
- splitter=Ct(splitat(separator))
- splitters_t[separator]=splitter
- end
- return splitter
-end
-lpeg.splitat=splitat
-lpeg.tsplitat=tsplitat
-function string.splitup(str,separator)
- if not separator then
- separator=","
- end
- return lpegmatch(splitters_m[separator] or splitat(separator),str)
-end
-local cache={}
-function lpeg.split(separator,str)
- local c=cache[separator]
- if not c then
- c=tsplitat(separator)
- cache[separator]=c
- end
- return lpegmatch(c,str)
-end
-function string.split(str,separator)
- if separator then
- local c=cache[separator]
- if not c then
- c=tsplitat(separator)
- cache[separator]=c
- end
- return lpegmatch(c,str)
- else
- return { str }
- end
-end
-local spacing=patterns.spacer^0*newline
-local empty=spacing*Cc("")
-local nonempty=Cs((1-spacing)^1)*spacing^-1
-local content=(empty+nonempty)^1
-patterns.textline=content
-local linesplitter=tsplitat(newline)
-patterns.linesplitter=linesplitter
-function string.splitlines(str)
- return lpegmatch(linesplitter,str)
-end
-local cache={}
-function lpeg.checkedsplit(separator,str)
- local c=cache[separator]
- if not c then
- separator=P(separator)
- local other=C((1-separator)^1)
- c=Ct(separator^0*other*(separator^1*other)^0)
- cache[separator]=c
- end
- return lpegmatch(c,str)
-end
-function string.checkedsplit(str,separator)
- local c=cache[separator]
- if not c then
- separator=P(separator)
- local other=C((1-separator)^1)
- c=Ct(separator^0*other*(separator^1*other)^0)
- cache[separator]=c
- end
- return lpegmatch(c,str)
-end
-local function f2(s) local c1,c2=byte(s,1,2) return c1*64+c2-12416 end
-local function f3(s) local c1,c2,c3=byte(s,1,3) return (c1*64+c2)*64+c3-925824 end
-local function f4(s) local c1,c2,c3,c4=byte(s,1,4) return ((c1*64+c2)*64+c3)*64+c4-63447168 end
-local utf8byte=patterns.utf8one/byte+patterns.utf8two/f2+patterns.utf8three/f3+patterns.utf8four/f4
-patterns.utf8byte=utf8byte
-local cache={}
-function lpeg.stripper(str)
- if type(str)=="string" then
- local s=cache[str]
- if not s then
- s=Cs(((S(str)^1)/""+1)^0)
- cache[str]=s
- end
- return s
- else
- return Cs(((str^1)/""+1)^0)
- end
-end
-local cache={}
-function lpeg.keeper(str)
- if type(str)=="string" then
- local s=cache[str]
- if not s then
- s=Cs((((1-S(str))^1)/""+1)^0)
- cache[str]=s
- end
- return s
- else
- return Cs((((1-str)^1)/""+1)^0)
- end
-end
-function lpeg.frontstripper(str)
- return (P(str)+P(true))*Cs(anything^0)
-end
-function lpeg.endstripper(str)
- return Cs((1-P(str)*endofstring)^0)
-end
-function lpeg.replacer(one,two,makefunction,isutf)
- local pattern
- local u=isutf and utf8char or 1
- if type(one)=="table" then
- local no=#one
- local p=P(false)
- if no==0 then
- for k,v in next,one do
- p=p+P(k)/v
- end
- pattern=Cs((p+u)^0)
- elseif no==1 then
- local o=one[1]
- one,two=P(o[1]),o[2]
- pattern=Cs((one/two+u)^0)
- else
- for i=1,no do
- local o=one[i]
- p=p+P(o[1])/o[2]
- end
- pattern=Cs((p+u)^0)
- end
- else
- pattern=Cs((P(one)/(two or "")+u)^0)
- end
- if makefunction then
- return function(str)
- return lpegmatch(pattern,str)
- end
- else
- return pattern
- end
-end
-function lpeg.finder(lst,makefunction,isutf)
- local pattern
- if type(lst)=="table" then
- pattern=P(false)
- if #lst==0 then
- for k,v in next,lst do
- pattern=pattern+P(k)
- end
- else
- for i=1,#lst do
- pattern=pattern+P(lst[i])
- end
- end
- else
- pattern=P(lst)
- end
- if isutf then
- pattern=((utf8char or 1)-pattern)^0*pattern
- else
- pattern=(1-pattern)^0*pattern
- end
- if makefunction then
- return function(str)
- return lpegmatch(pattern,str)
- end
- else
- return pattern
- end
-end
-local splitters_f,splitters_s={},{}
-function lpeg.firstofsplit(separator)
- local splitter=splitters_f[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=C((1-pattern)^0)
- splitters_f[separator]=splitter
- end
- return splitter
-end
-function lpeg.secondofsplit(separator)
- local splitter=splitters_s[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=(1-pattern)^0*pattern*C(anything^0)
- splitters_s[separator]=splitter
- end
- return splitter
-end
-local splitters_s,splitters_p={},{}
-function lpeg.beforesuffix(separator)
- local splitter=splitters_s[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=C((1-pattern)^0)*pattern*endofstring
- splitters_s[separator]=splitter
- end
- return splitter
-end
-function lpeg.afterprefix(separator)
- local splitter=splitters_p[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=pattern*C(anything^0)
- splitters_p[separator]=splitter
- end
- return splitter
-end
-function lpeg.balancer(left,right)
- left,right=P(left),P(right)
- return P { left*((1-left-right)+V(1))^0*right }
-end
-function lpeg.counter(pattern,action)
- local n=0
- local pattern=(P(pattern)/function() n=n+1 end+anything)^0
- if action then
- return function(str) n=0;lpegmatch(pattern,str);action(n) end
- else
- return function(str) n=0;lpegmatch(pattern,str);return n end
- end
-end
-function lpeg.is_lpeg(p)
- return p and lpegtype(p)=="pattern"
-end
-function lpeg.oneof(list,...)
- if type(list)~="table" then
- list={ list,... }
- end
- local p=P(list[1])
- for l=2,#list do
- p=p+P(list[l])
- end
- return p
-end
-local sort=table.sort
-local function copyindexed(old)
- local new={}
- for i=1,#old do
- new[i]=old
- end
- return new
-end
-local function sortedkeys(tab)
- local keys,s={},0
- for key,_ in next,tab do
- s=s+1
- keys[s]=key
- end
- sort(keys)
- return keys
-end
-function lpeg.append(list,pp,delayed,checked)
- local p=pp
- if #list>0 then
- local keys=copyindexed(list)
- sort(keys)
- for i=#keys,1,-1 do
- local k=keys[i]
- if p then
- p=P(k)+p
- else
- p=P(k)
- end
- end
- elseif delayed then
- local keys=sortedkeys(list)
- if p then
- for i=1,#keys,1 do
- local k=keys[i]
- local v=list[k]
- p=P(k)/list+p
- end
- else
- for i=1,#keys do
- local k=keys[i]
- local v=list[k]
- if p then
- p=P(k)+p
- else
- p=P(k)
- end
- end
- if p then
- p=p/list
- end
- end
- elseif checked then
- local keys=sortedkeys(list)
- for i=1,#keys do
- local k=keys[i]
- local v=list[k]
- if p then
- if k==v then
- p=P(k)+p
- else
- p=P(k)/v+p
- end
- else
- if k==v then
- p=P(k)
- else
- p=P(k)/v
- end
- end
- end
- else
- local keys=sortedkeys(list)
- for i=1,#keys do
- local k=keys[i]
- local v=list[k]
- if p then
- p=P(k)/v+p
- else
- p=P(k)/v
- end
- end
- end
- return p
-end
-local p_false=P(false)
-local p_true=P(true)
-local lower=utf and utf.lower or string.lower
-local upper=utf and utf.upper or string.upper
-function lpeg.setutfcasers(l,u)
- lower=l or lower
- upper=u or upper
-end
-local function make1(t,rest)
- local p=p_false
- local keys=sortedkeys(t)
- for i=1,#keys do
- local k=keys[i]
- if k~="" then
- local v=t[k]
- if v==true then
- p=p+P(k)*p_true
- elseif v==false then
- else
- p=p+P(k)*make1(v,v[""])
- end
- end
- end
- if rest then
- p=p+p_true
- end
- return p
-end
-local function make2(t,rest)
- local p=p_false
- local keys=sortedkeys(t)
- for i=1,#keys do
- local k=keys[i]
- if k~="" then
- local v=t[k]
- if v==true then
- p=p+(P(lower(k))+P(upper(k)))*p_true
- elseif v==false then
- else
- p=p+(P(lower(k))+P(upper(k)))*make2(v,v[""])
- end
- end
- end
- if rest then
- p=p+p_true
- end
- return p
-end
-local function utfchartabletopattern(list,insensitive)
- local tree={}
- local n=#list
- if n==0 then
- for s in next,list do
- local t=tree
- local p,pk
- for c in gmatch(s,".") do
- if t==true then
- t={ [c]=true,[""]=true }
- p[pk]=t
- p=t
- t=false
- elseif t==false then
- t={ [c]=false }
- p[pk]=t
- p=t
- t=false
- else
- local tc=t[c]
- if not tc then
- tc=false
- t[c]=false
- end
- p=t
- t=tc
- end
- pk=c
- end
- if t==false then
- p[pk]=true
- elseif t==true then
- else
- t[""]=true
- end
- end
- else
- for i=1,n do
- local s=list[i]
- local t=tree
- local p,pk
- for c in gmatch(s,".") do
- if t==true then
- t={ [c]=true,[""]=true }
- p[pk]=t
- p=t
- t=false
- elseif t==false then
- t={ [c]=false }
- p[pk]=t
- p=t
- t=false
- else
- local tc=t[c]
- if not tc then
- tc=false
- t[c]=false
- end
- p=t
- t=tc
- end
- pk=c
- end
- if t==false then
- p[pk]=true
- elseif t==true then
- else
- t[""]=true
- end
- end
- end
- return (insensitive and make2 or make1)(tree)
-end
-lpeg.utfchartabletopattern=utfchartabletopattern
-function lpeg.utfreplacer(list,insensitive)
- local pattern=Cs((utfchartabletopattern(list,insensitive)/list+utf8character)^0)
- return function(str)
- return lpegmatch(pattern,str) or str
- end
-end
-patterns.containseol=lpeg.finder(eol)
-local function nextstep(n,step,result)
- local m=n%step
- local d=floor(n/step)
- if d>0 then
- local v=V(tostring(step))
- local s=result.start
- for i=1,d do
- if s then
- s=v*s
- else
- s=v
- end
- end
- result.start=s
- end
- if step>1 and result.start then
- local v=V(tostring(step/2))
- result[tostring(step)]=v*v
- end
- if step>0 then
- return nextstep(m,step/2,result)
- else
- return result
- end
-end
-function lpeg.times(pattern,n)
- return P(nextstep(n,2^16,{ "start",["1"]=pattern }))
-end
-do
- local trailingzeros=zero^0*-digit
- local stripper=Cs((
- digits*(
- period*trailingzeros/""+period*(digit-trailingzeros)^1*(trailingzeros/"")
- )+1
- )^0)
- lpeg.patterns.stripzeros=stripper
- local nonzero=digit-zero
- local trailingzeros=zero^1*endofstring
- local stripper=Cs((1-period)^0*(
- period*trailingzeros/""+period*(nonzero^1+(trailingzeros/"")+zero^1)^0+endofstring
- ))
- lpeg.patterns.stripzero=stripper
-end
-local byte_to_HEX={}
-local byte_to_hex={}
-local byte_to_dec={}
-local hex_to_byte={}
-for i=0,255 do
- local H=format("%02X",i)
- local h=format("%02x",i)
- local d=format("%03i",i)
- local c=char(i)
- byte_to_HEX[c]=H
- byte_to_hex[c]=h
- byte_to_dec[c]=d
- hex_to_byte[h]=c
- hex_to_byte[H]=c
-end
-local hextobyte=P(2)/hex_to_byte
-local bytetoHEX=P(1)/byte_to_HEX
-local bytetohex=P(1)/byte_to_hex
-local bytetodec=P(1)/byte_to_dec
-local hextobytes=Cs(hextobyte^0)
-local bytestoHEX=Cs(bytetoHEX^0)
-local bytestohex=Cs(bytetohex^0)
-local bytestodec=Cs(bytetodec^0)
-patterns.hextobyte=hextobyte
-patterns.bytetoHEX=bytetoHEX
-patterns.bytetohex=bytetohex
-patterns.bytetodec=bytetodec
-patterns.hextobytes=hextobytes
-patterns.bytestoHEX=bytestoHEX
-patterns.bytestohex=bytestohex
-patterns.bytestodec=bytestodec
-function string.toHEX(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(bytestoHEX,s)
- end
-end
-function string.tohex(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(bytestohex,s)
- end
-end
-function string.todec(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(bytestodec,s)
- end
-end
-function string.tobytes(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(hextobytes,s)
- end
-end
-local patterns={}
-local function containsws(what)
- local p=patterns[what]
- if not p then
- local p1=P(what)*(whitespace+endofstring)*Cc(true)
- local p2=whitespace*P(p1)
- p=P(p1)+P(1-p2)^0*p2+Cc(false)
- patterns[what]=p
- end
- return p
-end
-lpeg.containsws=containsws
-function string.containsws(str,what)
- return lpegmatch(patterns[what] or containsws(what),str)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-function"] = package.loaded["l-function"] or true
-
--- original size: 361, stripped down to: 317
-
-if not modules then modules={} end modules ['l-functions']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-functions=functions or {}
-function functions.dummy() end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-string"] = package.loaded["l-string"] or true
-
--- original size: 6644, stripped down to: 3410
-
-if not modules then modules={} end modules ['l-string']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local string=string
-local sub,gmatch,format,char,byte,rep,lower=string.sub,string.gmatch,string.format,string.char,string.byte,string.rep,string.lower
-local lpegmatch,patterns=lpeg.match,lpeg.patterns
-local P,S,C,Ct,Cc,Cs=lpeg.P,lpeg.S,lpeg.C,lpeg.Ct,lpeg.Cc,lpeg.Cs
-local unquoted=patterns.squote*C(patterns.nosquote)*patterns.squote+patterns.dquote*C(patterns.nodquote)*patterns.dquote
-function string.unquoted(str)
- return lpegmatch(unquoted,str) or str
-end
-function string.quoted(str)
- return format("%q",str)
-end
-function string.count(str,pattern)
- local n=0
- for _ in gmatch(str,pattern) do
- n=n+1
- end
- return n
-end
-function string.limit(str,n,sentinel)
- if #str>n then
- sentinel=sentinel or "..."
- return sub(str,1,(n-#sentinel))..sentinel
- else
- return str
- end
-end
-local stripper=patterns.stripper
-local fullstripper=patterns.fullstripper
-local collapser=patterns.collapser
-local nospacer=patterns.nospacer
-local longtostring=patterns.longtostring
-function string.strip(str)
- return str and lpegmatch(stripper,str) or ""
-end
-function string.fullstrip(str)
- return str and lpegmatch(fullstripper,str) or ""
-end
-function string.collapsespaces(str)
- return str and lpegmatch(collapser,str) or ""
-end
-function string.nospaces(str)
- return str and lpegmatch(nospacer,str) or ""
-end
-function string.longtostring(str)
- return str and lpegmatch(longtostring,str) or ""
-end
-local pattern=P(" ")^0*P(-1)
-function string.is_empty(str)
- if not str or str=="" then
- return true
- else
- return lpegmatch(pattern,str) and true or false
- end
-end
-local anything=patterns.anything
-local moreescapes=Cc("%")*S(".-+%?()[]*$^{}")
-local allescapes=Cc("%")*S(".-+%?()[]*")
-local someescapes=Cc("%")*S(".-+%()[]")
-local matchescapes=Cc(".")*S("*?")
-local pattern_m=Cs ((moreescapes+anything )^0 )
-local pattern_a=Cs ((allescapes+anything )^0 )
-local pattern_b=Cs ((someescapes+matchescapes+anything )^0 )
-local pattern_c=Cs (Cc("^")*(someescapes+matchescapes+anything )^0*Cc("$") )
-function string.escapedpattern(str,simple)
- return lpegmatch(simple and pattern_b or pattern_a,str)
-end
-function string.topattern(str,lowercase,strict)
- if str=="" or type(str)~="string" then
- return ".*"
- elseif strict=="all" then
- str=lpegmatch(pattern_m,str)
- elseif strict then
- str=lpegmatch(pattern_c,str)
- else
- str=lpegmatch(pattern_b,str)
- end
- if lowercase then
- return lower(str)
- else
- return str
- end
-end
-function string.valid(str,default)
- return (type(str)=="string" and str~="" and str) or default or nil
-end
-string.itself=function(s) return s end
-local pattern_c=Ct(C(1)^0)
-local pattern_b=Ct((C(1)/byte)^0)
-function string.totable(str,bytes)
- return lpegmatch(bytes and pattern_b or pattern_c,str)
-end
-local replacer=lpeg.replacer("@","%%")
-function string.tformat(fmt,...)
- return format(lpegmatch(replacer,fmt),...)
-end
-string.quote=string.quoted
-string.unquote=string.unquoted
-if not string.bytetable then
- local limit=5000
- function string.bytetable(str)
- local n=#str
- if n>limit then
- local t={ byte(str,1,limit) }
- for i=limit+1,n do
- t[i]=byte(str,i)
- end
- return t
- else
- return { byte(str,1,n) }
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-table"] = package.loaded["l-table"] or true
-
--- original size: 41758, stripped down to: 22643
-
-if not modules then modules={} end modules ['l-table']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,next,tostring,tonumber,select,rawget=type,next,tostring,tonumber,select,rawget
-local table,string=table,string
-local concat,sort=table.concat,table.sort
-local format,lower,dump=string.format,string.lower,string.dump
-local getmetatable,setmetatable=getmetatable,setmetatable
-local lpegmatch,patterns=lpeg.match,lpeg.patterns
-local floor=math.floor
-local stripper=patterns.stripper
-function table.getn(t)
- return t and #t
-end
-function table.strip(tab)
- local lst={}
- local l=0
- for i=1,#tab do
- local s=lpegmatch(stripper,tab[i]) or ""
- if s=="" then
- else
- l=l+1
- lst[l]=s
- end
- end
- return lst
-end
-function table.keys(t)
- if t then
- local keys={}
- local k=0
- for key in next,t do
- k=k+1
- keys[k]=key
- end
- return keys
- else
- return {}
- end
-end
-local function compare(a,b)
- local ta=type(a)
- if ta=="number" then
- local tb=type(b)
- if ta==tb then
- return a<b
- elseif tb=="string" then
- return tostring(a)<b
- end
- elseif ta=="string" then
- local tb=type(b)
- if ta==tb then
- return a<b
- else
- return a<tostring(b)
- end
- end
- return tostring(a)<tostring(b)
-end
-local function sortedkeys(tab)
- if tab then
- local srt={}
- local category=0
- local s=0
- for key in next,tab do
- s=s+1
- srt[s]=key
- if category~=3 then
- local tkey=type(key)
- if category==1 then
- if tkey~="string" then
- category=3
- end
- elseif category==2 then
- if tkey~="number" then
- category=3
- end
- else
- if tkey=="string" then
- category=1
- elseif tkey=="number" then
- category=2
- else
- category=3
- end
- end
- end
- end
- if s<2 then
- elseif category==3 then
- sort(srt,compare)
- else
- sort(srt)
- end
- return srt
- else
- return {}
- end
-end
-local function sortedhashonly(tab)
- if tab then
- local srt={}
- local s=0
- for key in next,tab do
- if type(key)=="string" then
- s=s+1
- srt[s]=key
- end
- end
- if s>1 then
- sort(srt)
- end
- return srt
- else
- return {}
- end
-end
-local function sortedindexonly(tab)
- if tab then
- local srt={}
- local s=0
- for key in next,tab do
- if type(key)=="number" then
- s=s+1
- srt[s]=key
- end
- end
- if s>1 then
- sort(srt)
- end
- return srt
- else
- return {}
- end
-end
-local function sortedhashkeys(tab,cmp)
- if tab then
- local srt={}
- local s=0
- for key in next,tab do
- if key then
- s=s+1
- srt[s]=key
- end
- end
- if s>1 then
- sort(srt,cmp)
- end
- return srt
- else
- return {}
- end
-end
-function table.allkeys(t)
- local keys={}
- for k,v in next,t do
- for k in next,v do
- keys[k]=true
- end
- end
- return sortedkeys(keys)
-end
-table.sortedkeys=sortedkeys
-table.sortedhashonly=sortedhashonly
-table.sortedindexonly=sortedindexonly
-table.sortedhashkeys=sortedhashkeys
-local function nothing() end
-local function sortedhash(t,cmp)
- if t then
- local s
- if cmp then
- s=sortedhashkeys(t,function(a,b) return cmp(t,a,b) end)
- else
- s=sortedkeys(t)
- end
- local m=#s
- if m==1 then
- return next,t
- elseif m>0 then
- local n=0
- return function()
- if n<m then
- n=n+1
- local k=s[n]
- return k,t[k]
- end
- end
- end
- end
- return nothing
-end
-table.sortedhash=sortedhash
-table.sortedpairs=sortedhash
-function table.append(t,list)
- local n=#t
- for i=1,#list do
- n=n+1
- t[n]=list[i]
- end
- return t
-end
-function table.prepend(t,list)
- local nl=#list
- local nt=nl+#t
- for i=#t,1,-1 do
- t[nt]=t[i]
- nt=nt-1
- end
- for i=1,#list do
- t[i]=list[i]
- end
- return t
-end
-function table.merge(t,...)
- if not t then
- t={}
- end
- for i=1,select("#",...) do
- for k,v in next,(select(i,...)) do
- t[k]=v
- end
- end
- return t
-end
-function table.merged(...)
- local t={}
- for i=1,select("#",...) do
- for k,v in next,(select(i,...)) do
- t[k]=v
- end
- end
- return t
-end
-function table.imerge(t,...)
- local nt=#t
- for i=1,select("#",...) do
- local nst=select(i,...)
- for j=1,#nst do
- nt=nt+1
- t[nt]=nst[j]
- end
- end
- return t
-end
-function table.imerged(...)
- local tmp={}
- local ntmp=0
- for i=1,select("#",...) do
- local nst=select(i,...)
- for j=1,#nst do
- ntmp=ntmp+1
- tmp[ntmp]=nst[j]
- end
- end
- return tmp
-end
-local function fastcopy(old,metatabletoo)
- if old then
- local new={}
- for k,v in next,old do
- if type(v)=="table" then
- new[k]=fastcopy(v,metatabletoo)
- else
- new[k]=v
- end
- end
- if metatabletoo then
- local mt=getmetatable(old)
- if mt then
- setmetatable(new,mt)
- end
- end
- return new
- else
- return {}
- end
-end
-local function copy(t,tables)
- if not tables then
- tables={}
- end
- local tcopy={}
- if not tables[t] then
- tables[t]=tcopy
- end
- for i,v in next,t do
- if type(i)=="table" then
- if tables[i] then
- i=tables[i]
- else
- i=copy(i,tables)
- end
- end
- if type(v)~="table" then
- tcopy[i]=v
- elseif tables[v] then
- tcopy[i]=tables[v]
- else
- tcopy[i]=copy(v,tables)
- end
- end
- local mt=getmetatable(t)
- if mt then
- setmetatable(tcopy,mt)
- end
- return tcopy
-end
-table.fastcopy=fastcopy
-table.copy=copy
-function table.derive(parent)
- local child={}
- if parent then
- setmetatable(child,{ __index=parent })
- end
- return child
-end
-function table.tohash(t,value)
- local h={}
- if t then
- if value==nil then value=true end
- for _,v in next,t do
- h[v]=value
- end
- end
- return h
-end
-function table.fromhash(t)
- local hsh={}
- local h=0
- for k,v in next,t do
- if v then
- h=h+1
- hsh[h]=k
- end
- end
- return hsh
-end
-local noquotes,hexify,handle,compact,inline,functions,metacheck,accurate
-local reserved=table.tohash {
- 'and','break','do','else','elseif','end','false','for','function','if',
- 'in','local','nil','not','or','repeat','return','then','true','until','while',
- 'NaN','goto','const',
-}
-local function is_simple_table(t,hexify,accurate)
- local nt=#t
- if nt>0 then
- local n=0
- for _,v in next,t do
- n=n+1
- if type(v)=="table" then
- return nil
- end
- end
- local haszero=rawget(t,0)
- if n==nt then
- local tt={}
- for i=1,nt do
- local v=t[i]
- local tv=type(v)
- if tv=="number" then
- if hexify then
- tt[i]=format("0x%X",v)
- elseif accurate then
- tt[i]=format("%q",v)
- else
- tt[i]=v
- end
- elseif tv=="string" then
- tt[i]=format("%q",v)
- elseif tv=="boolean" then
- tt[i]=v and "true" or "false"
- else
- return nil
- end
- end
- return tt
- elseif haszero and (n==nt+1) then
- local tt={}
- for i=0,nt do
- local v=t[i]
- local tv=type(v)
- if tv=="number" then
- if hexify then
- tt[i+1]=format("0x%X",v)
- elseif accurate then
- tt[i+1]=format("%q",v)
- else
- tt[i+1]=v
- end
- elseif tv=="string" then
- tt[i+1]=format("%q",v)
- elseif tv=="boolean" then
- tt[i+1]=v and "true" or "false"
- else
- return nil
- end
- end
- tt[1]="[0] = "..tt[1]
- return tt
- end
- end
- return nil
-end
-table.is_simple_table=is_simple_table
-local propername=patterns.propername
-local function dummy() end
-local function do_serialize(root,name,depth,level,indexed)
- if level>0 then
- depth=depth.." "
- if indexed then
- handle(format("%s{",depth))
- else
- local tn=type(name)
- if tn=="number" then
- if hexify then
- handle(format("%s[0x%X]={",depth,name))
- else
- handle(format("%s[%s]={",depth,name))
- end
- elseif tn=="string" then
- if noquotes and not reserved[name] and lpegmatch(propername,name) then
- handle(format("%s%s={",depth,name))
- else
- handle(format("%s[%q]={",depth,name))
- end
- elseif tn=="boolean" then
- handle(format("%s[%s]={",depth,name and "true" or "false"))
- else
- handle(format("%s{",depth))
- end
- end
- end
- if root and next(root)~=nil then
- local first=nil
- local last=0
- if compact then
- last=#root
- for k=1,last do
- if rawget(root,k)==nil then
- last=k-1
- break
- end
- end
- if last>0 then
- first=1
- end
- end
- local sk=sortedkeys(root)
- for i=1,#sk do
- local k=sk[i]
- local v=root[k]
- local tv=type(v)
- local tk=type(k)
- if compact and first and tk=="number" and k>=first and k<=last then
- if tv=="number" then
- if hexify then
- handle(format("%s 0x%X,",depth,v))
- elseif accurate then
- handle(format("%s %q,",depth,v))
- else
- handle(format("%s %s,",depth,v))
- end
- elseif tv=="string" then
- handle(format("%s %q,",depth,v))
- elseif tv=="table" then
- if next(v)==nil then
- handle(format("%s {},",depth))
- elseif inline then
- local st=is_simple_table(v,hexify,accurate)
- if st then
- handle(format("%s { %s },",depth,concat(st,", ")))
- else
- do_serialize(v,k,depth,level+1,true)
- end
- else
- do_serialize(v,k,depth,level+1,true)
- end
- elseif tv=="boolean" then
- handle(format("%s %s,",depth,v and "true" or "false"))
- elseif tv=="function" then
- if functions then
- handle(format('%s load(%q),',depth,dump(v)))
- else
- handle(format('%s "function",',depth))
- end
- else
- handle(format("%s %q,",depth,tostring(v)))
- end
- elseif k=="__p__" then
- if false then
- handle(format("%s __p__=nil,",depth))
- end
- elseif tv=="number" then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=0x%X,",depth,k,v))
- elseif accurate then
- handle(format("%s [%s]=%q,",depth,k,v))
- else
- handle(format("%s [%s]=%s,",depth,k,v))
- end
- elseif tk=="boolean" then
- if hexify then
- handle(format("%s [%s]=0x%X,",depth,k and "true" or "false",v))
- elseif accurate then
- handle(format("%s [%s]=%q,",depth,k and "true" or "false",v))
- else
- handle(format("%s [%s]=%s,",depth,k and "true" or "false",v))
- end
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- if hexify then
- handle(format("%s %s=0x%X,",depth,k,v))
- elseif accurate then
- handle(format("%s %s=%q,",depth,k,v))
- else
- handle(format("%s %s=%s,",depth,k,v))
- end
- else
- if hexify then
- handle(format("%s [%q]=0x%X,",depth,k,v))
- elseif accurate then
- handle(format("%s [%q]=%q,",depth,k,v))
- else
- handle(format("%s [%q]=%s,",depth,k,v))
- end
- end
- elseif tv=="string" then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=%q,",depth,k,v))
- elseif accurate then
- handle(format("%s [%q]=%q,",depth,k,v))
- else
- handle(format("%s [%s]=%q,",depth,k,v))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=%q,",depth,k and "true" or "false",v))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=%q,",depth,k,v))
- else
- handle(format("%s [%q]=%q,",depth,k,v))
- end
- elseif tv=="table" then
- if next(v)==nil then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]={},",depth,k))
- elseif accurate then
- handle(format("%s [%q]={},",depth,k))
- else
- handle(format("%s [%s]={},",depth,k))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]={},",depth,k and "true" or "false"))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s={},",depth,k))
- else
- handle(format("%s [%q]={},",depth,k))
- end
- elseif inline then
- local st=is_simple_table(v,hexify,accurate)
- if st then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]={ %s },",depth,k,concat(st,", ")))
- elseif accurate then
- handle(format("%s [%q]={ %s },",depth,k,concat(st,", ")))
- else
- handle(format("%s [%s]={ %s },",depth,k,concat(st,", ")))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]={ %s },",depth,k and "true" or "false",concat(st,", ")))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s={ %s },",depth,k,concat(st,", ")))
- else
- handle(format("%s [%q]={ %s },",depth,k,concat(st,", ")))
- end
- else
- do_serialize(v,k,depth,level+1)
- end
- else
- do_serialize(v,k,depth,level+1)
- end
- elseif tv=="boolean" then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=%s,",depth,k,v and "true" or "false"))
- elseif accurate then
- handle(format("%s [%q]=%s,",depth,k,v and "true" or "false"))
- else
- handle(format("%s [%s]=%s,",depth,k,v and "true" or "false"))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=%s,",depth,tostring(k),v and "true" or "false"))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=%s,",depth,k,v and "true" or "false"))
- else
- handle(format("%s [%q]=%s,",depth,k,v and "true" or "false"))
- end
- elseif tv=="function" then
- if functions then
- local getinfo=debug and debug.getinfo
- if getinfo then
- local f=getinfo(v).what=="C" and dump(dummy) or dump(v)
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=load(%q),",depth,k,f))
- elseif accurate then
- handle(format("%s [%q]=load(%q),",depth,k,f))
- else
- handle(format("%s [%s]=load(%q),",depth,k,f))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=load(%q),",depth,k and "true" or "false",f))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=load(%q),",depth,k,f))
- else
- handle(format("%s [%q]=load(%q),",depth,k,f))
- end
- end
- end
- else
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=%q,",depth,k,tostring(v)))
- elseif accurate then
- handle(format("%s [%q]=%q,",depth,k,tostring(v)))
- else
- handle(format("%s [%s]=%q,",depth,k,tostring(v)))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=%q,",depth,k and "true" or "false",tostring(v)))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=%q,",depth,k,tostring(v)))
- else
- handle(format("%s [%q]=%q,",depth,k,tostring(v)))
- end
- end
- end
- end
- if level>0 then
- handle(format("%s},",depth))
- end
-end
-local function serialize(_handle,root,name,specification)
- local tname=type(name)
- if type(specification)=="table" then
- noquotes=specification.noquotes
- hexify=specification.hexify
- accurate=specification.accurate
- handle=_handle or specification.handle or print
- functions=specification.functions
- compact=specification.compact
- inline=specification.inline and compact
- metacheck=specification.metacheck
- if functions==nil then
- functions=true
- end
- if compact==nil then
- compact=true
- end
- if inline==nil then
- inline=compact
- end
- if metacheck==nil then
- metacheck=true
- end
- else
- noquotes=false
- hexify=false
- handle=_handle or print
- compact=true
- inline=true
- functions=true
- metacheck=true
- end
- if tname=="string" then
- if name=="return" then
- handle("return {")
- else
- handle(name.."={")
- end
- elseif tname=="number" then
- if hexify then
- handle(format("[0x%X]={",name))
- else
- handle("["..name.."]={")
- end
- elseif tname=="boolean" then
- if name then
- handle("return {")
- else
- handle("{")
- end
- else
- handle("t={")
- end
- if root then
- if metacheck and getmetatable(root) then
- local dummy=root._w_h_a_t_e_v_e_r_
- root._w_h_a_t_e_v_e_r_=nil
- end
- if next(root)~=nil then
- do_serialize(root,name,"",0)
- end
- end
- handle("}")
-end
-function table.serialize(root,name,specification)
- local t={}
- local n=0
- local function flush(s)
- n=n+1
- t[n]=s
- end
- serialize(flush,root,name,specification)
- return concat(t,"\n")
-end
-table.tohandle=serialize
-local maxtab=2*1024
-function table.tofile(filename,root,name,specification)
- local f=io.open(filename,'w')
- if f then
- if maxtab>1 then
- local t={}
- local n=0
- local function flush(s)
- n=n+1
- t[n]=s
- if n>maxtab then
- f:write(concat(t,"\n"),"\n")
- t={}
- n=0
- end
- end
- serialize(flush,root,name,specification)
- f:write(concat(t,"\n"),"\n")
- else
- local function flush(s)
- f:write(s,"\n")
- end
- serialize(flush,root,name,specification)
- end
- f:close()
- io.flush()
- end
-end
-local function flattened(t,f,depth)
- if f==nil then
- f={}
- depth=0xFFFF
- elseif tonumber(f) then
- depth=f
- f={}
- elseif not depth then
- depth=0xFFFF
- end
- for k,v in next,t do
- if type(k)~="number" then
- if depth>0 and type(v)=="table" then
- flattened(v,f,depth-1)
- else
- f[#f+1]=v
- end
- end
- end
- for k=1,#t do
- local v=t[k]
- if depth>0 and type(v)=="table" then
- flattened(v,f,depth-1)
- else
- f[#f+1]=v
- end
- end
- return f
-end
-table.flattened=flattened
-local function collapsed(t,f,h)
- if f==nil then
- f={}
- h={}
- end
- for k=1,#t do
- local v=t[k]
- if type(v)=="table" then
- collapsed(v,f,h)
- elseif not h[v] then
- f[#f+1]=v
- h[v]=true
- end
- end
- return f
-end
-local function collapsedhash(t,h)
- if h==nil then
- h={}
- end
- for k=1,#t do
- local v=t[k]
- if type(v)=="table" then
- collapsedhash(v,h)
- else
- h[v]=true
- end
- end
- return h
-end
-table.collapsed=collapsed
-table.collapsedhash=collapsedhash
-local function unnest(t,f)
- if not f then
- f={}
- end
- for i=1,#t do
- local v=t[i]
- if type(v)=="table" then
- if type(v[1])=="table" then
- unnest(v,f)
- else
- f[#f+1]=v
- end
- else
- f[#f+1]=v
- end
- end
- return f
-end
-function table.unnest(t)
- return unnest(t)
-end
-local function are_equal(a,b,n,m)
- if a==b then
- return true
- elseif a and b and #a==#b then
- if not n then
- n=1
- end
- if not m then
- m=#a
- end
- for i=n,m do
- local ai,bi=a[i],b[i]
- if ai==bi then
- elseif type(ai)=="table" and type(bi)=="table" then
- if not are_equal(ai,bi) then
- return false
- end
- else
- return false
- end
- end
- return true
- else
- return false
- end
-end
-local function identical(a,b)
- if a~=b then
- for ka,va in next,a do
- local vb=b[ka]
- if va==vb then
- elseif type(va)=="table" and type(vb)=="table" then
- if not identical(va,vb) then
- return false
- end
- else
- return false
- end
- end
- end
- return true
-end
-table.identical=identical
-table.are_equal=are_equal
-local function sparse(old,nest,keeptables)
- local new={}
- for k,v in next,old do
- if not (v=="" or v==false) then
- if nest and type(v)=="table" then
- v=sparse(v,nest)
- if keeptables or next(v)~=nil then
- new[k]=v
- end
- else
- new[k]=v
- end
- end
- end
- return new
-end
-table.sparse=sparse
-function table.compact(t)
- return sparse(t,true,true)
-end
-function table.contains(t,v)
- if t then
- for i=1,#t do
- if t[i]==v then
- return i
- end
- end
- end
- return false
-end
-function table.count(t)
- local n=0
- for k,v in next,t do
- n=n+1
- end
- return n
-end
-function table.swapped(t,s)
- local n={}
- if s then
- for k,v in next,s do
- n[k]=v
- end
- end
- for k,v in next,t do
- n[v]=k
- end
- return n
-end
-function table.hashed(t)
- for i=1,#t do
- t[t[i]]=i
- end
- return t
-end
-function table.mirrored(t)
- local n={}
- for k,v in next,t do
- n[v]=k
- n[k]=v
- end
- return n
-end
-function table.reversed(t)
- if t then
- local tt={}
- local tn=#t
- if tn>0 then
- local ttn=0
- for i=tn,1,-1 do
- ttn=ttn+1
- tt[ttn]=t[i]
- end
- end
- return tt
- end
-end
-function table.reverse(t)
- if t then
- local n=#t
- local m=n+1
- for i=1,floor(n/2) do
- local j=m-i
- t[i],t[j]=t[j],t[i]
- end
- return t
- end
-end
-local function sequenced(t,sep,simple)
- if not t then
- return ""
- elseif type(t)~="table" then
- return t
- end
- local n=#t
- local s={}
- if n>0 then
- for i=1,n do
- local v=t[i]
- if type(v)=="table" then
- s[i]="{"..sequenced(v,sep,simple).."}"
- else
- s[i]=tostring(t[i])
- end
- end
- else
- n=0
- for k,v in sortedhash(t) do
- if simple then
- if v==true then
- n=n+1
- s[n]=k
- elseif v and v~="" then
- n=n+1
- if type(v)=="table" then
- s[n]=k.."={"..sequenced(v,sep,simple).."}"
- else
- s[n]=k.."="..tostring(v)
- end
- end
- else
- n=n+1
- if type(v)=="table" then
- s[n]=k.."={"..sequenced(v,sep,simple).."}"
- else
- s[n]=k.."="..tostring(v)
- end
- end
- end
- end
- if sep==true then
- return "{ "..concat(s,", ").." }"
- else
- return concat(s,sep or " | ")
- end
-end
-table.sequenced=sequenced
-function table.print(t,...)
- if type(t)~="table" then
- print(tostring(t))
- else
- serialize(print,t,...)
- end
-end
-if setinspector then
- setinspector("table",function(v) if type(v)=="table" then serialize(print,v,"table") return true end end)
-end
-function table.sub(t,i,j)
- return { unpack(t,i,j) }
-end
-function table.is_empty(t)
- return not t or next(t)==nil
-end
-function table.has_one_entry(t)
- return t and next(t,next(t))==nil
-end
-function table.loweredkeys(t)
- local l={}
- for k,v in next,t do
- l[lower(k)]=v
- end
- return l
-end
-function table.unique(old)
- local hash={}
- local new={}
- local n=0
- for i=1,#old do
- local oi=old[i]
- if not hash[oi] then
- n=n+1
- new[n]=oi
- hash[oi]=true
- end
- end
- return new
-end
-function table.sorted(t,...)
- sort(t,...)
- return t
-end
-function table.values(t,s)
- if t then
- local values={}
- local keys={}
- local v=0
- for key,value in next,t do
- if not keys[value] then
- v=v+1
- values[v]=value
- keys[k]=key
- end
- end
- if s then
- sort(values)
- end
- return values
- else
- return {}
- end
-end
-function table.filtered(t,pattern,sort,cmp)
- if t and type(pattern)=="string" then
- if sort then
- local s
- if cmp then
- s=sortedhashkeys(t,function(a,b) return cmp(t,a,b) end)
- else
- s=sortedkeys(t)
- end
- local n=0
- local m=#s
- local function kv(s)
- while n<m do
- n=n+1
- local k=s[n]
- if find(k,pattern) then
- return k,t[k]
- end
- end
- end
- return kv,s
- else
- local n=next(t)
- local function iterator()
- while n~=nil do
- local k=n
- n=next(t,k)
- if find(k,pattern) then
- return k,t[k]
- end
- end
- end
- return iterator,t
- end
- else
- return nothing
- end
-end
-if not table.move then
- function table.move(a1,f,e,t,a2)
- if a2 and a1~=a2 then
- for i=f,e do
- a2[t]=a1[i]
- t=t+1
- end
- return a2
- else
- t=t+e-f
- for i=e,f,-1 do
- a1[t]=a1[i]
- t=t-1
- end
- return a1
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-io"] = package.loaded["l-io"] or true
-
--- original size: 11829, stripped down to: 6331
-
-if not modules then modules={} end modules ['l-io']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local io=io
-local open,flush,write,read=io.open,io.flush,io.write,io.read
-local byte,find,gsub,format=string.byte,string.find,string.gsub,string.format
-local concat=table.concat
-local type=type
-if string.find(os.getenv("PATH") or "",";",1,true) then
- io.fileseparator,io.pathseparator="\\",";"
-else
- io.fileseparator,io.pathseparator="/",":"
-end
-local large=0x01000000
-local medium=0x00100000
-local small=0x00020000
-local function readall(f)
- local size=f:seek("end")
- if size>0 then
- f:seek("set",0)
- return f:read(size)
- else
- return ""
- end
-end
-io.readall=readall
-function io.loaddata(filename,textmode)
- local f=open(filename,(textmode and 'r') or 'rb')
- if f then
- local size=f:seek("end")
- local data=nil
- if size>0 then
- f:seek("set",0)
- data=f:read(size)
- end
- f:close()
- return data
- end
-end
-function io.copydata(source,target,action)
- local f=open(source,"rb")
- if f then
- local g=open(target,"wb")
- if g then
- local size=f:seek("end")
- if size>0 then
- f:seek("set",0)
- local data=f:read(size)
- if action then
- data=action(data)
- end
- if data then
- g:write(data)
- end
- end
- g:close()
- end
- f:close()
- flush()
- end
-end
-function io.savedata(filename,data,joiner)
- local f=open(filename,"wb")
- if f then
- if type(data)=="table" then
- f:write(concat(data,joiner or ""))
- elseif type(data)=="function" then
- data(f)
- else
- f:write(data or "")
- end
- f:close()
- flush()
- return true
- else
- return false
- end
-end
-if fio and fio.readline then
- local readline=fio.readline
- function io.loadlines(filename,n)
- local f=open(filename,'r')
- if not f then
- elseif n then
- local lines={}
- for i=1,n do
- local line=readline(f)
- if line then
- lines[i]=line
- else
- break
- end
- end
- f:close()
- lines=concat(lines,"\n")
- if #lines>0 then
- return lines
- end
- else
- local line=readline(f)
- f:close()
- if line and #line>0 then
- return line
- end
- end
- end
-else
- function io.loadlines(filename,n)
- local f=open(filename,'r')
- if not f then
- elseif n then
- local lines={}
- for i=1,n do
- local line=f:read("*lines")
- if line then
- lines[i]=line
- else
- break
- end
- end
- f:close()
- lines=concat(lines,"\n")
- if #lines>0 then
- return lines
- end
- else
- local line=f:read("*line") or ""
- f:close()
- if #line>0 then
- return line
- end
- end
- end
-end
-function io.loadchunk(filename,n)
- local f=open(filename,'rb')
- if f then
- local data=f:read(n or 1024)
- f:close()
- if #data>0 then
- return data
- end
- end
-end
-function io.exists(filename)
- local f=open(filename)
- if f==nil then
- return false
- else
- f:close()
- return true
- end
-end
-function io.size(filename)
- local f=open(filename)
- if f==nil then
- return 0
- else
- local s=f:seek("end")
- f:close()
- return s
- end
-end
-local function noflines(f)
- if type(f)=="string" then
- local f=open(filename)
- if f then
- local n=f and noflines(f) or 0
- f:close()
- return n
- else
- return 0
- end
- else
- local n=0
- for _ in f:lines() do
- n=n+1
- end
- f:seek('set',0)
- return n
- end
-end
-io.noflines=noflines
-local nextchar={
- [ 4]=function(f)
- return f:read(1,1,1,1)
- end,
- [ 2]=function(f)
- return f:read(1,1)
- end,
- [ 1]=function(f)
- return f:read(1)
- end,
- [-2]=function(f)
- local a,b=f:read(1,1)
- return b,a
- end,
- [-4]=function(f)
- local a,b,c,d=f:read(1,1,1,1)
- return d,c,b,a
- end
-}
-function io.characters(f,n)
- if f then
- return nextchar[n or 1],f
- end
-end
-local nextbyte={
- [4]=function(f)
- local a,b,c,d=f:read(1,1,1,1)
- if d then
- return byte(a),byte(b),byte(c),byte(d)
- end
- end,
- [3]=function(f)
- local a,b,c=f:read(1,1,1)
- if b then
- return byte(a),byte(b),byte(c)
- end
- end,
- [2]=function(f)
- local a,b=f:read(1,1)
- if b then
- return byte(a),byte(b)
- end
- end,
- [1]=function (f)
- local a=f:read(1)
- if a then
- return byte(a)
- end
- end,
- [-2]=function (f)
- local a,b=f:read(1,1)
- if b then
- return byte(b),byte(a)
- end
- end,
- [-3]=function(f)
- local a,b,c=f:read(1,1,1)
- if b then
- return byte(c),byte(b),byte(a)
- end
- end,
- [-4]=function(f)
- local a,b,c,d=f:read(1,1,1,1)
- if d then
- return byte(d),byte(c),byte(b),byte(a)
- end
- end
-}
-function io.bytes(f,n)
- if f then
- return nextbyte[n or 1],f
- else
- return nil,nil
- end
-end
-function io.ask(question,default,options)
- while true do
- write(question)
- if options then
- write(format(" [%s]",concat(options,"|")))
- end
- if default then
- write(format(" [%s]",default))
- end
- write(format(" "))
- flush()
- local answer=read()
- answer=gsub(answer,"^%s*(.*)%s*$","%1")
- if answer=="" and default then
- return default
- elseif not options then
- return answer
- else
- for k=1,#options do
- if options[k]==answer then
- return answer
- end
- end
- local pattern="^"..answer
- for k=1,#options do
- local v=options[k]
- if find(v,pattern) then
- return v
- end
- end
- end
- end
-end
-local function readnumber(f,n,m)
- if m then
- f:seek("set",n)
- n=m
- end
- if n==1 then
- return byte(f:read(1))
- elseif n==2 then
- local a,b=byte(f:read(2),1,2)
- return 0x100*a+b
- elseif n==3 then
- local a,b,c=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
- elseif n==4 then
- local a,b,c,d=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
- elseif n==8 then
- local a,b=readnumber(f,4),readnumber(f,4)
- return 0x100*a+b
- elseif n==12 then
- local a,b,c=readnumber(f,4),readnumber(f,4),readnumber(f,4)
- return 0x10000*a+0x100*b+c
- elseif n==-2 then
- local b,a=byte(f:read(2),1,2)
- return 0x100*a+b
- elseif n==-3 then
- local c,b,a=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
- elseif n==-4 then
- local d,c,b,a=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
- elseif n==-8 then
- local h,g,f,e,d,c,b,a=byte(f:read(8),1,8)
- return 0x100000000000000*a+0x1000000000000*b+0x10000000000*c+0x100000000*d+0x1000000*e+0x10000*f+0x100*g+h
- else
- return 0
- end
-end
-io.readnumber=readnumber
-function io.readstring(f,n,m)
- if m then
- f:seek("set",n)
- n=m
- end
- local str=gsub(f:read(n),"\000","")
- return str
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-number"] = package.loaded["l-number"] or true
-
--- original size: 5720, stripped down to: 2176
-
-if not modules then modules={} end modules ['l-number']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local tostring,tonumber=tostring,tonumber
-local format,floor,match,rep=string.format,math.floor,string.match,string.rep
-local concat,insert=table.concat,table.insert
-local lpegmatch=lpeg.match
-local floor=math.floor
-number=number or {}
-local number=number
-if bit32 then
- local bextract=bit32.extract
- local t={
- "0","0","0","0","0","0","0","0",
- "0","0","0","0","0","0","0","0",
- "0","0","0","0","0","0","0","0",
- "0","0","0","0","0","0","0","0",
- }
- function number.tobitstring(b,m,w)
- if not w then
- w=32
- end
- local n=w
- for i=0,w-1 do
- local v=bextract(b,i)
- local k=w-i
- if v==1 then
- n=k
- t[k]="1"
- else
- t[k]="0"
- end
- end
- if w then
- return concat(t,"",1,w)
- elseif m then
- m=33-m*8
- if m<1 then
- m=1
- end
- return concat(t,"",1,m)
- elseif n<8 then
- return concat(t)
- elseif n<16 then
- return concat(t,"",9)
- elseif n<24 then
- return concat(t,"",17)
- else
- return concat(t,"",25)
- end
- end
-else
- function number.tobitstring(n,m)
- if n>0 then
- local t={}
- while n>0 do
- insert(t,1,n%2>0 and 1 or 0)
- n=floor(n/2)
- end
- local nn=8-#t%8
- if nn>0 and nn<8 then
- for i=1,nn do
- insert(t,1,0)
- end
- end
- if m then
- m=m*8-#t
- if m>0 then
- insert(t,1,rep("0",m))
- end
- end
- return concat(t)
- elseif m then
- rep("00000000",m)
- else
- return "00000000"
- end
- end
-end
-function number.valid(str,default)
- return tonumber(str) or default or nil
-end
-function number.toevenhex(n)
- local s=format("%X",n)
- if #s%2==0 then
- return s
- else
- return "0"..s
- end
-end
-function number.bytetodecimal(b)
- local d=floor(b*100/255+0.5)
- if d>100 then
- return 100
- elseif d<-100 then
- return -100
- else
- return d
- end
-end
-function number.decimaltobyte(d)
- local b=floor(d*255/100+0.5)
- if b>255 then
- return 255
- elseif b<-255 then
- return -255
- else
- return b
- end
-end
-function number.idiv(i,d)
- return floor(i/d)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-set"] = package.loaded["l-set"] or true
-
--- original size: 1923, stripped down to: 1044
-
-if not modules then modules={} end modules ['l-set']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-set=set or {}
-local nums={}
-local tabs={}
-local concat=table.concat
-local next,type=next,type
-set.create=table.tohash
-function set.tonumber(t)
- if next(t) then
- local s=""
- for k,v in next,t do
- if v then
- s=s.." "..k
- end
- end
- local n=nums[s]
- if not n then
- n=#tabs+1
- tabs[n]=t
- nums[s]=n
- end
- return n
- else
- return 0
- end
-end
-function set.totable(n)
- if n==0 then
- return {}
- else
- return tabs[n] or {}
- end
-end
-function set.tolist(n)
- if n==0 or not tabs[n] then
- return ""
- else
- local t,n={},0
- for k,v in next,tabs[n] do
- if v then
- n=n+1
- t[n]=k
- end
- end
- return concat(t," ")
- end
-end
-function set.contains(n,s)
- if type(n)=="table" then
- return n[s]
- elseif n==0 then
- return false
- else
- local t=tabs[n]
- return t and t[s]
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-os"] = package.loaded["l-os"] or true
-
--- original size: 19409, stripped down to: 10419
-
-if not modules then modules={} end modules ['l-os']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local os=os
-local date,time=os.date,os.time
-local find,format,gsub,upper,gmatch=string.find,string.format,string.gsub,string.upper,string.gmatch
-local concat=table.concat
-local random,ceil,randomseed=math.random,math.ceil,math.randomseed
-local type,setmetatable,tonumber,tostring=type,setmetatable,tonumber,tostring
-do
- local selfdir=os.selfdir
- if selfdir=="" then
- selfdir=nil
- end
- if not selfdir then
- if arg then
- for i=1,#arg do
- local a=arg[i]
- if find(a,"^%-%-[c:]*texmfbinpath=") then
- selfdir=gsub(a,"^.-=","")
- break
- end
- end
- end
- if not selfdir then
- selfdir=os.selfbin or "luatex"
- if find(selfdir,"[/\\]") then
- selfdir=gsub(selfdir,"[/\\][^/\\]*$","")
- elseif os.getenv then
- local path=os.getenv("PATH")
- local name=gsub(selfdir,"^.*[/\\][^/\\]","")
- local patt="[^:]+"
- if os.type=="windows" then
- patt="[^;]+"
- name=name..".exe"
- end
- local isfile
- if lfs then
- local attributes=lfs.attributes
- isfile=function(name)
- local a=attributes(name,"mode")
- return a=="file" or a=="link" or nil
- end
- else
- local open=io.open
- isfile=function(name)
- local f=open(name)
- if f then
- f:close()
- return true
- end
- end
- end
- for p in gmatch(path,patt) do
- if isfile(p.."/"..name) then
- selfdir=p
- break
- end
- end
- end
- end
- os.selfdir=selfdir or "."
- end
-end
-math.initialseed=tonumber(string.sub(string.reverse(tostring(ceil(socket and socket.gettime()*10000 or time()))),1,6))
-randomseed(math.initialseed)
-if not os.__getenv__ then
- os.__getenv__=os.getenv
- os.__setenv__=os.setenv
- if os.env then
- local osgetenv=os.getenv
- local ossetenv=os.setenv
- local osenv=os.env local _=osenv.PATH
- function os.setenv(k,v)
- if v==nil then
- v=""
- end
- local K=upper(k)
- osenv[K]=v
- if type(v)=="table" then
- v=concat(v,";")
- end
- ossetenv(K,v)
- end
- function os.getenv(k)
- local K=upper(k)
- local v=osenv[K] or osenv[k] or osgetenv(K) or osgetenv(k)
- if v=="" then
- return nil
- else
- return v
- end
- end
- else
- local ossetenv=os.setenv
- local osgetenv=os.getenv
- local osenv={}
- function os.setenv(k,v)
- if v==nil then
- v=""
- end
- local K=upper(k)
- osenv[K]=v
- end
- function os.getenv(k)
- local K=upper(k)
- local v=osenv[K] or osgetenv(K) or osgetenv(k)
- if v=="" then
- return nil
- else
- return v
- end
- end
- local function __index(t,k)
- return os.getenv(k)
- end
- local function __newindex(t,k,v)
- os.setenv(k,v)
- end
- os.env={}
- setmetatable(os.env,{ __index=__index,__newindex=__newindex } )
- end
-end
-local execute=os.execute
-local iopopen=io.popen
-local function resultof(command)
- local handle=iopopen(command,"r")
- if handle then
- local result=handle:read("*all") or ""
- handle:close()
- return result
- else
- return ""
- end
-end
-os.resultof=resultof
-function os.pipeto(command)
- return iopopen(command,"w")
-end
-if not io.fileseparator then
- if find(os.getenv("PATH"),";",1,true) then
- io.fileseparator,io.pathseparator,os.type="\\",";",os.type or "windows"
- else
- io.fileseparator,io.pathseparator,os.type="/",":",os.type or "unix"
- end
-end
-os.type=os.type or (io.pathseparator==";" and "windows") or "unix"
-os.name=os.name or (os.type=="windows" and "mswin" ) or "linux"
-if os.type=="windows" then
- os.libsuffix,os.binsuffix,os.binsuffixes='dll','exe',{ 'exe','cmd','bat' }
-else
- os.libsuffix,os.binsuffix,os.binsuffixes='so','',{ '' }
-end
-local launchers={
- windows="start %s",
- macosx="open %s",
- unix="xdg-open %s &> /dev/null &",
-}
-function os.launch(str)
- local command=format(launchers[os.name] or launchers.unix,str)
- execute(command)
-end
-local gettimeofday=os.gettimeofday or os.clock
-os.gettimeofday=gettimeofday
-local startuptime=gettimeofday()
-function os.runtime()
- return gettimeofday()-startuptime
-end
-local resolvers=os.resolvers or {}
-os.resolvers=resolvers
-setmetatable(os,{ __index=function(t,k)
- local r=resolvers[k]
- return r and r(t,k) or nil
-end })
-local name,platform=os.name or "linux",os.getenv("MTX_PLATFORM") or ""
-if platform~="" then
- os.platform=platform
-elseif os.type=="windows" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("PROCESSOR_ARCHITECTURE") or ""
- local platform=""
- if find(architecture,"AMD64",1,true) then
- platform="win64"
- else
- platform="mswin"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="linux" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("HOSTTYPE") or resultof("uname -m") or ""
- local platform=os.getenv("MTX_PLATFORM") or ""
- local musl=find(os.selfdir or "","linuxmusl")
- if platform~="" then
- elseif find(architecture,"x86_64",1,true) then
- platform=musl and "linuxmusl" or "linux-64"
- elseif find(architecture,"ppc",1,true) then
- platform="linux-ppc"
- else
- platform=musl and "linuxmusl" or "linux"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="macosx" then
- function resolvers.platform(t,k)
- local architecture=resultof("echo $HOSTTYPE") or ""
- local platform=""
- if architecture=="" then
- platform="osx-intel"
- elseif find(architecture,"i386",1,true) then
- platform="osx-intel"
- elseif find(architecture,"x86_64",1,true) then
- platform="osx-64"
- elseif find(architecture,"arm64",1,true) then
- platform="osx-64"
- else
- platform="osx-ppc"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="sunos" then
- function resolvers.platform(t,k)
- local architecture=resultof("uname -m") or ""
- local platform=""
- if find(architecture,"sparc",1,true) then
- platform="solaris-sparc"
- else
- platform="solaris-intel"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="freebsd" then
- function resolvers.platform(t,k)
- local architecture=resultof("uname -m") or ""
- local platform=""
- if find(architecture,"amd64",1,true) then
- platform="freebsd-amd64"
- else
- platform="freebsd"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="kfreebsd" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("HOSTTYPE") or resultof("uname -m") or ""
- local platform=""
- if find(architecture,"x86_64",1,true) then
- platform="kfreebsd-amd64"
- else
- platform="kfreebsd-i386"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-else
- function resolvers.platform(t,k)
- local platform="linux"
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-end
-os.newline=name=="windows" and "\013\010" or "\010"
-function resolvers.bits(t,k)
- local bits=find(os.platform,"64",1,true) and 64 or 32
- os.bits=bits
- return bits
-end
-local t={ 8,9,"a","b" }
-function os.uuid()
- return format("%04x%04x-4%03x-%s%03x-%04x-%04x%04x%04x",
- random(0xFFFF),random(0xFFFF),
- random(0x0FFF),
- t[ceil(random(4))] or 8,random(0x0FFF),
- random(0xFFFF),
- random(0xFFFF),random(0xFFFF),random(0xFFFF)
- )
-end
-local d
-function os.timezone(delta)
- d=d or ((tonumber(date("%H")) or 0)-(tonumber(date("!%H")) or 0))
- if delta then
- if d>0 then
- return format("+%02i:00",d)
- else
- return format("-%02i:00",-d)
- end
- else
- return 1
- end
-end
-local timeformat=format("%%s%s",os.timezone(true))
-local dateformat="!%Y-%m-%d %H:%M:%S"
-local lasttime=nil
-local lastdate=nil
-function os.fulltime(t,default)
- t=t and tonumber(t) or 0
- if t>0 then
- elseif default then
- return default
- else
- t=time()
- end
- if t~=lasttime then
- lasttime=t
- lastdate=format(timeformat,date(dateformat))
- end
- return lastdate
-end
-local dateformat="%Y-%m-%d %H:%M:%S"
-local lasttime=nil
-local lastdate=nil
-function os.localtime(t,default)
- t=t and tonumber(t) or 0
- if t>0 then
- elseif default then
- return default
- else
- t=time()
- end
- if t~=lasttime then
- lasttime=t
- lastdate=date(dateformat,t)
- end
- return lastdate
-end
-function os.converttime(t,default)
- local t=tonumber(t)
- if t and t>0 then
- return date(dateformat,t)
- else
- return default or "-"
- end
-end
-local memory={}
-local function which(filename)
- local fullname=memory[filename]
- if fullname==nil then
- local suffix=file.suffix(filename)
- local suffixes=suffix=="" and os.binsuffixes or { suffix }
- for directory in gmatch(os.getenv("PATH"),"[^"..io.pathseparator.."]+") do
- local df=file.join(directory,filename)
- for i=1,#suffixes do
- local dfs=file.addsuffix(df,suffixes[i])
- if io.exists(dfs) then
- fullname=dfs
- break
- end
- end
- end
- if not fullname then
- fullname=false
- end
- memory[filename]=fullname
- end
- return fullname
-end
-os.which=which
-os.where=which
-function os.today()
- return date("!*t")
-end
-function os.now()
- return date("!%Y-%m-%d %H:%M:%S")
-end
-if not os.sleep then
- local socket=socket
- function os.sleep(n)
- if not socket then
- socket=require("socket")
- end
- socket.sleep(n)
- end
-end
-local function isleapyear(year)
- return (year%4==0) and (year%100~=0 or year%400==0)
-end
-os.isleapyear=isleapyear
-local days={ 31,28,31,30,31,30,31,31,30,31,30,31 }
-local function nofdays(year,month,day)
- if not month then
- return isleapyear(year) and 365 or 364
- elseif not day then
- return month==2 and isleapyear(year) and 29 or days[month]
- else
- for i=1,month-1 do
- day=day+days[i]
- end
- if month>2 and isleapyear(year) then
- day=day+1
- end
- return day
- end
-end
-os.nofdays=nofdays
-function os.weekday(day,month,year)
- return date("%w",time { year=year,month=month,day=day })+1
-end
-function os.validdate(year,month,day)
- if month<1 then
- month=1
- elseif month>12 then
- month=12
- end
- if day<1 then
- day=1
- else
- local max=nofdays(year,month)
- if day>max then
- day=max
- end
- end
- return year,month,day
-end
-function os.date(fmt,...)
- if not fmt then
- fmt="%Y-%m-%d %H:%M"
- end
- return date(fmt,...)
-end
-local osexit=os.exit
-local exitcode=nil
-function os.setexitcode(code)
- exitcode=code
-end
-function os.exit(c)
- if exitcode~=nil then
- return osexit(exitcode)
- end
- if c~=nil then
- return osexit(c)
- end
- return osexit()
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-file"] = package.loaded["l-file"] or true
-
--- original size: 22175, stripped down to: 10302
-
-if not modules then modules={} end modules ['l-file']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-file=file or {}
-local file=file
-if not lfs then
- lfs=optionalrequire("lfs")
-end
-local insert,concat=table.insert,table.concat
-local match,find,gmatch=string.match,string.find,string.gmatch
-local lpegmatch=lpeg.match
-local getcurrentdir,attributes=lfs.currentdir,lfs.attributes
-local checkedsplit=string.checkedsplit
-local P,R,S,C,Cs,Cp,Cc,Ct=lpeg.P,lpeg.R,lpeg.S,lpeg.C,lpeg.Cs,lpeg.Cp,lpeg.Cc,lpeg.Ct
-local attributes=lfs.attributes
-function lfs.isdir(name)
- if name then
- return attributes(name,"mode")=="directory"
- end
-end
-function lfs.isfile(name)
- if name then
- local a=attributes(name,"mode")
- return a=="file" or a=="link" or nil
- end
-end
-function lfs.isfound(name)
- if name then
- local a=attributes(name,"mode")
- return (a=="file" or a=="link") and name or nil
- end
-end
-function lfs.modification(name)
- return name and attributes(name,"modification") or nil
-end
-if sandbox then
- sandbox.redefine(lfs.isfile,"lfs.isfile")
- sandbox.redefine(lfs.isdir,"lfs.isdir")
- sandbox.redefine(lfs.isfound,"lfs.isfound")
-end
-local colon=P(":")
-local period=P(".")
-local periods=P("..")
-local fwslash=P("/")
-local bwslash=P("\\")
-local slashes=S("\\/")
-local noperiod=1-period
-local noslashes=1-slashes
-local name=noperiod^1
-local suffix=period/""*(1-period-slashes)^1*-1
-local pattern=C((1-(slashes^1*noslashes^1*-1))^1)*P(1)
-local function pathpart(name,default)
- return name and lpegmatch(pattern,name) or default or ""
-end
-local pattern=(noslashes^0*slashes)^1*C(noslashes^1)*-1
-local function basename(name)
- return name and lpegmatch(pattern,name) or name
-end
-local pattern=(noslashes^0*slashes^1)^0*Cs((1-suffix)^1)*suffix^0
-local function nameonly(name)
- return name and lpegmatch(pattern,name) or name
-end
-local pattern=(noslashes^0*slashes)^0*(noperiod^1*period)^1*C(noperiod^1)*-1
-local function suffixonly(name)
- return name and lpegmatch(pattern,name) or ""
-end
-local pattern=(noslashes^0*slashes)^0*noperiod^1*((period*C(noperiod^1))^1)*-1+Cc("")
-local function suffixesonly(name)
- if name then
- return lpegmatch(pattern,name)
- else
- return ""
- end
-end
-file.pathpart=pathpart
-file.basename=basename
-file.nameonly=nameonly
-file.suffixonly=suffixonly
-file.suffix=suffixonly
-file.suffixesonly=suffixesonly
-file.suffixes=suffixesonly
-file.dirname=pathpart
-file.extname=suffixonly
-local drive=C(R("az","AZ"))*colon
-local path=C((noslashes^0*slashes)^0)
-local suffix=period*C(P(1-period)^0*P(-1))
-local base=C((1-suffix)^0)
-local rest=C(P(1)^0)
-drive=drive+Cc("")
-path=path+Cc("")
-base=base+Cc("")
-suffix=suffix+Cc("")
-local pattern_a=drive*path*base*suffix
-local pattern_b=path*base*suffix
-local pattern_c=C(drive*path)*C(base*suffix)
-local pattern_d=path*rest
-function file.splitname(str,splitdrive)
- if not str then
- elseif splitdrive then
- return lpegmatch(pattern_a,str)
- else
- return lpegmatch(pattern_b,str)
- end
-end
-function file.splitbase(str)
- if str then
- return lpegmatch(pattern_d,str)
- else
- return "",str
- end
-end
-function file.nametotable(str,splitdrive)
- if str then
- local path,drive,subpath,name,base,suffix=lpegmatch(pattern_c,str)
- if splitdrive then
- return {
- path=path,
- drive=drive,
- subpath=subpath,
- name=name,
- base=base,
- suffix=suffix,
- }
- else
- return {
- path=path,
- name=name,
- base=base,
- suffix=suffix,
- }
- end
- end
-end
-local pattern=Cs(((period*(1-period-slashes)^1*-1)/""+1)^1)
-function file.removesuffix(name)
- return name and lpegmatch(pattern,name)
-end
-local suffix=period/""*(1-period-slashes)^1*-1
-local pattern=Cs((noslashes^0*slashes^1)^0*((1-suffix)^1))*Cs(suffix)
-function file.addsuffix(filename,suffix,criterium)
- if not filename or not suffix or suffix=="" then
- return filename
- elseif criterium==true then
- return filename.."."..suffix
- elseif not criterium then
- local n,s=lpegmatch(pattern,filename)
- if not s or s=="" then
- return filename.."."..suffix
- else
- return filename
- end
- else
- local n,s=lpegmatch(pattern,filename)
- if s and s~="" then
- local t=type(criterium)
- if t=="table" then
- for i=1,#criterium do
- if s==criterium[i] then
- return filename
- end
- end
- elseif t=="string" then
- if s==criterium then
- return filename
- end
- end
- end
- return (n or filename).."."..suffix
- end
-end
-local suffix=period*(1-period-slashes)^1*-1
-local pattern=Cs((1-suffix)^0)
-function file.replacesuffix(name,suffix)
- if name and suffix and suffix~="" then
- return lpegmatch(pattern,name).."."..suffix
- else
- return name
- end
-end
-local reslasher=lpeg.replacer(P("\\"),"/")
-function file.reslash(str)
- return str and lpegmatch(reslasher,str)
-end
-if lfs.isreadablefile and lfs.iswritablefile then
- file.is_readable=lfs.isreadablefile
- file.is_writable=lfs.iswritablefile
-else
- function file.is_writable(name)
- if not name then
- elseif lfs.isdir(name) then
- name=name.."/m_t_x_t_e_s_t.tmp"
- local f=io.open(name,"wb")
- if f then
- f:close()
- os.remove(name)
- return true
- end
- elseif lfs.isfile(name) then
- local f=io.open(name,"ab")
- if f then
- f:close()
- return true
- end
- else
- local f=io.open(name,"ab")
- if f then
- f:close()
- os.remove(name)
- return true
- end
- end
- return false
- end
- local readable=P("r")*Cc(true)
- function file.is_readable(name)
- if name then
- local a=attributes(name)
- return a and lpegmatch(readable,a.permissions) or false
- else
- return false
- end
- end
-end
-file.isreadable=file.is_readable
-file.iswritable=file.is_writable
-function file.size(name)
- if name then
- local a=attributes(name)
- return a and a.size or 0
- else
- return 0
- end
-end
-function file.splitpath(str,separator)
- return str and checkedsplit(lpegmatch(reslasher,str),separator or io.pathseparator)
-end
-function file.joinpath(tab,separator)
- return tab and concat(tab,separator or io.pathseparator)
-end
-local someslash=S("\\/")
-local stripper=Cs(P(fwslash)^0/""*reslasher)
-local isnetwork=someslash*someslash*(1-someslash)+(1-fwslash-colon)^1*colon
-local isroot=fwslash^1*-1
-local hasroot=fwslash^1
-local reslasher=lpeg.replacer(S("\\/"),"/")
-local deslasher=lpeg.replacer(S("\\/")^1,"/")
-function file.join(one,two,three,...)
- if not two then
- return one=="" and one or lpegmatch(reslasher,one)
- end
- if one=="" then
- return lpegmatch(stripper,three and concat({ two,three,... },"/") or two)
- end
- if lpegmatch(isnetwork,one) then
- local one=lpegmatch(reslasher,one)
- local two=lpegmatch(deslasher,three and concat({ two,three,... },"/") or two)
- if lpegmatch(hasroot,two) then
- return one..two
- else
- return one.."/"..two
- end
- elseif lpegmatch(isroot,one) then
- local two=lpegmatch(deslasher,three and concat({ two,three,... },"/") or two)
- if lpegmatch(hasroot,two) then
- return two
- else
- return "/"..two
- end
- else
- return lpegmatch(deslasher,concat({ one,two,three,... },"/"))
- end
-end
-local drivespec=R("az","AZ")^1*colon
-local anchors=fwslash+drivespec
-local untouched=periods+(1-period)^1*P(-1)
-local mswindrive=Cs(drivespec*(bwslash/"/"+fwslash)^0)
-local mswinuncpath=(bwslash+fwslash)*(bwslash+fwslash)*Cc("//")
-local splitstarter=(mswindrive+mswinuncpath+Cc(false))*Ct(lpeg.splitat(S("/\\")^1))
-local absolute=fwslash
-function file.collapsepath(str,anchor)
- if not str then
- return
- end
- if anchor==true and not lpegmatch(anchors,str) then
- str=getcurrentdir().."/"..str
- end
- if str=="" or str=="." then
- return "."
- elseif lpegmatch(untouched,str) then
- return lpegmatch(reslasher,str)
- end
- local starter,oldelements=lpegmatch(splitstarter,str)
- local newelements={}
- local i=#oldelements
- while i>0 do
- local element=oldelements[i]
- if element=='.' then
- elseif element=='..' then
- local n=i-1
- while n>0 do
- local element=oldelements[n]
- if element~='..' and element~='.' then
- oldelements[n]='.'
- break
- else
- n=n-1
- end
- end
- if n<1 then
- insert(newelements,1,'..')
- end
- elseif element~="" then
- insert(newelements,1,element)
- end
- i=i-1
- end
- if #newelements==0 then
- return starter or "."
- elseif starter then
- return starter..concat(newelements,'/')
- elseif lpegmatch(absolute,str) then
- return "/"..concat(newelements,'/')
- else
- newelements=concat(newelements,'/')
- if anchor=="." and find(str,"^%./") then
- return "./"..newelements
- else
- return newelements
- end
- end
-end
-local validchars=R("az","09","AZ","--","..")
-local pattern_a=lpeg.replacer(1-validchars)
-local pattern_a=Cs((validchars+P(1)/"-")^1)
-local whatever=P("-")^0/""
-local pattern_b=Cs(whatever*(1-whatever*-1)^1)
-function file.robustname(str,strict)
- if str then
- str=lpegmatch(pattern_a,str) or str
- if strict then
- return lpegmatch(pattern_b,str) or str
- else
- return str
- end
- end
-end
-local loaddata=io.loaddata
-local savedata=io.savedata
-file.readdata=loaddata
-file.savedata=savedata
-function file.copy(oldname,newname)
- if oldname and newname then
- local data=loaddata(oldname)
- if data and data~="" then
- savedata(newname,data)
- end
- end
-end
-local letter=R("az","AZ")+S("_-+")
-local separator=P("://")
-local qualified=period^0*fwslash+letter*colon+letter^1*separator+letter^1*fwslash
-local rootbased=fwslash+letter*colon
-lpeg.patterns.qualified=qualified
-lpeg.patterns.rootbased=rootbased
-function file.is_qualified_path(filename)
- return filename and lpegmatch(qualified,filename)~=nil
-end
-function file.is_rootbased_path(filename)
- return filename and lpegmatch(rootbased,filename)~=nil
-end
-function file.strip(name,dir)
- if name then
- local b,a=match(name,"^(.-)"..dir.."(.*)$")
- return a~="" and a or name
- end
-end
-function lfs.mkdirs(path)
- local full=""
- for sub in gmatch(path,"(/*[^\\/]+)") do
- full=full..sub
- lfs.mkdir(full)
- end
-end
-function file.withinbase(path)
- local l=0
- if not find(path,"^/") then
- path="/"..path
- end
- for dir in gmatch(path,"/([^/]+)") do
- if dir==".." then
- l=l-1
- elseif dir~="." then
- l=l+1
- end
- if l<0 then
- return false
- end
- end
- return true
-end
-local symlinkattributes=lfs.symlinkattributes
-function lfs.readlink(name)
- return symlinkattributes(name,"target") or nil
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-gzip"] = package.loaded["l-gzip"] or true
-
--- original size: 5115, stripped down to: 1699
-
-if not modules then modules={} end modules ['l-gzip']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-gzip=gzip or {}
-if not zlib then
- zlib=xzip
-elseif not xzip then
- xzip=zlib
-end
-if zlib then
- local suffix=file.suffix
- local suffixes=file.suffixes
- local find=string.find
- local openfile=io.open
- local gzipwindow=15+16
- local gziplevel=3
- local identifier="^\x1F\x8B\x08"
- local compress=zlib.compress
- local decompress=zlib.decompress
- function gzip.load(filename)
- local f=openfile(filename,"rb")
- if not f then
- else
- local data=f:read("*all")
- f:close()
- if data and data~="" then
- if suffix(filename)=="gz" then
- data=decompress(data,gzipwindow)
- end
- return data
- end
- end
- end
- function gzip.save(filename,data,level)
- if suffix(filename)~="gz" then
- filename=filename..".gz"
- end
- local f=openfile(filename,"wb")
- if f then
- data=compress(data or "",level or gziplevel,nil,gzipwindow)
- f:write(data)
- f:close()
- return #data
- end
- end
- function gzip.suffix(filename)
- local suffix,extra=suffixes(filename)
- local gzipped=extra=="gz"
- return suffix,gzipped
- end
- function gzip.compressed(s)
- return s and find(s,identifier)
- end
- function gzip.compress(s,level)
- if s and not find(s,identifier) then
- if not level then
- level=gziplevel
- elseif level<=0 then
- return s
- elseif level>9 then
- level=9
- end
- return compress(s,level or gziplevel,nil,gzipwindow) or s
- end
- end
- function gzip.decompress(s)
- if s and find(s,identifier) then
- return decompress(s,gzipwindow)
- else
- return s
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-md5"] = package.loaded["l-md5"] or true
-
--- original size: 3414, stripped down to: 2307
-
-if not modules then modules={} end modules ['l-md5']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if not md5 then
- md5=optionalrequire("md5")
-end
-if not md5 then
- md5={
- sum=function(str) print("error: md5 is not loaded (sum ignored)") return str end,
- sumhexa=function(str) print("error: md5 is not loaded (sumhexa ignored)") return str end,
- }
-end
-local md5,file=md5,file
-local gsub=string.gsub
-local modification,isfile,touch=lfs.modification,lfs.isfile,lfs.touch
-local loaddata,savedata=io.loaddata,io.savedata
-do
- local patterns=lpeg and lpeg.patterns
- if patterns then
- local bytestoHEX=patterns.bytestoHEX
- local bytestohex=patterns.bytestohex
- local bytestodec=patterns.bytestodec
- local lpegmatch=lpeg.match
- local md5sum=md5.sum
- if not md5.HEX then function md5.HEX(str) if str then return lpegmatch(bytestoHEX,md5sum(str)) end end end
- if not md5.hex then function md5.hex(str) if str then return lpegmatch(bytestohex,md5sum(str)) end end end
- if not md5.dec then function md5.dec(str) if str then return lpegmatch(bytestodec,md5sum(str)) end end end
- md5.sumhexa=md5.hex
- md5.sumHEXA=md5.HEX
- end
-end
-local md5HEX=md5.HEX
-function file.needsupdating(oldname,newname,threshold)
- local oldtime=modification(oldname)
- if oldtime then
- local newtime=modification(newname)
- if not newtime then
- return true
- elseif newtime>=oldtime then
- return false
- elseif oldtime-newtime<(threshold or 1) then
- return false
- else
- return true
- end
- else
- return false
- end
-end
-file.needs_updating=file.needsupdating
-function file.syncmtimes(oldname,newname)
- local oldtime=modification(oldname)
- if oldtime and isfile(newname) then
- touch(newname,oldtime,oldtime)
- end
-end
-local function checksum(name)
- if md5 then
- local data=loaddata(name)
- if data then
- return md5HEX(data)
- end
- end
- return nil
-end
-file.checksum=checksum
-function file.loadchecksum(name)
- if md5 then
- local data=loaddata(name..".md5")
- return data and (gsub(data,"%s",""))
- end
- return nil
-end
-function file.savechecksum(name,checksum)
- if not checksum then checksum=checksum(name) end
- if checksum then
- savedata(name..".md5",checksum)
- return checksum
- end
- return nil
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-sha"] = package.loaded["l-sha"] or true
-
--- original size: 1085, stripped down to: 969
-
-if not modules then modules={} end modules ['l-sha']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if sha2 then
- local lpegmatch=lpeg.match
- local lpegpatterns=lpeg.patterns
- local bytestohex=lpegpatterns.bytestohex
- local bytestoHEX=lpegpatterns.bytestoHEX
- local digest256=sha2.digest256
- local digest384=sha2.digest384
- local digest512=sha2.digest512
- sha2.hash256=function(str) return lpegmatch(bytestohex,digest256(str)) end
- sha2.hash384=function(str) return lpegmatch(bytestohex,digest384(str)) end
- sha2.hash512=function(str) return lpegmatch(bytestohex,digest512(str)) end
- sha2.HASH256=function(str) return lpegmatch(bytestoHEX,digest256(str)) end
- sha2.HASH384=function(str) return lpegmatch(bytestoHEX,digest384(str)) end
- sha2.HASH512=function(str) return lpegmatch(bytestoHEX,digest512(str)) end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-url"] = package.loaded["l-url"] or true
-
--- original size: 14755, stripped down to: 6981
-
-if not modules then modules={} end modules ['l-url']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local char,format,byte=string.char,string.format,string.byte
-local concat=table.concat
-local tonumber,type,next=tonumber,type,next
-local P,C,R,S,Cs,Cc,Ct,Cf,Cg,V=lpeg.P,lpeg.C,lpeg.R,lpeg.S,lpeg.Cs,lpeg.Cc,lpeg.Ct,lpeg.Cf,lpeg.Cg,lpeg.V
-local lpegmatch,lpegpatterns,replacer=lpeg.match,lpeg.patterns,lpeg.replacer
-local sortedhash=table.sortedhash
-url=url or {}
-local url=url
-local unescapes={}
-local escapes={}
-setmetatable(unescapes,{ __index=function(t,k)
- local v=char(tonumber(k,16))
- t[k]=v
- return v
-end })
-setmetatable(escapes,{ __index=function(t,k)
- local v=format("%%%02X",byte(k))
- t[k]=v
- return v
-end })
-local colon=P(":")
-local qmark=P("?")
-local hash=P("#")
-local slash=P("/")
-local atsign=P("@")
-local percent=P("%")
-local endofstring=P(-1)
-local hexdigit=R("09","AF","af")
-local plus=P("+")
-local nothing=Cc("")
-local okay=R("09","AZ","az")+S("-_.,:=+*~!'()@&$")
-local escapedchar=(percent*C(hexdigit*hexdigit))/unescapes
-local unescapedchar=P(1)/escapes
-local escaped=(plus/" ")+escapedchar
-local noslash=P("/")/""
-local plustospace=P("+")/" "
-local decoder=Cs((
- plustospace+escapedchar+P("\r\n")/"\n"+P(1)
- )^0 )
-local encoder=Cs((
- R("09","AZ","az")^1+S("-./_")^1+P(" ")/"+"+P("\n")/"\r\n"+unescapedchar
- )^0 )
-lpegpatterns.urldecoder=decoder
-lpegpatterns.urlencoder=encoder
-function url.decode (str) return str and lpegmatch(decoder,str) or str end
-function url.encode (str) return str and lpegmatch(encoder,str) or str end
-function url.unescape(str) return str and lpegmatch(unescaper,str) or str end
-local schemestr=Cs((escaped+(1-colon-slash-qmark-hash))^2)
-local authoritystr=Cs((escaped+(1- slash-qmark-hash))^0)
-local pathstr=Cs((escaped+(1- qmark-hash))^0)
-local querystr=Cs(((1- hash))^0)
-local fragmentstr=Cs((escaped+(1- endofstring))^0)
-local scheme=schemestr*colon+nothing
-local authority=slash*slash*authoritystr+nothing
-local path=slash*pathstr+nothing
-local query=qmark*querystr+nothing
-local fragment=hash*fragmentstr+nothing
-local validurl=scheme*authority*path*query*fragment
-local parser=Ct(validurl)
-lpegpatterns.url=validurl
-lpegpatterns.urlsplitter=parser
-local escaper=Cs((R("09","AZ","az")^1+P(" ")/"%%20"+S("-./_:")^1+P(1)/escapes)^0)
-local unescaper=Cs((escapedchar+1)^0)
-local getcleaner=Cs((P("+++")/"%%2B"+P("+")/"%%20"+P(1))^1)
-lpegpatterns.urlunescaped=escapedchar
-lpegpatterns.urlescaper=escaper
-lpegpatterns.urlunescaper=unescaper
-lpegpatterns.urlgetcleaner=getcleaner
-function url.unescapeget(str)
- return lpegmatch(getcleaner,str)
-end
-local function split(str)
- return (type(str)=="string" and lpegmatch(parser,str)) or str
-end
-local isscheme=schemestr*colon*slash*slash
-local function hasscheme(str)
- if str then
- local scheme=lpegmatch(isscheme,str)
- return scheme~="" and scheme or false
- else
- return false
- end
-end
-local rootletter=R("az","AZ")+S("_-+")
-local separator=P("://")
-local qualified=P(".")^0*P("/")+rootletter*P(":")+rootletter^1*separator+rootletter^1*P("/")
-local rootbased=P("/")+rootletter*P(":")
-local barswapper=replacer("|",":")
-local backslashswapper=replacer("\\","/")
-local equal=P("=")
-local amp=P("&")
-local key=Cs(((plustospace+escapedchar+1)-equal )^0)
-local value=Cs(((plustospace+escapedchar+1)-amp-endofstring)^0)
-local splitquery=Cf (Ct("")*P { "sequence",
- sequence=V("pair")*(amp*V("pair"))^0,
- pair=Cg(key*equal*value),
-},rawset)
-local userpart=(1-atsign-colon)^1
-local serverpart=(1-colon)^1
-local splitauthority=((Cs(userpart)*colon*Cs(userpart)+Cs(userpart)*Cc(nil))*atsign+Cc(nil)*Cc(nil))*Cs(serverpart)*(colon*(serverpart/tonumber)+Cc(nil))
-local function hashed(str)
- if not str or str=="" then
- return {
- scheme="invalid",
- original=str,
- }
- end
- local detailed=split(str)
- local rawscheme=""
- local rawquery=""
- local somescheme=false
- local somequery=false
- if detailed then
- rawscheme=detailed[1]
- rawquery=detailed[4]
- somescheme=rawscheme~=""
- somequery=rawquery~=""
- end
- if not somescheme and not somequery then
- return {
- scheme="file",
- authority="",
- path=str,
- query="",
- fragment="",
- original=str,
- noscheme=true,
- filename=str,
- }
- end
- local authority=detailed[2]
- local path=detailed[3]
- local filename
- local username
- local password
- local host
- local port
- if authority~="" then
- username,password,host,port=lpegmatch(splitauthority,authority)
- end
- if authority=="" then
- filename=path
- elseif path=="" then
- filename=""
- else
- filename=authority.."/"..path
- end
- return {
- scheme=rawscheme,
- authority=authority,
- path=path,
- query=lpegmatch(unescaper,rawquery),
- queries=lpegmatch(splitquery,rawquery),
- fragment=detailed[5],
- original=str,
- noscheme=false,
- filename=filename,
- host=host,
- port=port,
- }
-end
-url.split=split
-url.hasscheme=hasscheme
-url.hashed=hashed
-function url.addscheme(str,scheme)
- if hasscheme(str) then
- return str
- elseif not scheme then
- return "file:///"..str
- else
- return scheme..":///"..str
- end
-end
-function url.construct(hash)
- local result,r={},0
- local scheme=hash.scheme
- local authority=hash.authority
- local path=hash.path
- local queries=hash.queries
- local fragment=hash.fragment
- if scheme and scheme~="" then
- r=r+1;result[r]=lpegmatch(escaper,scheme)
- r=r+1;result[r]="://"
- end
- if authority and authority~="" then
- r=r+1;result[r]=lpegmatch(escaper,authority)
- end
- if path and path~="" then
- r=r+1;result[r]="/"
- r=r+1;result[r]=lpegmatch(escaper,path)
- end
- if queries then
- local done=false
- for k,v in sortedhash(queries) do
- r=r+1;result[r]=done and "&" or "?"
- r=r+1;result[r]=lpegmatch(escaper,k)
- r=r+1;result[r]="="
- r=r+1;result[r]=lpegmatch(escaper,v)
- done=true
- end
- end
- if fragment and fragment~="" then
- r=r+1;result[r]="#"
- r=r+1;result[r]=lpegmatch(escaper,fragment)
- end
- return concat(result)
-end
-local pattern=Cs(slash^-1/""*R("az","AZ")*((S(":|")/":")+P(":"))*slash*P(1)^0)
-function url.filename(filename)
- local spec=hashed(filename)
- local path=spec.path
- return (spec.scheme=="file" and path and lpegmatch(pattern,path)) or filename
-end
-local function escapestring(str)
- return lpegmatch(escaper,str)
-end
-url.escape=escapestring
-function url.query(str)
- if type(str)=="string" then
- return lpegmatch(splitquery,str) or ""
- else
- return str
- end
-end
-function url.toquery(data)
- local td=type(data)
- if td=="string" then
- return #str and escape(data) or nil
- elseif td=="table" then
- if next(data) then
- local t={}
- for k,v in next,data do
- t[#t+1]=format("%s=%s",k,escapestring(v))
- end
- return concat(t,"&")
- end
- else
- end
-end
-local pattern=Cs(noslash^0*(1-noslash*P(-1))^0)
-function url.barepath(path)
- if not path or path=="" then
- return ""
- else
- return lpegmatch(pattern,path)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-dir"] = package.loaded["l-dir"] or true
-
--- original size: 18253, stripped down to: 10816
-
-if not modules then modules={} end modules ['l-dir']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,select=type,select
-local find,gmatch,match,gsub,sub=string.find,string.gmatch,string.match,string.gsub,string.sub
-local concat,insert,remove,unpack=table.concat,table.insert,table.remove,table.unpack
-local lpegmatch=lpeg.match
-local P,S,R,C,Cc,Cs,Ct,Cv,V=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.Cc,lpeg.Cs,lpeg.Ct,lpeg.Cv,lpeg.V
-dir=dir or {}
-local dir=dir
-local lfs=lfs
-local attributes=lfs.attributes
-local walkdir=lfs.dir
-local isdir=lfs.isdir
-local isfile=lfs.isfile
-local currentdir=lfs.currentdir
-local chdir=lfs.chdir
-local mkdir=lfs.mkdir
-local onwindows=os.type=="windows" or find(os.getenv("PATH"),";",1,true)
-if onwindows then
- local tricky=S("/\\")*P(-1)
- isdir=function(name)
- if lpegmatch(tricky,name) then
- return attributes(name,"mode")=="directory"
- else
- return attributes(name.."/.","mode")=="directory"
- end
- end
- isfile=function(name)
- return attributes(name,"mode")=="file"
- end
- lfs.isdir=isdir
- lfs.isfile=isfile
-else
- isdir=function(name)
- return attributes(name,"mode")=="directory"
- end
- isfile=function(name)
- return attributes(name,"mode")=="file"
- end
- lfs.isdir=isdir
- lfs.isfile=isfile
-end
-function dir.current()
- return (gsub(currentdir(),"\\","/"))
-end
-local function glob_pattern_function(path,patt,recurse,action)
- if isdir(path) then
- local usedpath
- if path=="/" then
- usedpath="/."
- elseif not find(path,"/$") then
- usedpath=path.."/."
- path=path.."/"
- else
- usedpath=path
- end
- local dirs
- local nofdirs=0
- for name,mode,size,time in walkdir(usedpath) do
- if name~="." and name~=".." then
- local full=path..name
- if mode==nil then
- mode=attributes(full,'mode')
- end
- if mode=='file' then
- if not patt or find(full,patt) then
- action(full,size,time)
- end
- elseif recurse and mode=="directory" then
- if dirs then
- nofdirs=nofdirs+1
- dirs[nofdirs]=full
- else
- nofdirs=1
- dirs={ full }
- end
- end
- end
- end
- if dirs then
- for i=1,nofdirs do
- glob_pattern_function(dirs[i],patt,recurse,action)
- end
- end
- end
-end
-local function glob_pattern_table(path,patt,recurse,result)
- if not result then
- result={}
- end
- local usedpath
- if path=="/" then
- usedpath="/."
- elseif not find(path,"/$") then
- usedpath=path.."/."
- path=path.."/"
- else
- usedpath=path
- end
- local dirs
- local nofdirs=0
- local noffiles=#result
- for name,mode in walkdir(usedpath) do
- if name~="." and name~=".." then
- local full=path..name
- if mode==nil then
- mode=attributes(full,'mode')
- end
- if mode=='file' then
- if not patt or find(full,patt) then
- noffiles=noffiles+1
- result[noffiles]=full
- end
- elseif recurse and mode=="directory" then
- if dirs then
- nofdirs=nofdirs+1
- dirs[nofdirs]=full
- else
- nofdirs=1
- dirs={ full }
- end
- end
- end
- end
- if dirs then
- for i=1,nofdirs do
- glob_pattern_table(dirs[i],patt,recurse,result)
- end
- end
- return result
-end
-local function globpattern(path,patt,recurse,method)
- local kind=type(method)
- if patt and sub(patt,1,-3)==path then
- patt=false
- end
- local okay=isdir(path)
- if kind=="function" then
- return okay and glob_pattern_function(path,patt,recurse,method) or {}
- elseif kind=="table" then
- return okay and glob_pattern_table(path,patt,recurse,method) or method
- else
- return okay and glob_pattern_table(path,patt,recurse,{}) or {}
- end
-end
-dir.globpattern=globpattern
-local function collectpattern(path,patt,recurse,result)
- local ok,scanner
- result=result or {}
- if path=="/" then
- ok,scanner,first=xpcall(function() return walkdir(path..".") end,function() end)
- else
- ok,scanner,first=xpcall(function() return walkdir(path) end,function() end)
- end
- if ok and type(scanner)=="function" then
- if not find(path,"/$") then
- path=path..'/'
- end
- for name in scanner,first do
- if name=="." then
- elseif name==".." then
- else
- local full=path..name
- local attr=attributes(full)
- local mode=attr.mode
- if mode=='file' then
- if find(full,patt) then
- result[name]=attr
- end
- elseif recurse and mode=="directory" then
- attr.list=collectpattern(full,patt,recurse)
- result[name]=attr
- end
- end
- end
- end
- return result
-end
-dir.collectpattern=collectpattern
-local separator,pattern
-if onwindows then
- local slash=S("/\\")/"/"
- pattern={
- [1]=(Cs(P(".")+slash^1)+Cs(R("az","AZ")*P(":")*slash^0)+Cc("./"))*V(2)*V(3),
- [2]=Cs(((1-S("*?/\\"))^0*slash)^0),
- [3]=Cs(P(1)^0)
- }
-else
- pattern={
- [1]=(C(P(".")+P("/")^1)+Cc("./"))*V(2)*V(3),
- [2]=C(((1-S("*?/"))^0*P("/"))^0),
- [3]=C(P(1)^0)
- }
-end
-local filter=Cs ((
- P("**")/".*"+P("*")/"[^/]*"+P("?")/"[^/]"+P(".")/"%%."+P("+")/"%%+"+P("-")/"%%-"+P(1)
-)^0 )
-local function glob(str,t)
- if type(t)=="function" then
- if type(str)=="table" then
- for s=1,#str do
- glob(str[s],t)
- end
- elseif isfile(str) then
- t(str)
- else
- local root,path,base=lpegmatch(pattern,str)
- if root and path and base then
- local recurse=find(base,"**",1,true)
- local start=root..path
- local result=lpegmatch(filter,start..base)
- globpattern(start,result,recurse,t)
- end
- end
- else
- if type(str)=="table" then
- local t=t or {}
- for s=1,#str do
- glob(str[s],t)
- end
- return t
- elseif isfile(str) then
- if t then
- t[#t+1]=str
- return t
- else
- return { str }
- end
- else
- local root,path,base=lpegmatch(pattern,str)
- if root and path and base then
- local recurse=find(base,"**",1,true)
- local start=root..path
- local result=lpegmatch(filter,start..base)
- return globpattern(start,result,recurse,t)
- else
- return {}
- end
- end
- end
-end
-dir.glob=glob
-local function globfiles(path,recurse,func,files)
- if type(func)=="string" then
- local s=func
- func=function(name) return find(name,s) end
- end
- files=files or {}
- local noffiles=#files
- for name,mode in walkdir(path) do
- if find(name,"^%.") then
- else
- if mode==nil then
- mode=attributes(name,'mode')
- end
- if mode=="directory" then
- if recurse then
- globfiles(path.."/"..name,recurse,func,files)
- end
- elseif mode=="file" then
- if not func or func(name) then
- noffiles=noffiles+1
- files[noffiles]=path.."/"..name
- end
- end
- end
- end
- return files
-end
-dir.globfiles=globfiles
-local function globdirs(path,recurse,func,files)
- if type(func)=="string" then
- local s=func
- func=function(name) return find(name,s) end
- end
- files=files or {}
- local noffiles=#files
- for name,mode in walkdir(path) do
- if find(name,"^%.") then
- else
- if mode==nil then
- mode=attributes(name,'mode')
- end
- if mode=="directory" then
- if not func or func(name) then
- noffiles=noffiles+1
- files[noffiles]=path.."/"..name
- if recurse then
- globdirs(path.."/"..name,recurse,func,files)
- end
- end
- end
- end
- end
- return files
-end
-dir.globdirs=globdirs
-function dir.ls(pattern)
- return concat(glob(pattern),"\n")
-end
-local make_indeed=true
-if onwindows then
- function dir.mkdirs(...)
- local n=select("#",...)
- local str
- if n==1 then
- str=select(1,...)
- if isdir(str) then
- return str,true
- end
- else
- str=""
- for i=1,n do
- local s=select(i,...)
- if s=="" then
- elseif str=="" then
- str=s
- else
- str=str.."/"..s
- end
- end
- end
- local pth=""
- local drive=false
- local first,middle,last=match(str,"^(//)(//*)(.*)$")
- if first then
- else
- first,last=match(str,"^(//)/*(.-)$")
- if first then
- middle,last=match(str,"([^/]+)/+(.-)$")
- if middle then
- pth="//"..middle
- else
- pth="//"..last
- last=""
- end
- else
- first,middle,last=match(str,"^([a-zA-Z]:)(/*)(.-)$")
- if first then
- pth,drive=first..middle,true
- else
- middle,last=match(str,"^(/*)(.-)$")
- if not middle then
- last=str
- end
- end
- end
- end
- for s in gmatch(last,"[^/]+") do
- if pth=="" then
- pth=s
- elseif drive then
- pth,drive=pth..s,false
- else
- pth=pth.."/"..s
- end
- if make_indeed and not isdir(pth) then
- mkdir(pth)
- end
- end
- return pth,(isdir(pth)==true)
- end
-else
- function dir.mkdirs(...)
- local n=select("#",...)
- local str,pth
- if n==1 then
- str=select(1,...)
- if isdir(str) then
- return str,true
- end
- else
- str=""
- for i=1,n do
- local s=select(i,...)
- if s and s~="" then
- if str~="" then
- str=str.."/"..s
- else
- str=s
- end
- end
- end
- end
- str=gsub(str,"/+","/")
- if find(str,"^/") then
- pth="/"
- for s in gmatch(str,"[^/]+") do
- local first=(pth=="/")
- if first then
- pth=pth..s
- else
- pth=pth.."/"..s
- end
- if make_indeed and not first and not isdir(pth) then
- mkdir(pth)
- end
- end
- else
- pth="."
- for s in gmatch(str,"[^/]+") do
- pth=pth.."/"..s
- if make_indeed and not isdir(pth) then
- mkdir(pth)
- end
- end
- end
- return pth,(isdir(pth)==true)
- end
-end
-dir.makedirs=dir.mkdirs
-do
- local chdir=sandbox and sandbox.original(chdir) or chdir
- if onwindows then
- local xcurrentdir=dir.current
- function dir.expandname(str)
- local first,nothing,last=match(str,"^(//)(//*)(.*)$")
- if first then
- first=xcurrentdir().."/"
- end
- if not first then
- first,last=match(str,"^(//)/*(.*)$")
- end
- if not first then
- first,last=match(str,"^([a-zA-Z]:)(.*)$")
- if first and not find(last,"^/") then
- local d=currentdir()
- if chdir(first) then
- first=xcurrentdir()
- end
- chdir(d)
- end
- end
- if not first then
- first,last=xcurrentdir(),str
- end
- last=gsub(last,"//","/")
- last=gsub(last,"/%./","/")
- last=gsub(last,"^/*","")
- first=gsub(first,"/*$","")
- if last=="" or last=="." then
- return first
- else
- return first.."/"..last
- end
- end
- else
- function dir.expandname(str)
- if not find(str,"^/") then
- str=currentdir().."/"..str
- end
- str=gsub(str,"//","/")
- str=gsub(str,"/%./","/")
- str=gsub(str,"(.)/%.$","%1")
- return str
- end
- end
-end
-file.expandname=dir.expandname
-local stack={}
-function dir.push(newdir)
- local curdir=currentdir()
- insert(stack,curdir)
- if newdir and newdir~="" and chdir(newdir) then
- return newdir
- else
- return curdir
- end
-end
-function dir.pop()
- local d=remove(stack)
- if d then
- chdir(d)
- end
- return d
-end
-local function found(...)
- for i=1,select("#",...) do
- local path=select(i,...)
- local kind=type(path)
- if kind=="string" then
- if isdir(path) then
- return path
- end
- elseif kind=="table" then
- local path=found(unpack(path))
- if path then
- return path
- end
- end
- end
-end
-dir.found=found
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-boolean"] = package.loaded["l-boolean"] or true
-
--- original size: 1850, stripped down to: 1498
-
-if not modules then modules={} end modules ['l-boolean']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,tonumber=type,tonumber
-boolean=boolean or {}
-local boolean=boolean
-function boolean.tonumber(b)
- if b then return 1 else return 0 end
-end
-function toboolean(str,tolerant)
- if str==nil then
- return false
- elseif str==false then
- return false
- elseif str==true then
- return true
- elseif str=="true" then
- return true
- elseif str=="false" then
- return false
- elseif not tolerant then
- return false
- elseif str==0 then
- return false
- elseif (tonumber(str) or 0)>0 then
- return true
- else
- return str=="yes" or str=="on" or str=="t"
- end
-end
-string.toboolean=toboolean
-function string.booleanstring(str)
- if str=="0" then
- return false
- elseif str=="1" then
- return true
- elseif str=="" then
- return false
- elseif str=="false" then
- return false
- elseif str=="true" then
- return true
- elseif (tonumber(str) or 0)>0 then
- return true
- else
- return str=="yes" or str=="on" or str=="t"
- end
-end
-function string.is_boolean(str,default,strict)
- if type(str)=="string" then
- if str=="true" or str=="yes" or str=="on" or str=="t" or (not strict and str=="1") then
- return true
- elseif str=="false" or str=="no" or str=="off" or str=="f" or (not strict and str=="0") then
- return false
- end
- end
- return default
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-unicode"] = package.loaded["l-unicode"] or true
-
--- original size: 41303, stripped down to: 17277
-
-if not modules then modules={} end modules ['l-unicode']={
- version=1.001,
- optimize=true,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utf=utf or {}
-unicode=nil
-if not string.utfcharacters then
- local gmatch=string.gmatch
- function string.characters(str)
- return gmatch(str,".[\128-\191]*")
- end
-end
-utf.characters=string.utfcharacters
-local type=type
-local char,byte,format,sub,gmatch=string.char,string.byte,string.format,string.sub,string.gmatch
-local concat=table.concat
-local P,C,R,Cs,Ct,Cmt,Cc,Carg,Cp=lpeg.P,lpeg.C,lpeg.R,lpeg.Cs,lpeg.Ct,lpeg.Cmt,lpeg.Cc,lpeg.Carg,lpeg.Cp
-local lpegmatch=lpeg.match
-local patterns=lpeg.patterns
-local tabletopattern=lpeg.utfchartabletopattern
-local bytepairs=string.bytepairs
-local finder=lpeg.finder
-local replacer=lpeg.replacer
-local p_utftype=patterns.utftype
-local p_utfstricttype=patterns.utfstricttype
-local p_utfoffset=patterns.utfoffset
-local p_utf8character=patterns.utf8character
-local p_utf8char=patterns.utf8char
-local p_utf8byte=patterns.utf8byte
-local p_utfbom=patterns.utfbom
-local p_newline=patterns.newline
-local p_whitespace=patterns.whitespace
-if not utf.char then
- utf.char=string.utfcharacter or (utf8 and utf8.char)
- if not utf.char then
- local char=string.char
- if bit32 then
- local rshift=bit32.rshift
- function utf.char(n)
- if n<0x80 then
- return char(n)
- elseif n<0x800 then
- return char(
- 0xC0+rshift(n,6),
- 0x80+(n%0x40)
- )
- elseif n<0x10000 then
- return char(
- 0xE0+rshift(n,12),
- 0x80+(rshift(n,6)%0x40),
- 0x80+(n%0x40)
- )
- elseif n<0x200000 then
- return char(
- 0xF0+rshift(n,18),
- 0x80+(rshift(n,12)%0x40),
- 0x80+(rshift(n,6)%0x40),
- 0x80+(n%0x40)
- )
- else
- return ""
- end
- end
- else
- local floor=math.floor
- function utf.char(n)
- if n<0x80 then
- return char(n)
- elseif n<0x800 then
- return char(
- 0xC0+floor(n/0x40),
- 0x80+(n%0x40)
- )
- elseif n<0x10000 then
- return char(
- 0xE0+floor(n/0x1000),
- 0x80+(floor(n/0x40)%0x40),
- 0x80+(n%0x40)
- )
- elseif n<0x200000 then
- return char(
- 0xF0+floor(n/0x40000),
- 0x80+(floor(n/0x1000)%0x40),
- 0x80+(floor(n/0x40)%0x40),
- 0x80+(n%0x40)
- )
- else
- return ""
- end
- end
- end
- end
-end
-if not utf.byte then
- utf.byte=string.utfvalue or (utf8 and utf8.codepoint)
- if not utf.byte then
- function utf.byte(c)
- return lpegmatch(p_utf8byte,c)
- end
- end
-end
-local utfchar,utfbyte=utf.char,utf.byte
-function utf.filetype(data)
- return data and lpegmatch(p_utftype,data) or "unknown"
-end
-local toentities=Cs (
- (
- patterns.utf8one+(
- patterns.utf8two+patterns.utf8three+patterns.utf8four
- )/function(s) local b=utfbyte(s) if b<127 then return s else return format("&#%X;",b) end end
- )^0
-)
-patterns.toentities=toentities
-function utf.toentities(str)
- return lpegmatch(toentities,str)
-end
-local one=P(1)
-local two=C(1)*C(1)
-local four=C(R(utfchar(0xD8),utfchar(0xFF)))*C(1)*C(1)*C(1)
-local pattern=P("\254\255")*Cs((
- four/function(a,b,c,d)
- local ab=0xFF*byte(a)+byte(b)
- local cd=0xFF*byte(c)+byte(d)
- return utfchar((ab-0xD800)*0x400+(cd-0xDC00)+0x10000)
- end+two/function(a,b)
- return utfchar(byte(a)*256+byte(b))
- end+one
- )^1 )+P("\255\254")*Cs((
- four/function(b,a,d,c)
- local ab=0xFF*byte(a)+byte(b)
- local cd=0xFF*byte(c)+byte(d)
- return utfchar((ab-0xD800)*0x400+(cd-0xDC00)+0x10000)
- end+two/function(b,a)
- return utfchar(byte(a)*256+byte(b))
- end+one
- )^1 )
-function string.toutf(s)
- return lpegmatch(pattern,s) or s
-end
-local validatedutf=Cs (
- (
- patterns.utf8one+patterns.utf8two+patterns.utf8three+patterns.utf8four+P(1)/"�"
- )^0
-)
-patterns.validatedutf=validatedutf
-function utf.is_valid(str)
- return type(str)=="string" and lpegmatch(validatedutf,str) or false
-end
-if not utf.len then
- utf.len=string.utflength or (utf8 and utf8.len)
- if not utf.len then
- local n,f=0,1
- local utfcharcounter=patterns.utfbom^-1*Cmt (
- Cc(1)*patterns.utf8one^1+Cc(2)*patterns.utf8two^1+Cc(3)*patterns.utf8three^1+Cc(4)*patterns.utf8four^1,
- function(_,t,d)
- n=n+(t-f)/d
- f=t
- return true
- end
- )^0
- function utf.len(str)
- n,f=0,1
- lpegmatch(utfcharcounter,str or "")
- return n
- end
- end
-end
-utf.length=utf.len
-if not utf.sub then
- local utflength=utf.length
- local b,e,n,first,last=0,0,0,0,0
- local function slide_zero(s,p)
- n=n+1
- if n>=last then
- e=p-1
- else
- return p
- end
- end
- local function slide_one(s,p)
- n=n+1
- if n==first then
- b=p
- end
- if n>=last then
- e=p-1
- else
- return p
- end
- end
- local function slide_two(s,p)
- n=n+1
- if n==first then
- b=p
- else
- return true
- end
- end
- local pattern_zero=Cmt(p_utf8character,slide_zero)^0
- local pattern_one=Cmt(p_utf8character,slide_one )^0
- local pattern_two=Cmt(p_utf8character,slide_two )^0
- local pattern_first=C(p_utf8character)
- function utf.sub(str,start,stop)
- if not start then
- return str
- end
- if start==0 then
- start=1
- end
- if not stop then
- if start<0 then
- local l=utflength(str)
- start=l+start
- else
- start=start-1
- end
- b,n,first=0,0,start
- lpegmatch(pattern_two,str)
- if n>=first then
- return sub(str,b)
- else
- return ""
- end
- end
- if start<0 or stop<0 then
- local l=utf.length(str)
- if start<0 then
- start=l+start
- if start<=0 then
- start=1
- else
- start=start+1
- end
- end
- if stop<0 then
- stop=l+stop
- if stop==0 then
- stop=1
- else
- stop=stop+1
- end
- end
- end
- if start==1 and stop==1 then
- return lpegmatch(pattern_first,str) or ""
- elseif start>stop then
- return ""
- elseif start>1 then
- b,e,n,first,last=0,0,0,start-1,stop
- lpegmatch(pattern_one,str)
- if n>=first and e==0 then
- e=#str
- end
- return sub(str,b,e)
- else
- b,e,n,last=1,0,0,stop
- lpegmatch(pattern_zero,str)
- if e==0 then
- e=#str
- end
- return sub(str,b,e)
- end
- end
-end
-function utf.remapper(mapping,option,action)
- local variant=type(mapping)
- if variant=="table" then
- action=action or mapping
- if option=="dynamic" then
- local pattern=false
- table.setmetatablenewindex(mapping,function(t,k,v) rawset(t,k,v) pattern=false end)
- return function(str)
- if not str or str=="" then
- return ""
- else
- if not pattern then
- pattern=Cs((tabletopattern(mapping)/action+p_utf8character)^0)
- end
- return lpegmatch(pattern,str)
- end
- end
- elseif option=="pattern" then
- return Cs((tabletopattern(mapping)/action+p_utf8character)^0)
- else
- local pattern=Cs((tabletopattern(mapping)/action+p_utf8character)^0)
- return function(str)
- if not str or str=="" then
- return ""
- else
- return lpegmatch(pattern,str)
- end
- end,pattern
- end
- elseif variant=="function" then
- if option=="pattern" then
- return Cs((p_utf8character/mapping+p_utf8character)^0)
- else
- local pattern=Cs((p_utf8character/mapping+p_utf8character)^0)
- return function(str)
- if not str or str=="" then
- return ""
- else
- return lpegmatch(pattern,str)
- end
- end,pattern
- end
- else
- return function(str)
- return str or ""
- end
- end
-end
-function utf.replacer(t)
- local r=replacer(t,false,false,true)
- return function(str)
- return lpegmatch(r,str)
- end
-end
-function utf.subtituter(t)
- local f=finder (t)
- local r=replacer(t,false,false,true)
- return function(str)
- local i=lpegmatch(f,str)
- if not i then
- return str
- elseif i>#str then
- return str
- else
- return lpegmatch(r,str)
- end
- end
-end
-local utflinesplitter=p_utfbom^-1*lpeg.tsplitat(p_newline)
-local utfcharsplitter_ows=p_utfbom^-1*Ct(C(p_utf8character)^0)
-local utfcharsplitter_iws=p_utfbom^-1*Ct((p_whitespace^1+C(p_utf8character))^0)
-local utfcharsplitter_raw=Ct(C(p_utf8character)^0)
-patterns.utflinesplitter=utflinesplitter
-function utf.splitlines(str)
- return lpegmatch(utflinesplitter,str or "")
-end
-function utf.split(str,ignorewhitespace)
- if ignorewhitespace then
- return lpegmatch(utfcharsplitter_iws,str or "")
- else
- return lpegmatch(utfcharsplitter_ows,str or "")
- end
-end
-function utf.totable(str)
- return lpegmatch(utfcharsplitter_raw,str)
-end
-function utf.magic(f)
- local str=f:read(4) or ""
- local off=lpegmatch(p_utfoffset,str)
- if off<4 then
- f:seek('set',off)
- end
- return lpegmatch(p_utftype,str)
-end
-local utf16_to_utf8_be,utf16_to_utf8_le
-local utf32_to_utf8_be,utf32_to_utf8_le
-local utf_16_be_getbom=patterns.utfbom_16_be^-1
-local utf_16_le_getbom=patterns.utfbom_16_le^-1
-local utf_32_be_getbom=patterns.utfbom_32_be^-1
-local utf_32_le_getbom=patterns.utfbom_32_le^-1
-local utf_16_be_linesplitter=utf_16_be_getbom*lpeg.tsplitat(patterns.utf_16_be_nl)
-local utf_16_le_linesplitter=utf_16_le_getbom*lpeg.tsplitat(patterns.utf_16_le_nl)
-local utf_32_be_linesplitter=utf_32_be_getbom*lpeg.tsplitat(patterns.utf_32_be_nl)
-local utf_32_le_linesplitter=utf_32_le_getbom*lpeg.tsplitat(patterns.utf_32_le_nl)
-local more=0
-local p_utf16_to_utf8_be=C(1)*C(1)/function(left,right)
- local now=256*byte(left)+byte(right)
- if more>0 then
- now=(more-0xD800)*0x400+(now-0xDC00)+0x10000
- more=0
- return utfchar(now)
- elseif now>=0xD800 and now<=0xDBFF then
- more=now
- return ""
- else
- return utfchar(now)
- end
-end
-local p_utf16_to_utf8_le=C(1)*C(1)/function(right,left)
- local now=256*byte(left)+byte(right)
- if more>0 then
- now=(more-0xD800)*0x400+(now-0xDC00)+0x10000
- more=0
- return utfchar(now)
- elseif now>=0xD800 and now<=0xDBFF then
- more=now
- return ""
- else
- return utfchar(now)
- end
-end
-local p_utf32_to_utf8_be=C(1)*C(1)*C(1)*C(1)/function(a,b,c,d)
- return utfchar(256*256*256*byte(a)+256*256*byte(b)+256*byte(c)+byte(d))
-end
-local p_utf32_to_utf8_le=C(1)*C(1)*C(1)*C(1)/function(a,b,c,d)
- return utfchar(256*256*256*byte(d)+256*256*byte(c)+256*byte(b)+byte(a))
-end
-p_utf16_to_utf8_be=P(true)/function() more=0 end*utf_16_be_getbom*Cs(p_utf16_to_utf8_be^0)
-p_utf16_to_utf8_le=P(true)/function() more=0 end*utf_16_le_getbom*Cs(p_utf16_to_utf8_le^0)
-p_utf32_to_utf8_be=P(true)/function() more=0 end*utf_32_be_getbom*Cs(p_utf32_to_utf8_be^0)
-p_utf32_to_utf8_le=P(true)/function() more=0 end*utf_32_le_getbom*Cs(p_utf32_to_utf8_le^0)
-patterns.utf16_to_utf8_be=p_utf16_to_utf8_be
-patterns.utf16_to_utf8_le=p_utf16_to_utf8_le
-patterns.utf32_to_utf8_be=p_utf32_to_utf8_be
-patterns.utf32_to_utf8_le=p_utf32_to_utf8_le
-utf16_to_utf8_be=function(s)
- if s and s~="" then
- return lpegmatch(p_utf16_to_utf8_be,s)
- else
- return s
- end
-end
-local utf16_to_utf8_be_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_16_be_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf16_to_utf8_be,s)
- end
- end
- return t
-end
-utf16_to_utf8_le=function(s)
- if s and s~="" then
- return lpegmatch(p_utf16_to_utf8_le,s)
- else
- return s
- end
-end
-local utf16_to_utf8_le_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_16_le_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf16_to_utf8_le,s)
- end
- end
- return t
-end
-utf32_to_utf8_be=function(s)
- if s and s~="" then
- return lpegmatch(p_utf32_to_utf8_be,s)
- else
- return s
- end
-end
-local utf32_to_utf8_be_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_32_be_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf32_to_utf8_be,s)
- end
- end
- return t
-end
-utf32_to_utf8_le=function(s)
- if s and s~="" then
- return lpegmatch(p_utf32_to_utf8_le,s)
- else
- return s
- end
-end
-local utf32_to_utf8_le_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_32_le_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf32_to_utf8_le,s)
- end
- end
- return t
-end
-utf.utf16_to_utf8_le_t=utf16_to_utf8_le_t
-utf.utf16_to_utf8_be_t=utf16_to_utf8_be_t
-utf.utf32_to_utf8_le_t=utf32_to_utf8_le_t
-utf.utf32_to_utf8_be_t=utf32_to_utf8_be_t
-utf.utf16_to_utf8_le=utf16_to_utf8_le
-utf.utf16_to_utf8_be=utf16_to_utf8_be
-utf.utf32_to_utf8_le=utf32_to_utf8_le
-utf.utf32_to_utf8_be=utf32_to_utf8_be
-function utf.utf8_to_utf8_t(t)
- return type(t)=="string" and lpegmatch(utflinesplitter,t) or t
-end
-function utf.utf16_to_utf8_t(t,endian)
- return endian and utf16_to_utf8_be_t(t) or utf16_to_utf8_le_t(t) or t
-end
-function utf.utf32_to_utf8_t(t,endian)
- return endian and utf32_to_utf8_be_t(t) or utf32_to_utf8_le_t(t) or t
-end
-if bit32 then
- local rshift=bit32.rshift
- local function little(b)
- if b<0x10000 then
- return char(b%256,rshift(b,8))
- else
- b=b-0x10000
- local b1=rshift(b,10)+0xD800
- local b2=b%1024+0xDC00
- return char(b1%256,rshift(b1,8),b2%256,rshift(b2,8))
- end
- end
- local function big(b)
- if b<0x10000 then
- return char(rshift(b,8),b%256)
- else
- b=b-0x10000
- local b1=rshift(b,10)+0xD800
- local b2=b%1024+0xDC00
- return char(rshift(b1,8),b1%256,rshift(b2,8),b2%256)
- end
- end
- local l_remap=Cs((p_utf8byte/little+P(1)/"")^0)
- local b_remap=Cs((p_utf8byte/big+P(1)/"")^0)
- local function utf8_to_utf16_be(str,nobom)
- if nobom then
- return lpegmatch(b_remap,str)
- else
- return char(254,255)..lpegmatch(b_remap,str)
- end
- end
- local function utf8_to_utf16_le(str,nobom)
- if nobom then
- return lpegmatch(l_remap,str)
- else
- return char(255,254)..lpegmatch(l_remap,str)
- end
- end
- utf.utf8_to_utf16_be=utf8_to_utf16_be
- utf.utf8_to_utf16_le=utf8_to_utf16_le
- function utf.utf8_to_utf16(str,littleendian,nobom)
- if littleendian then
- return utf8_to_utf16_le(str,nobom)
- else
- return utf8_to_utf16_be(str,nobom)
- end
- end
-end
-local pattern=Cs (
- (p_utf8byte/function(unicode ) return format("0x%04X",unicode) end)*(p_utf8byte*Carg(1)/function(unicode,separator) return format("%s0x%04X",separator,unicode) end)^0
-)
-function utf.tocodes(str,separator)
- return lpegmatch(pattern,str,1,separator or " ")
-end
-function utf.ustring(s)
- return format("U+%05X",type(s)=="number" and s or utfbyte(s))
-end
-function utf.xstring(s)
- return format("0x%05X",type(s)=="number" and s or utfbyte(s))
-end
-function utf.toeight(str)
- if not str or str=="" then
- return nil
- end
- local utftype=lpegmatch(p_utfstricttype,str)
- if utftype=="utf-8" then
- return sub(str,4)
- elseif utftype=="utf-16-be" then
- return utf16_to_utf8_be(str)
- elseif utftype=="utf-16-le" then
- return utf16_to_utf8_le(str)
- else
- return str
- end
-end
-do
- local p_nany=p_utf8character/""
- local cache={}
- function utf.count(str,what)
- if type(what)=="string" then
- local p=cache[what]
- if not p then
- p=Cs((P(what)/" "+p_nany)^0)
- cache[p]=p
- end
- return #lpegmatch(p,str)
- else
- return #lpegmatch(Cs((P(what)/" "+p_nany)^0),str)
- end
- end
-end
-if not string.utfvalues then
- local find=string.find
- local dummy=function()
- end
- function string.utfvalues(str)
- local n=#str
- if n==0 then
- return dummy
- elseif n==1 then
- return function() return utfbyte(str) end
- else
- local p=1
- return function()
- local b,e=find(str,".[\128-\191]*",p)
- if b then
- p=e+1
- return utfbyte(sub(str,b,e))
- end
- end
- end
- end
-end
-utf.values=string.utfvalues
-function utf.chrlen(u)
- return
- (u<0x80 and 1) or
- (u<0xE0 and 2) or
- (u<0xF0 and 3) or
- (u<0xF8 and 4) or
- (u<0xFC and 5) or
- (u<0xFE and 6) or 0
-end
-if bit32 then
- local extract=bit32.extract
- local char=string.char
- function utf.toutf32string(n)
- if n<=0xFF then
- return
- char(n).."\000\000\000"
- elseif n<=0xFFFF then
- return
- char(extract(n,0,8))..char(extract(n,8,8)).."\000\000"
- elseif n<=0xFFFFFF then
- return
- char(extract(n,0,8))..char(extract(n,8,8))..char(extract(n,16,8)).."\000"
- else
- return
- char(extract(n,0,8))..char(extract(n,8,8))..char(extract(n,16,8))..char(extract(n,24,8))
- end
- end
-end
-local len=utf.len
-local rep=rep
-function string.utfpadd(s,n)
- if n and n~=0 then
- local l=len(s)
- if n>0 then
- local d=n-l
- if d>0 then
- return rep(c or " ",d)..s
- end
- else
- local d=- n-l
- if d>0 then
- return s..rep(c or " ",d)
- end
- end
- end
- return s
-end
-do
- local utfcharacters=utf.characters or string.utfcharacters
- local utfchar=utf.char or string.utfcharacter
- lpeg.UP=P
- if utfcharacters then
- function lpeg.US(str)
- local p=P(false)
- for uc in utfcharacters(str) do
- p=p+P(uc)
- end
- return p
- end
- else
- function lpeg.US(str)
- local p=P(false)
- local f=function(uc)
- p=p+P(uc)
- end
- lpegmatch((p_utf8char/f)^0,str)
- return p
- end
- end
- local range=p_utf8byte*p_utf8byte+Cc(false)
- function lpeg.UR(str,more)
- local first,last
- if type(str)=="number" then
- first=str
- last=more or first
- else
- first,last=lpegmatch(range,str)
- if not last then
- return P(str)
- end
- end
- if first==last then
- return P(str)
- end
- if not utfchar then
- utfchar=utf.char
- end
- if utfchar and (last-first<8) then
- local p=P(false)
- for i=first,last do
- p=p+P(utfchar(i))
- end
- return p
- else
- local f=function(b)
- return b>=first and b<=last
- end
- return p_utf8byte/f
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-math"] = package.loaded["l-math"] or true
-
--- original size: 2555, stripped down to: 1831
-
-if not modules then modules={} end modules ['l-math']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if not math.ceiling then
- math.ceiling=math.ceil
-end
-if not math.round then
- local floor=math.floor
- function math.round(x) return floor(x+0.5) end
-end
-if not math.div then
- local floor=math.floor
- function math.div(n,m) return floor(n/m) end
-end
-if not math.mod then
- function math.mod(n,m) return n%m end
-end
-if not math.sind then
- local sin,cos,tan=math.sin,math.cos,math.tan
- local pipi=2*math.pi/360
- function math.sind(d) return sin(d*pipi) end
- function math.cosd(d) return cos(d*pipi) end
- function math.tand(d) return tan(d*pipi) end
-end
-if not math.odd then
- function math.odd (n) return n%2~=0 end
- function math.even(n) return n%2==0 end
-end
-if not math.cosh then
- local exp=math.exp
- function math.cosh(x)
- local xx=exp(x)
- return (xx+1/xx)/2
- end
- function math.sinh(x)
- local xx=exp(x)
- return (xx-1/xx)/2
- end
- function math.tanh(x)
- local xx=exp(x)
- return (xx-1/xx)/(xx+1/xx)
- end
-end
-if not math.pow then
- function math.pow(x,y)
- return x^y
- end
-end
-if not math.atan2 then
- math.atan2=math.atan
-end
-if not math.ldexp then
- function math.ldexp(x,e)
- return x*2.0^e
- end
-end
-if not math.log10 then
- local log=math.log
- function math.log10(x)
- return log(x,10)
- end
-end
-if not math.type then
- function math.type()
- return "float"
- end
-end
-if not math.tointeger then
- math.mininteger=-0x4FFFFFFFFFFF
- math.maxinteger=0x4FFFFFFFFFFF
- local floor=math.floor
- function math.tointeger(n)
- local f=floor(n)
- return f==n and f or nil
- end
-end
-if not math.ult then
- local floor=math.floor
- function math.tointeger(m,n)
- return floor(m)<floor(n)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-str"] = package.loaded["util-str"] or true
-
--- original size: 45129, stripped down to: 23525
-
-if not modules then modules={} end modules ['util-str']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities=utilities or {}
-utilities.strings=utilities.strings or {}
-local strings=utilities.strings
-local format,gsub,rep,sub,find=string.format,string.gsub,string.rep,string.sub,string.find
-local load,dump=load,string.dump
-local tonumber,type,tostring,next,setmetatable=tonumber,type,tostring,next,setmetatable
-local unpack,concat=table.unpack,table.concat
-local P,V,C,S,R,Ct,Cs,Cp,Carg,Cc=lpeg.P,lpeg.V,lpeg.C,lpeg.S,lpeg.R,lpeg.Ct,lpeg.Cs,lpeg.Cp,lpeg.Carg,lpeg.Cc
-local patterns,lpegmatch=lpeg.patterns,lpeg.match
-local utfchar,utfbyte,utflen=utf.char,utf.byte,utf.len
-local loadstripped=function(str,shortcuts)
- if shortcuts then
- return load(dump(load(str),true),nil,nil,shortcuts)
- else
- return load(dump(load(str),true))
- end
-end
-if not number then number={} end
-local stripzero=patterns.stripzero
-local stripzeros=patterns.stripzeros
-local newline=patterns.newline
-local endofstring=patterns.endofstring
-local anything=patterns.anything
-local whitespace=patterns.whitespace
-local space=patterns.space
-local spacer=patterns.spacer
-local spaceortab=patterns.spaceortab
-local digit=patterns.digit
-local sign=patterns.sign
-local period=patterns.period
-local ptf=1/65536
-local bpf=(7200/7227)/65536
-local function points(n)
- if n==0 then
- return "0pt"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0pt"
- end
- n=n*ptf
- if n%1==0 then
- return format("%ipt",n)
- else
- return lpegmatch(stripzeros,format("%.5fpt",n))
- end
-end
-local function nupoints(n)
- if n==0 then
- return "0"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0"
- end
- n=n*ptf
- if n%1==0 then
- return format("%i",n)
- else
- return format("%.5f",n)
- end
-end
-local function basepoints(n)
- if n==0 then
- return "0bp"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0bp"
- end
- n=n*bpf
- if n%1==0 then
- return format("%ibp",n)
- else
- return lpegmatch(stripzeros,format("%.5fbp",n))
- end
-end
-local function nubasepoints(n)
- if n==0 then
- return "0"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0"
- end
- n=n*bpf
- if n%1==0 then
- return format("%i",n)
- else
- return format("%.5f",n)
- end
-end
-number.points=points
-number.nupoints=nupoints
-number.basepoints=basepoints
-number.nubasepoints=nubasepoints
-local rubish=spaceortab^0*newline
-local anyrubish=spaceortab+newline
-local stripped=(spaceortab^1/"")*newline
-local leading=rubish^0/""
-local trailing=(anyrubish^1*endofstring)/""
-local redundant=rubish^3/"\n"
-local pattern=Cs(leading*(trailing+redundant+stripped+anything)^0)
-function strings.collapsecrlf(str)
- return lpegmatch(pattern,str)
-end
-local repeaters={}
-function strings.newrepeater(str,offset)
- offset=offset or 0
- local s=repeaters[str]
- if not s then
- s={}
- repeaters[str]=s
- end
- local t=s[offset]
- if t then
- return t
- end
- t={}
- setmetatable(t,{ __index=function(t,k)
- if not k then
- return ""
- end
- local n=k+offset
- local s=n>0 and rep(str,n) or ""
- t[k]=s
- return s
- end })
- s[offset]=t
- return t
-end
-local extra,tab,start=0,0,4,0
-local nspaces=strings.newrepeater(" ")
-string.nspaces=nspaces
-local pattern=Carg(1)/function(t)
- extra,tab,start=0,t or 7,1
- end*Cs((
- Cp()*patterns.tab/function(position)
- local current=(position-start+1)+extra
- local spaces=tab-(current-1)%tab
- if spaces>0 then
- extra=extra+spaces-1
- return nspaces[spaces]
- else
- return ""
- end
- end+newline*Cp()/function(position)
- extra,start=0,position
- end+anything
- )^1)
-function strings.tabtospace(str,tab)
- return lpegmatch(pattern,str,1,tab or 7)
-end
-function string.utfpadding(s,n)
- if not n or n==0 then
- return ""
- end
- local l=utflen(s)
- if n>0 then
- return nspaces[n-l]
- else
- return nspaces[-n-l]
- end
-end
-local optionalspace=spacer^0
-local nospace=optionalspace/""
-local endofline=nospace*newline
-local stripend=(whitespace^1*endofstring)/""
-local normalline=(nospace*((1-optionalspace*(newline+endofstring))^1)*nospace)
-local stripempty=endofline^1/""
-local normalempty=endofline^1
-local singleempty=endofline*(endofline^0/"")
-local doubleempty=endofline*endofline^-1*(endofline^0/"")
-local stripstart=stripempty^0
-local intospace=whitespace^1/" "
-local noleading=whitespace^1/""
-local notrailing=noleading*endofstring
-local p_prune_normal=Cs (stripstart*(stripend+normalline+normalempty )^0 )
-local p_prune_collapse=Cs (stripstart*(stripend+normalline+doubleempty )^0 )
-local p_prune_noempty=Cs (stripstart*(stripend+normalline+singleempty )^0 )
-local p_prune_intospace=Cs (noleading*(notrailing+intospace+1 )^0 )
-local p_retain_normal=Cs ((normalline+normalempty )^0 )
-local p_retain_collapse=Cs ((normalline+doubleempty )^0 )
-local p_retain_noempty=Cs ((normalline+singleempty )^0 )
-local striplinepatterns={
- ["prune"]=p_prune_normal,
- ["prune and collapse"]=p_prune_collapse,
- ["prune and no empty"]=p_prune_noempty,
- ["prune and to space"]=p_prune_intospace,
- ["retain"]=p_retain_normal,
- ["retain and collapse"]=p_retain_collapse,
- ["retain and no empty"]=p_retain_noempty,
- ["collapse"]=patterns.collapser,
-}
-setmetatable(striplinepatterns,{ __index=function(t,k) return p_prune_collapse end })
-strings.striplinepatterns=striplinepatterns
-function strings.striplines(str,how)
- return str and lpegmatch(striplinepatterns[how],str) or str
-end
-function strings.collapse(str)
- return str and lpegmatch(p_prune_intospace,str) or str
-end
-strings.striplong=strings.striplines
-function strings.nice(str)
- str=gsub(str,"[:%-+_]+"," ")
- return str
-end
-local n=0
-local sequenced=table.sequenced
-function string.autodouble(s,sep)
- if s==nil then
- return '""'
- end
- local t=type(s)
- if t=="number" then
- return tostring(s)
- end
- if t=="table" then
- return ('"'..sequenced(s,sep or ",")..'"')
- end
- return ('"'..tostring(s)..'"')
-end
-function string.autosingle(s,sep)
- if s==nil then
- return "''"
- end
- local t=type(s)
- if t=="number" then
- return tostring(s)
- end
- if t=="table" then
- return ("'"..sequenced(s,sep or ",").."'")
- end
- return ("'"..tostring(s).."'")
-end
-local tracedchars={ [0]=
- "[null]","[soh]","[stx]","[etx]","[eot]","[enq]","[ack]","[bel]",
- "[bs]","[ht]","[lf]","[vt]","[ff]","[cr]","[so]","[si]",
- "[dle]","[dc1]","[dc2]","[dc3]","[dc4]","[nak]","[syn]","[etb]",
- "[can]","[em]","[sub]","[esc]","[fs]","[gs]","[rs]","[us]",
- "[space]",
-}
-string.tracedchars=tracedchars
-strings.tracers=tracedchars
-function string.tracedchar(b)
- if type(b)=="number" then
- return tracedchars[b] or (utfchar(b).." (U+"..format("%05X",b)..")")
- else
- local c=utfbyte(b)
- return tracedchars[c] or (b.." (U+"..(c and format("%05X",c) or "?????")..")")
- end
-end
-function number.signed(i)
- if i>0 then
- return "+",i
- else
- return "-",-i
- end
-end
-local two=digit*digit
-local three=two*digit
-local prefix=(Carg(1)*three)^1
-local splitter=Cs (
- (((1-(three^1*period))^1+C(three))*prefix+C((1-period)^1))*(anything/""*Carg(2))*C(2)
-)
-local splitter3=Cs (
- three*prefix*endofstring+two*prefix*endofstring+digit*prefix*endofstring+three+two+digit
-)
-patterns.formattednumber=splitter
-function number.formatted(n,sep1,sep2)
- if sep1==false then
- if type(n)=="number" then
- n=tostring(n)
- end
- return lpegmatch(splitter3,n,1,sep2 or ".")
- else
- if type(n)=="number" then
- n=format("%0.2f",n)
- end
- if sep1==true then
- return lpegmatch(splitter,n,1,".",",")
- elseif sep1=="." then
- return lpegmatch(splitter,n,1,sep1,sep2 or ",")
- elseif sep1=="," then
- return lpegmatch(splitter,n,1,sep1,sep2 or ".")
- else
- return lpegmatch(splitter,n,1,sep1 or ",",sep2 or ".")
- end
- end
-end
-local p=Cs(
- P("-")^0*(P("0")^1/"")^0*(1-period)^0*(period*P("0")^1*endofstring/""+period^0)*P(1-P("0")^1*endofstring)^0
- )
-function number.compactfloat(n,fmt)
- if n==0 then
- return "0"
- elseif n==1 then
- return "1"
- end
- n=lpegmatch(p,format(fmt or "%0.3f",n))
- if n=="." or n=="" or n=="-" then
- return "0"
- end
- return n
-end
-local zero=P("0")^1/""
-local plus=P("+")/""
-local minus=P("-")
-local separator=period
-local trailing=zero^1*#S("eE")
-local exponent=(S("eE")*(plus+Cs((minus*zero^0*endofstring)/"")+minus)*zero^0*(endofstring*Cc("0")+anything^1))
-local pattern_a=Cs(minus^0*digit^1*(separator/""*trailing+separator*(trailing+digit)^0)*exponent)
-local pattern_b=Cs((exponent+anything)^0)
-function number.sparseexponent(f,n)
- if not n then
- n=f
- f="%e"
- end
- local tn=type(n)
- if tn=="string" then
- local m=tonumber(n)
- if m then
- return lpegmatch((f=="%e" or f=="%E") and pattern_a or pattern_b,format(f,m))
- end
- elseif tn=="number" then
- return lpegmatch((f=="%e" or f=="%E") and pattern_a or pattern_b,format(f,n))
- end
- return tostring(n)
-end
-local hf={}
-local hs={}
-setmetatable(hf,{ __index=function(t,k)
- local v="%."..k.."f"
- t[k]=v
- return v
-end } )
-setmetatable(hs,{ __index=function(t,k)
- local v="%"..k.."s"
- t[k]=v
- return v
-end } )
-function number.formattedfloat(n,b,a)
- local s=format(hf[a],n)
- local l=(b or 0)+(a or 0)+1
- if #s<l then
- return format(hs[l],s)
- else
- return s
- end
-end
-local template=[[
-%s
-%s
-return function(%s) return %s end
-]]
-local pattern=Cs(Cc('"')*(
- (1-S('"\\\n\r'))^1+P('"')/'\\"'+P('\\')/'\\\\'+P('\n')/'\\n'+P('\r')/'\\r'
-)^0*Cc('"'))
-patterns.escapedquotes=pattern
-function string.escapedquotes(s)
- return lpegmatch(pattern,s)
-end
-local preamble=""
-local environment={
- global=global or _G,
- lpeg=lpeg,
- type=type,
- tostring=tostring,
- tonumber=tonumber,
- format=string.format,
- concat=table.concat,
- signed=number.signed,
- points=number.points,
- nupoints=number.nupoints,
- basepoints=number.basepoints,
- nubasepoints=number.nubasepoints,
- utfchar=utf.char,
- utfbyte=utf.byte,
- lpegmatch=lpeg.match,
- nspaces=string.nspaces,
- utfpadding=string.utfpadding,
- tracedchar=string.tracedchar,
- autosingle=string.autosingle,
- autodouble=string.autodouble,
- sequenced=table.sequenced,
- formattednumber=number.formatted,
- sparseexponent=number.sparseexponent,
- formattedfloat=number.formattedfloat,
- stripzero=patterns.stripzero,
- stripzeros=patterns.stripzeros,
- escapedquotes=string.escapedquotes,
- FORMAT=string.f6,
-}
-local arguments={ "a1" }
-setmetatable(arguments,{ __index=function(t,k)
- local v=t[k-1]..",a"..k
- t[k]=v
- return v
- end
-})
-local prefix_any=C((sign+space+period+digit)^0)
-local prefix_sub=(C((sign+digit)^0)+Cc(0))*period*(C((sign+digit)^0)+Cc(0))
-local prefix_tab=P("{")*C((1-P("}"))^0)*P("}")+C((1-R("az","AZ","09","%%"))^0)
-local format_s=function(f)
- n=n+1
- if f and f~="" then
- return format("format('%%%ss',a%s)",f,n)
- else
- return format("(a%s or '')",n)
- end
-end
-local format_S=function(f)
- n=n+1
- if f and f~="" then
- return format("format('%%%ss',tostring(a%s))",f,n)
- else
- return format("tostring(a%s)",n)
- end
-end
-local format_right=function(f)
- n=n+1
- f=tonumber(f)
- if not f or f==0 then
- return format("(a%s or '')",n)
- elseif f>0 then
- return format("utfpadding(a%s,%i)..a%s",n,f,n)
- else
- return format("a%s..utfpadding(a%s,%i)",n,n,f)
- end
-end
-local format_left=function(f)
- n=n+1
- f=tonumber(f)
- if not f or f==0 then
- return format("(a%s or '')",n)
- end
- if f<0 then
- return format("utfpadding(a%s,%i)..a%s",n,-f,n)
- else
- return format("a%s..utfpadding(a%s,%i)",n,n,-f)
- end
-end
-local format_q=JITSUPPORTED and function()
- n=n+1
- return format("(a%s ~= nil and format('%%q',tostring(a%s)) or '')",n,n)
-end or function()
- n=n+1
- return format("(a%s ~= nil and format('%%q',a%s) or '')",n,n)
-end
-local format_Q=function()
- n=n+1
- return format("escapedquotes(tostring(a%s))",n)
-end
-local format_i=function(f)
- n=n+1
- if f and f~="" then
- return format("format('%%%si',a%s)",f,n)
- else
- return format("format('%%i',a%s)",n)
- end
-end
-local format_d=format_i
-local format_I=function(f)
- n=n+1
- return format("format('%%s%%%si',signed(a%s))",f,n)
-end
-local format_f=function(f)
- n=n+1
- return format("format('%%%sf',a%s)",f,n)
-end
-local format_F=function(f)
- n=n+1
- if not f or f=="" then
- return format("(((a%s > -0.0000000005 and a%s < 0.0000000005) and '0') or format((a%s %% 1 == 0) and '%%i' or '%%.9f',a%s))",n,n,n,n)
- else
- return format("format((a%s %% 1 == 0) and '%%i' or '%%%sf',a%s)",n,f,n)
- end
-end
-local format_k=function(b,a)
- n=n+1
- return format("formattedfloat(a%s,%s,%s)",n,b or 0,a or 0)
-end
-local format_g=function(f)
- n=n+1
- return format("format('%%%sg',a%s)",f,n)
-end
-local format_G=function(f)
- n=n+1
- return format("format('%%%sG',a%s)",f,n)
-end
-local format_e=function(f)
- n=n+1
- return format("format('%%%se',a%s)",f,n)
-end
-local format_E=function(f)
- n=n+1
- return format("format('%%%sE',a%s)",f,n)
-end
-local format_j=function(f)
- n=n+1
- return format("sparseexponent('%%%se',a%s)",f,n)
-end
-local format_J=function(f)
- n=n+1
- return format("sparseexponent('%%%sE',a%s)",f,n)
-end
-local format_x=function(f)
- n=n+1
- return format("format('%%%sx',a%s)",f,n)
-end
-local format_X=function(f)
- n=n+1
- return format("format('%%%sX',a%s)",f,n)
-end
-local format_o=function(f)
- n=n+1
- return format("format('%%%so',a%s)",f,n)
-end
-local format_c=function()
- n=n+1
- return format("utfchar(a%s)",n)
-end
-local format_C=function()
- n=n+1
- return format("tracedchar(a%s)",n)
-end
-local format_r=function(f)
- n=n+1
- return format("format('%%%s.0f',a%s)",f,n)
-end
-local format_h=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('0x%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_H=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('0x%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_u=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('u+%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_U=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('U+%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_p=function()
- n=n+1
- return format("points(a%s)",n)
-end
-local format_P=function()
- n=n+1
- return format("nupoints(a%s)",n)
-end
-local format_b=function()
- n=n+1
- return format("basepoints(a%s)",n)
-end
-local format_B=function()
- n=n+1
- return format("nubasepoints(a%s)",n)
-end
-local format_t=function(f)
- n=n+1
- if f and f~="" then
- return format("concat(a%s,%q)",n,f)
- else
- return format("concat(a%s)",n)
- end
-end
-local format_T=function(f)
- n=n+1
- if f and f~="" then
- return format("sequenced(a%s,%q)",n,f)
- else
- return format("sequenced(a%s)",n)
- end
-end
-local format_l=function()
- n=n+1
- return format("(a%s and 'true' or 'false')",n)
-end
-local format_L=function()
- n=n+1
- return format("(a%s and 'TRUE' or 'FALSE')",n)
-end
-local format_n=function()
- n=n+1
- return format("((a%s %% 1 == 0) and format('%%i',a%s) or tostring(a%s))",n,n,n)
-end
-local format_N if environment.FORMAT then
- format_N=function(f)
- n=n+1
- if not f or f=="" then
- return format("FORMAT(a%s,'%%.9f')",n)
- elseif f==".6" or f=="0.6" then
- return format("FORMAT(a%s)",n)
- else
- return format("FORMAT(a%s,'%%%sf')",n,f)
- end
- end
-else
- format_N=function(f)
- n=n+1
- if not f or f=="" then
- f=".9"
- end
- return format("(((a%s %% 1 == 0) and format('%%i',a%s)) or lpegmatch(stripzero,format('%%%sf',a%s)))",n,n,f,n)
- end
-end
-local format_a=function(f)
- n=n+1
- if f and f~="" then
- return format("autosingle(a%s,%q)",n,f)
- else
- return format("autosingle(a%s)",n)
- end
-end
-local format_A=function(f)
- n=n+1
- if f and f~="" then
- return format("autodouble(a%s,%q)",n,f)
- else
- return format("autodouble(a%s)",n)
- end
-end
-local format_w=function(f)
- n=n+1
- f=tonumber(f)
- if f then
- return format("nspaces[%s+a%s]",f,n)
- else
- return format("nspaces[a%s]",n)
- end
-end
-local format_W=function(f)
- return format("nspaces[%s]",tonumber(f) or 0)
-end
-local format_m=function(f)
- n=n+1
- if not f or f=="" then
- f=","
- end
- if f=="0" then
- return format([[formattednumber(a%s,false)]],n)
- else
- return format([[formattednumber(a%s,%q,".")]],n,f)
- end
-end
-local format_M=function(f)
- n=n+1
- if not f or f=="" then
- f="."
- end
- if f=="0" then
- return format([[formattednumber(a%s,false)]],n)
- else
- return format([[formattednumber(a%s,%q,",")]],n,f)
- end
-end
-local format_z=function(f)
- n=n+(tonumber(f) or 1)
- return "''"
-end
-local format_rest=function(s)
- return format("%q",s)
-end
-local format_extension=function(extensions,f,name)
- local extension=extensions[name] or "tostring(%s)"
- local f=tonumber(f) or 1
- local w=find(extension,"%.%.%.")
- if f==0 then
- if w then
- extension=gsub(extension,"%.%.%.","")
- end
- return extension
- elseif f==1 then
- if w then
- extension=gsub(extension,"%.%.%.","%%s")
- end
- n=n+1
- local a="a"..n
- return format(extension,a,a)
- elseif f<0 then
- if w then
- extension=gsub(extension,"%.%.%.","")
- return extension
- else
- local a="a"..(n+f+1)
- return format(extension,a,a)
- end
- else
- if w then
- extension=gsub(extension,"%.%.%.",rep("%%s,",f-1).."%%s")
- end
- local t={}
- for i=1,f do
- n=n+1
- t[i]="a"..n
- end
- return format(extension,unpack(t))
- end
-end
-local builder=Cs { "start",
- start=(
- (
- P("%")/""*(
- V("!")
-+V("s")+V("q")+V("i")+V("d")+V("f")+V("F")+V("g")+V("G")+V("e")+V("E")+V("x")+V("X")+V("o")
-+V("c")+V("C")+V("S")
-+V("Q")
-+V("n")
-+V("N")
-+V("k")
-+V("r")+V("h")+V("H")+V("u")+V("U")+V("p")+V("P")+V("b")+V("B")+V("t")+V("T")+V("l")+V("L")+V("I")+V("w")
-+V("W")
-+V("a")
-+V("A")
-+V("j")+V("J")
-+V("m")+V("M")
-+V("z")
-+V(">")
-+V("<")
- )+V("*")
- )*(endofstring+Carg(1))
- )^0,
- ["s"]=(prefix_any*P("s"))/format_s,
- ["q"]=(prefix_any*P("q"))/format_q,
- ["i"]=(prefix_any*P("i"))/format_i,
- ["d"]=(prefix_any*P("d"))/format_d,
- ["f"]=(prefix_any*P("f"))/format_f,
- ["F"]=(prefix_any*P("F"))/format_F,
- ["g"]=(prefix_any*P("g"))/format_g,
- ["G"]=(prefix_any*P("G"))/format_G,
- ["e"]=(prefix_any*P("e"))/format_e,
- ["E"]=(prefix_any*P("E"))/format_E,
- ["x"]=(prefix_any*P("x"))/format_x,
- ["X"]=(prefix_any*P("X"))/format_X,
- ["o"]=(prefix_any*P("o"))/format_o,
- ["S"]=(prefix_any*P("S"))/format_S,
- ["Q"]=(prefix_any*P("Q"))/format_Q,
- ["n"]=(prefix_any*P("n"))/format_n,
- ["N"]=(prefix_any*P("N"))/format_N,
- ["k"]=(prefix_sub*P("k"))/format_k,
- ["c"]=(prefix_any*P("c"))/format_c,
- ["C"]=(prefix_any*P("C"))/format_C,
- ["r"]=(prefix_any*P("r"))/format_r,
- ["h"]=(prefix_any*P("h"))/format_h,
- ["H"]=(prefix_any*P("H"))/format_H,
- ["u"]=(prefix_any*P("u"))/format_u,
- ["U"]=(prefix_any*P("U"))/format_U,
- ["p"]=(prefix_any*P("p"))/format_p,
- ["P"]=(prefix_any*P("P"))/format_P,
- ["b"]=(prefix_any*P("b"))/format_b,
- ["B"]=(prefix_any*P("B"))/format_B,
- ["t"]=(prefix_tab*P("t"))/format_t,
- ["T"]=(prefix_tab*P("T"))/format_T,
- ["l"]=(prefix_any*P("l"))/format_l,
- ["L"]=(prefix_any*P("L"))/format_L,
- ["I"]=(prefix_any*P("I"))/format_I,
- ["w"]=(prefix_any*P("w"))/format_w,
- ["W"]=(prefix_any*P("W"))/format_W,
- ["j"]=(prefix_any*P("j"))/format_j,
- ["J"]=(prefix_any*P("J"))/format_J,
- ["m"]=(prefix_any*P("m"))/format_m,
- ["M"]=(prefix_any*P("M"))/format_M,
- ["z"]=(prefix_any*P("z"))/format_z,
- ["a"]=(prefix_any*P("a"))/format_a,
- ["A"]=(prefix_any*P("A"))/format_A,
- ["<"]=(prefix_any*P("<"))/format_left,
- [">"]=(prefix_any*P(">"))/format_right,
- ["*"]=Cs(((1-P("%"))^1+P("%%")/"%%")^1)/format_rest,
- ["?"]=Cs(((1-P("%"))^1 )^1)/format_rest,
- ["!"]=Carg(2)*prefix_any*P("!")*C((1-P("!"))^1)*P("!")/format_extension,
-}
-local xx=setmetatable({},{ __index=function(t,k) local v=format("%02x",k) t[k]=v return v end })
-local XX=setmetatable({},{ __index=function(t,k) local v=format("%02X",k) t[k]=v return v end })
-local preset={
- ["%02x"]=function(n) return xx[n] end,
- ["%02X"]=function(n) return XX[n] end,
-}
-local direct=P("%")*(sign+space+period+digit)^0*S("sqidfgGeExXo")*endofstring/[[local format = string.format return function(str) return format("%0",str) end]]
-local function make(t,str)
- local f=preset[str]
- if f then
- return f
- end
- local p=lpegmatch(direct,str)
- if p then
- f=loadstripped(p)()
- else
- n=0
- p=lpegmatch(builder,str,1,t._connector_,t._extensions_)
- if n>0 then
- p=format(template,preamble,t._preamble_,arguments[n],p)
- f=loadstripped(p,t._environment_)()
- else
- f=function() return str end
- end
- end
- t[str]=f
- return f
-end
-local function use(t,fmt,...)
- return t[fmt](...)
-end
-strings.formatters={}
-function strings.formatters.new(noconcat)
- local e={}
- for k,v in next,environment do
- e[k]=v
- end
- local t={
- _type_="formatter",
- _connector_=noconcat and "," or "..",
- _extensions_={},
- _preamble_="",
- _environment_=e,
- }
- setmetatable(t,{ __index=make,__call=use })
- return t
-end
-local formatters=strings.formatters.new()
-string.formatters=formatters
-string.formatter=function(str,...) return formatters[str](...) end
-local function add(t,name,template,preamble)
- if type(t)=="table" and t._type_=="formatter" then
- t._extensions_[name]=template or "%s"
- if type(preamble)=="string" then
- t._preamble_=preamble.."\n"..t._preamble_
- elseif type(preamble)=="table" then
- for k,v in next,preamble do
- t._environment_[k]=v
- end
- end
- end
-end
-strings.formatters.add=add
-patterns.xmlescape=Cs((P("<")/"&lt;"+P(">")/"&gt;"+P("&")/"&amp;"+P('"')/"&quot;"+anything)^0)
-patterns.texescape=Cs((C(S("#$%\\{}"))/"\\%1"+anything)^0)
-patterns.luaescape=Cs(((1-S('"\n'))^1+P('"')/'\\"'+P('\n')/'\\n"')^0)
-patterns.luaquoted=Cs(Cc('"')*((1-S('"\n'))^1+P('"')/'\\"'+P('\n')/'\\n"')^0*Cc('"'))
-add(formatters,"xml",[[lpegmatch(xmlescape,%s)]],{ xmlescape=patterns.xmlescape })
-add(formatters,"tex",[[lpegmatch(texescape,%s)]],{ texescape=patterns.texescape })
-add(formatters,"lua",[[lpegmatch(luaescape,%s)]],{ luaescape=patterns.luaescape })
-local dquote=patterns.dquote
-local equote=patterns.escaped+dquote/'\\"'+1
-local cquote=Cc('"')
-local pattern=Cs(dquote*(equote-P(-2))^0*dquote)
-+Cs(cquote*(equote-space)^0*space*equote^0*cquote)
-function string.optionalquoted(str)
- return lpegmatch(pattern,str) or str
-end
-local pattern=Cs((newline/(os.newline or "\r")+1)^0)
-function string.replacenewlines(str)
- return lpegmatch(pattern,str)
-end
-function strings.newcollector()
- local result,r={},0
- return
- function(fmt,str,...)
- r=r+1
- result[r]=str==nil and fmt or formatters[fmt](str,...)
- end,
- function(connector)
- if result then
- local str=concat(result,connector)
- result,r={},0
- return str
- end
- end
-end
-local f_16_16=formatters["%0.5N"]
-function number.to16dot16(n)
- return f_16_16(n/65536.0)
-end
-if not string.explode then
- local tsplitat=lpeg.tsplitat
- local p_utf=patterns.utf8character
- local p_check=C(p_utf)*(P("+")*Cc(true))^0
- local p_split=Ct(C(p_utf)^0)
- local p_space=Ct((C(1-P(" ")^1)+P(" ")^1)^0)
- function string.explode(str,symbol)
- if symbol=="" then
- return lpegmatch(p_split,str)
- elseif symbol then
- local a,b=lpegmatch(p_check,symbol)
- if b then
- return lpegmatch(tsplitat(P(a)^1),str)
- else
- return lpegmatch(tsplitat(a),str)
- end
- else
- return lpegmatch(p_space,str)
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-tab"] = package.loaded["util-tab"] or true
-
--- original size: 32815, stripped down to: 18257
-
-if not modules then modules={} end modules ['util-tab']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities=utilities or {}
-utilities.tables=utilities.tables or {}
-local tables=utilities.tables
-local format,gmatch,gsub,sub=string.format,string.gmatch,string.gsub,string.sub
-local concat,insert,remove,sort=table.concat,table.insert,table.remove,table.sort
-local setmetatable,getmetatable,tonumber,tostring,rawget=setmetatable,getmetatable,tonumber,tostring,rawget
-local type,next,rawset,tonumber,tostring,load,select=type,next,rawset,tonumber,tostring,load,select
-local lpegmatch,P,Cs,Cc=lpeg.match,lpeg.P,lpeg.Cs,lpeg.Cc
-local sortedkeys,sortedpairs=table.sortedkeys,table.sortedpairs
-local formatters=string.formatters
-local utftoeight=utf.toeight
-local splitter=lpeg.tsplitat(".")
-function utilities.tables.definetable(target,nofirst,nolast)
- local composed=nil
- local t={}
- local snippets=lpegmatch(splitter,target)
- for i=1,#snippets-(nolast and 1 or 0) do
- local name=snippets[i]
- if composed then
- composed=composed.."."..name
- t[#t+1]=formatters["if not %s then %s = { } end"](composed,composed)
- else
- composed=name
- if not nofirst then
- t[#t+1]=formatters["%s = %s or { }"](composed,composed)
- end
- end
- end
- if composed then
- if nolast then
- composed=composed.."."..snippets[#snippets]
- end
- return concat(t,"\n"),composed
- else
- return "",target
- end
-end
-function tables.definedtable(...)
- local t=_G
- for i=1,select("#",...) do
- local li=select(i,...)
- local tl=t[li]
- if not tl then
- tl={}
- t[li]=tl
- end
- t=tl
- end
- return t
-end
-function tables.accesstable(target,root)
- local t=root or _G
- for name in gmatch(target,"([^%.]+)") do
- t=t[name]
- if not t then
- return
- end
- end
- return t
-end
-function tables.migratetable(target,v,root)
- local t=root or _G
- local names=lpegmatch(splitter,target)
- for i=1,#names-1 do
- local name=names[i]
- t[name]=t[name] or {}
- t=t[name]
- if not t then
- return
- end
- end
- t[names[#names]]=v
-end
-function tables.removevalue(t,value)
- if value then
- for i=1,#t do
- if t[i]==value then
- remove(t,i)
- end
- end
- end
-end
-function tables.replacevalue(t,oldvalue,newvalue)
- if oldvalue and newvalue then
- for i=1,#t do
- if t[i]==oldvalue then
- t[i]=newvalue
- end
- end
- end
-end
-function tables.insertbeforevalue(t,value,extra)
- for i=1,#t do
- if t[i]==extra then
- remove(t,i)
- end
- end
- for i=1,#t do
- if t[i]==value then
- insert(t,i,extra)
- return
- end
- end
- insert(t,1,extra)
-end
-function tables.insertaftervalue(t,value,extra)
- for i=1,#t do
- if t[i]==extra then
- remove(t,i)
- end
- end
- for i=1,#t do
- if t[i]==value then
- insert(t,i+1,extra)
- return
- end
- end
- insert(t,#t+1,extra)
-end
-local escape=Cs(Cc('"')*((P('"')/'""'+P(1))^0)*Cc('"'))
-function table.tocsv(t,specification)
- if t and #t>0 then
- local result={}
- local r={}
- specification=specification or {}
- local fields=specification.fields
- if type(fields)~="string" then
- fields=sortedkeys(t[1])
- end
- local separator=specification.separator or ","
- local noffields=#fields
- if specification.preamble==true then
- for f=1,noffields do
- r[f]=lpegmatch(escape,tostring(fields[f]))
- end
- result[1]=concat(r,separator)
- end
- for i=1,#t do
- local ti=t[i]
- for f=1,noffields do
- local field=ti[fields[f]]
- if type(field)=="string" then
- r[f]=lpegmatch(escape,field)
- else
- r[f]=tostring(field)
- end
- end
- result[i+1]=concat(r,separator)
- end
- return concat(result,"\n")
- else
- return ""
- end
-end
-local nspaces=utilities.strings.newrepeater(" ")
-local function toxml(t,d,result,step)
- local r=#result
- for k,v in sortedpairs(t) do
- local s=nspaces[d]
- local tk=type(k)
- local tv=type(v)
- if tv=="table" then
- if tk=="number" then
- r=r+1 result[r]=formatters["%s<entry n='%s'>"](s,k)
- toxml(v,d+step,result,step)
- r=r+1 result[r]=formatters["%s</entry>"](s,k)
- else
- r=r+1 result[r]=formatters["%s<%s>"](s,k)
- toxml(v,d+step,result,step)
- r=r+1 result[r]=formatters["%s</%s>"](s,k)
- end
- elseif tv=="string" then
- if tk=="number" then
- r=r+1 result[r]=formatters["%s<entry n='%s'>%!xml!</entry>"](s,k,v,k)
- else
- r=r+1 result[r]=formatters["%s<%s>%!xml!</%s>"](s,k,v,k)
- end
- elseif tk=="number" then
- r=r+1 result[r]=formatters["%s<entry n='%s'>%S</entry>"](s,k,v,k)
- else
- r=r+1 result[r]=formatters["%s<%s>%S</%s>"](s,k,v,k)
- end
- end
-end
-function table.toxml(t,specification)
- specification=specification or {}
- local name=specification.name
- local noroot=name==false
- local result=(specification.nobanner or noroot) and {} or { "<?xml version='1.0' standalone='yes' ?>" }
- local indent=specification.indent or 0
- local spaces=specification.spaces or 1
- if noroot then
- toxml(t,indent,result,spaces)
- else
- toxml({ [name or "data"]=t },indent,result,spaces)
- end
- return concat(result,"\n")
-end
-function tables.encapsulate(core,capsule,protect)
- if type(capsule)~="table" then
- protect=true
- capsule={}
- end
- for key,value in next,core do
- if capsule[key] then
- print(formatters["\ninvalid %s %a in %a"]("inheritance",key,core))
- os.exit()
- else
- capsule[key]=value
- end
- end
- if protect then
- for key,value in next,core do
- core[key]=nil
- end
- setmetatable(core,{
- __index=capsule,
- __newindex=function(t,key,value)
- if capsule[key] then
- print(formatters["\ninvalid %s %a' in %a"]("overload",key,core))
- os.exit()
- else
- rawset(t,key,value)
- end
- end
- } )
- end
-end
-if JITSUPPORTED then
- local f_hashed_string=formatters["[%Q]=%Q,"]
- local f_hashed_number=formatters["[%Q]=%s,"]
- local f_hashed_boolean=formatters["[%Q]=%l,"]
- local f_hashed_table=formatters["[%Q]="]
- local f_indexed_string=formatters["[%s]=%Q,"]
- local f_indexed_number=formatters["[%s]=%s,"]
- local f_indexed_boolean=formatters["[%s]=%l,"]
- local f_indexed_table=formatters["[%s]="]
- local f_ordered_string=formatters["%Q,"]
- local f_ordered_number=formatters["%s,"]
- local f_ordered_boolean=formatters["%l,"]
- function table.fastserialize(t,prefix)
- local r={ type(prefix)=="string" and prefix or "return" }
- local m=1
- local function fastserialize(t,outer)
- local n=#t
- m=m+1
- r[m]="{"
- if n>0 then
- local v=t[0]
- if v then
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_indexed_string(0,v)
- elseif tv=="number" then
- m=m+1 r[m]=f_indexed_number(0,v)
- elseif tv=="table" then
- m=m+1 r[m]=f_indexed_table(0)
- fastserialize(v)
- m=m+1 r[m]=f_indexed_table(0)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_indexed_boolean(0,v)
- end
- end
- for i=1,n do
- local v=t[i]
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_ordered_string(v)
- elseif tv=="number" then
- m=m+1 r[m]=f_ordered_number(v)
- elseif tv=="table" then
- fastserialize(v)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_ordered_boolean(v)
- end
- end
- end
- for k,v in next,t do
- local tk=type(k)
- if tk=="number" then
- if k>n or k<0 then
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_indexed_string(k,v)
- elseif tv=="number" then
- m=m+1 r[m]=f_indexed_number(k,v)
- elseif tv=="table" then
- m=m+1 r[m]=f_indexed_table(k)
- fastserialize(v)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_indexed_boolean(k,v)
- end
- end
- else
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_hashed_string(k,v)
- elseif tv=="number" then
- m=m+1 r[m]=f_hashed_number(k,v)
- elseif tv=="table" then
- m=m+1 r[m]=f_hashed_table(k)
- fastserialize(v)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_hashed_boolean(k,v)
- end
- end
- end
- m=m+1
- if outer then
- r[m]="}"
- else
- r[m]="},"
- end
- return r
- end
- return concat(fastserialize(t,true))
- end
-else
- local f_v=formatters["[%q]=%q,"]
- local f_t=formatters["[%q]="]
- local f_q=formatters["%q,"]
- function table.fastserialize(t,prefix)
- local r={ type(prefix)=="string" and prefix or "return" }
- local m=1
- local function fastserialize(t,outer)
- local n=#t
- m=m+1
- r[m]="{"
- if n>0 then
- local v=t[0]
- if v then
- m=m+1
- r[m]="[0]='"
- if type(v)=="table" then
- fastserialize(v)
- else
- r[m]=format("%q,",v)
- end
- end
- for i=1,n do
- local v=t[i]
- m=m+1
- if type(v)=="table" then
- r[m]=format("[%i]=",i)
- fastserialize(v)
- else
- r[m]=format("[%i]=%q,",i,v)
- end
- end
- end
- for k,v in next,t do
- local tk=type(k)
- if tk=="number" then
- if k>n or k<0 then
- m=m+1
- if type(v)=="table" then
- r[m]=format("[%i]=",k)
- fastserialize(v)
- else
- r[m]=format("[%i]=%q,",k,v)
- end
- end
- else
- m=m+1
- if type(v)=="table" then
- r[m]=format("[%q]=",k)
- fastserialize(v)
- else
- r[m]=format("[%q]=%q,",k,v)
- end
- end
- end
- m=m+1
- if outer then
- r[m]="}"
- else
- r[m]="},"
- end
- return r
- end
- return concat(fastserialize(t,true))
- end
-end
-function table.deserialize(str)
- if not str or str=="" then
- return
- end
- local code=load(str)
- if not code then
- return
- end
- code=code()
- if not code then
- return
- end
- return code
-end
-function table.load(filename,loader)
- if filename then
- local t=(loader or io.loaddata)(filename)
- if t and t~="" then
- local t=utftoeight(t)
- t=load(t)
- if type(t)=="function" then
- t=t()
- if type(t)=="table" then
- return t
- end
- end
- end
- end
-end
-function table.save(filename,t,n,...)
- io.savedata(filename,table.serialize(t,n==nil and true or n,...))
-end
-local f_key_value=formatters["%s=%q"]
-local f_add_table=formatters[" {%t},\n"]
-local f_return_table=formatters["return {\n%t}"]
-local function slowdrop(t)
- local r={}
- local l={}
- for i=1,#t do
- local ti=t[i]
- local j=0
- for k,v in next,ti do
- j=j+1
- l[j]=f_key_value(k,v)
- end
- r[i]=f_add_table(l)
- end
- return f_return_table(r)
-end
-local function fastdrop(t)
- local r={ "return {\n" }
- local m=1
- for i=1,#t do
- local ti=t[i]
- m=m+1 r[m]=" {"
- for k,v in next,ti do
- m=m+1 r[m]=f_key_value(k,v)
- end
- m=m+1 r[m]="},\n"
- end
- m=m+1
- r[m]="}"
- return concat(r)
-end
-function table.drop(t,slow)
- if #t==0 then
- return "return { }"
- elseif slow==true then
- return slowdrop(t)
- else
- return fastdrop(t)
- end
-end
-local selfmapper={ __index=function(t,k) t[k]=k return k end }
-function table.twowaymapper(t)
- if not t then
- t={}
- else
- local zero=rawget(t,0)
- for i=zero and 0 or 1,#t do
- local ti=t[i]
- if ti then
- local i=tostring(i)
- t[i]=ti
- t[ti]=i
- end
- end
- end
- setmetatable(t,selfmapper)
- return t
-end
-local f_start_key_idx=formatters["%w{"]
-local f_start_key_num=JITSUPPORTED and formatters["%w[%s]={"] or formatters["%w[%q]={"]
-local f_start_key_str=formatters["%w[%q]={"]
-local f_start_key_boo=formatters["%w[%l]={"]
-local f_start_key_nop=formatters["%w{"]
-local f_stop=formatters["%w},"]
-local f_key_num_value_num=JITSUPPORTED and formatters["%w[%s]=%s,"] or formatters["%w[%s]=%q,"]
-local f_key_str_value_num=JITSUPPORTED and formatters["%w[%Q]=%s,"] or formatters["%w[%Q]=%q,"]
-local f_key_boo_value_num=JITSUPPORTED and formatters["%w[%l]=%s,"] or formatters["%w[%l]=%q,"]
-local f_key_num_value_str=JITSUPPORTED and formatters["%w[%s]=%Q,"] or formatters["%w[%q]=%Q,"]
-local f_key_str_value_str=formatters["%w[%Q]=%Q,"]
-local f_key_boo_value_str=formatters["%w[%l]=%Q,"]
-local f_key_num_value_boo=JITSUPPORTED and formatters["%w[%s]=%l,"] or formatters["%w[%q]=%l,"]
-local f_key_str_value_boo=formatters["%w[%Q]=%l,"]
-local f_key_boo_value_boo=formatters["%w[%l]=%l,"]
-local f_key_num_value_not=JITSUPPORTED and formatters["%w[%s]={},"] or formatters["%w[%q]={},"]
-local f_key_str_value_not=formatters["%w[%Q]={},"]
-local f_key_boo_value_not=formatters["%w[%l]={},"]
-local f_key_num_value_seq=JITSUPPORTED and formatters["%w[%s]={ %, t },"] or formatters["%w[%q]={ %, t },"]
-local f_key_str_value_seq=formatters["%w[%Q]={ %, t },"]
-local f_key_boo_value_seq=formatters["%w[%l]={ %, t },"]
-local f_val_num=JITSUPPORTED and formatters["%w%s,"] or formatters["%w%q,"]
-local f_val_str=formatters["%w%Q,"]
-local f_val_boo=formatters["%w%l,"]
-local f_val_not=formatters["%w{},"]
-local f_val_seq=formatters["%w{ %, t },"]
-local f_fin_seq=formatters[" %, t }"]
-local f_table_return=formatters["return {"]
-local f_table_name=formatters["%s={"]
-local f_table_direct=formatters["{"]
-local f_table_entry=formatters["[%Q]={"]
-local f_table_finish=formatters["}"]
-local spaces=utilities.strings.newrepeater(" ")
-local original_serialize=table.serialize
-local is_simple_table=table.is_simple_table
-local function serialize(root,name,specification)
- if type(specification)=="table" then
- return original_serialize(root,name,specification)
- end
- local t
- local n=1
- local unknown=false
- local function do_serialize(root,name,depth,level,indexed)
- if level>0 then
- n=n+1
- if indexed then
- t[n]=f_start_key_idx(depth)
- else
- local tn=type(name)
- if tn=="number" then
- t[n]=f_start_key_num(depth,name)
- elseif tn=="string" then
- t[n]=f_start_key_str(depth,name)
- elseif tn=="boolean" then
- t[n]=f_start_key_boo(depth,name)
- else
- t[n]=f_start_key_nop(depth)
- end
- end
- depth=depth+1
- end
- if root and next(root)~=nil then
- local first=nil
- local last=#root
- if last>0 then
- for k=1,last do
- if rawget(root,k)==nil then
- last=k-1
- break
- end
- end
- if last>0 then
- first=1
- end
- end
- local sk=sortedkeys(root)
- for i=1,#sk do
- local k=sk[i]
- local v=root[k]
- local tv=type(v)
- local tk=type(k)
- if first and tk=="number" and k<=last and k>=first then
- if tv=="number" then
- n=n+1 t[n]=f_val_num(depth,v)
- elseif tv=="string" then
- n=n+1 t[n]=f_val_str(depth,v)
- elseif tv=="table" then
- if next(v)==nil then
- n=n+1 t[n]=f_val_not(depth)
- else
- local st=is_simple_table(v)
- if st then
- n=n+1 t[n]=f_val_seq(depth,st)
- else
- do_serialize(v,k,depth,level+1,true)
- end
- end
- elseif tv=="boolean" then
- n=n+1 t[n]=f_val_boo(depth,v)
- elseif unknown then
- n=n+1 t[n]=f_val_str(depth,tostring(v))
- end
- elseif tv=="number" then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_num(depth,k,v)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_num(depth,k,v)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_num(depth,k,v)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_num(depth,tostring(k),v)
- end
- elseif tv=="string" then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_str(depth,k,v)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_str(depth,k,v)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_str(depth,k,v)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_str(depth,tostring(k),v)
- end
- elseif tv=="table" then
- if next(v)==nil then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_not(depth,k)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_not(depth,k)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_not(depth,k)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_not(depth,tostring(k))
- end
- else
- local st=is_simple_table(v)
- if not st then
- do_serialize(v,k,depth,level+1)
- elseif tk=="number" then
- n=n+1 t[n]=f_key_num_value_seq(depth,k,st)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_seq(depth,k,st)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_seq(depth,k,st)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_seq(depth,tostring(k),st)
- end
- end
- elseif tv=="boolean" then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_boo(depth,k,v)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_boo(depth,k,v)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_boo(depth,k,v)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_boo(depth,tostring(k),v)
- end
- else
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_str(depth,k,tostring(v))
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_str(depth,k,tostring(v))
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_str(depth,k,tostring(v))
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_str(depth,tostring(k),tostring(v))
- end
- end
- end
- end
- if level>0 then
- n=n+1 t[n]=f_stop(depth-1)
- end
- end
- local tname=type(name)
- if tname=="string" then
- if name=="return" then
- t={ f_table_return() }
- else
- t={ f_table_name(name) }
- end
- elseif tname=="number" then
- t={ f_table_entry(name) }
- elseif tname=="boolean" then
- if name then
- t={ f_table_return() }
- else
- t={ f_table_direct() }
- end
- else
- t={ f_table_name("t") }
- end
- if root then
- if getmetatable(root) then
- local dummy=root._w_h_a_t_e_v_e_r_
- root._w_h_a_t_e_v_e_r_=nil
- end
- if next(root)~=nil then
- local st=is_simple_table(root)
- if st then
- return t[1]..f_fin_seq(st)
- else
- do_serialize(root,name,1,0)
- end
- end
- end
- n=n+1
- t[n]=f_table_finish()
- return concat(t,"\n")
-end
-table.serialize=serialize
-if setinspector then
- setinspector("table",function(v)
- if type(v)=="table" then
- print(serialize(v,"table",{ metacheck=false }))
- return true
- end
- end)
-end
-local mt={
- __newindex=function(t,k,v)
- local n=t.last+1
- t.last=n
- t.list[n]=k
- t.hash[k]=v
- end,
- __index=function(t,k)
- return t.hash[k]
- end,
- __len=function(t)
- return t.last
- end,
-}
-function table.orderedhash()
- return setmetatable({ list={},hash={},last=0 },mt)
-end
-function table.ordered(t)
- local n=t.last
- if n>0 then
- local l=t.list
- local i=1
- local h=t.hash
- local f=function()
- if i<=n then
- local k=i
- local v=h[l[k]]
- i=i+1
- return k,v
- end
- end
- return f,1,h[l[1]]
- else
- return function() end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-fil"] = package.loaded["util-fil"] or true
-
--- original size: 11552, stripped down to: 9023
-
-if not modules then modules={} end modules ['util-fil']={
- version=1.001,
- optimize=true,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local tonumber=tonumber
-local byte=string.byte
-local char=string.char
-utilities=utilities or {}
-local files={}
-utilities.files=files
-local zerobased={}
-function files.open(filename,zb)
- local f=io.open(filename,"rb")
- if f then
- zerobased[f]=zb or false
- end
- return f
-end
-function files.close(f)
- zerobased[f]=nil
- f:close()
-end
-function files.size(f)
- local current=f:seek()
- local size=f:seek("end")
- f:seek("set",current)
- return size
-end
-files.getsize=files.size
-function files.setposition(f,n)
- if zerobased[f] then
- f:seek("set",n)
- else
- f:seek("set",n-1)
- end
-end
-function files.getposition(f)
- if zerobased[f] then
- return f:seek()
- else
- return f:seek()+1
- end
-end
-function files.look(f,n,chars)
- local p=f:seek()
- local s=f:read(n)
- f:seek("set",p)
- if chars then
- return s
- else
- return byte(s,1,#s)
- end
-end
-function files.skip(f,n)
- if n==1 then
- f:read(n)
- else
- f:seek("set",f:seek()+n)
- end
-end
-function files.readbyte(f)
- return byte(f:read(1))
-end
-function files.readbytes(f,n)
- return byte(f:read(n),1,n)
-end
-function files.readbytetable(f,n)
- local s=f:read(n or 1)
- return { byte(s,1,#s) }
-end
-function files.readchar(f)
- return f:read(1)
-end
-function files.readstring(f,n)
- return f:read(n or 1)
-end
-function files.readinteger1(f)
- local n=byte(f:read(1))
- if n>=0x80 then
- return n-0x100
- else
- return n
- end
-end
-files.readcardinal1=files.readbyte
-files.readcardinal=files.readcardinal1
-files.readinteger=files.readinteger1
-files.readsignedbyte=files.readinteger1
-function files.readcardinal2(f)
- local a,b=byte(f:read(2),1,2)
- return 0x100*a+b
-end
-function files.readcardinal2le(f)
- local b,a=byte(f:read(2),1,2)
- return 0x100*a+b
-end
-function files.readinteger2(f)
- local a,b=byte(f:read(2),1,2)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function files.readinteger2le(f)
- local b,a=byte(f:read(2),1,2)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function files.readcardinal3(f)
- local a,b,c=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
-end
-function files.readcardinal3le(f)
- local c,b,a=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
-end
-function files.readinteger3(f)
- local a,b,c=byte(f:read(3),1,3)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function files.readinteger3le(f)
- local c,b,a=byte(f:read(3),1,3)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function files.readcardinal4(f)
- local a,b,c,d=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function files.readcardinal4le(f)
- local d,c,b,a=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function files.readinteger4(f)
- local a,b,c,d=byte(f:read(4),1,4)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function files.readinteger4le(f)
- local d,c,b,a=byte(f:read(4),1,4)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function files.readfixed2(f)
- local a,b=byte(f:read(2),1,2)
- if a>=0x80 then
- tonumber((a-0x100).."."..b)
- else
- tonumber((a ).."."..b)
- end
-end
-function files.readfixed4(f)
- local a,b,c,d=byte(f:read(4),1,4)
- if a>=0x80 then
- tonumber((0x100*a+b-0x10000).."."..(0x100*c+d))
- else
- tonumber((0x100*a+b ).."."..(0x100*c+d))
- end
-end
-if bit32 then
- local extract=bit32.extract
- local band=bit32.band
- function files.read2dot14(f)
- local a,b=byte(f:read(2),1,2)
- if a>=0x80 then
- local n=-(0x100*a+b)
- return-(extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- else
- local n=0x100*a+b
- return (extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- end
- end
-end
-function files.skipshort(f,n)
- f:read(2*(n or 1))
-end
-function files.skiplong(f,n)
- f:read(4*(n or 1))
-end
-if bit32 then
- local rshift=bit32.rshift
- function files.writecardinal2(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- f:write(b,a)
- end
- function files.writecardinal4(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- n=rshift(n,8)
- local c=char(n%256)
- n=rshift(n,8)
- local d=char(n%256)
- f:write(d,c,b,a)
- end
- function files.writecardinal2le(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- f:write(a,b)
- end
- function files.writecardinal4le(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- n=rshift(n,8)
- local c=char(n%256)
- n=rshift(n,8)
- local d=char(n%256)
- f:write(a,b,c,d)
- end
-else
- local floor=math.floor
- function files.writecardinal2(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- f:write(b,a)
- end
- function files.writecardinal4(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- n=floor(n/256)
- local c=char(n%256)
- n=floor(n/256)
- local d=char(n%256)
- f:write(d,c,b,a)
- end
- function files.writecardinal2le(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- f:write(a,b)
- end
- function files.writecardinal4le(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- n=floor(n/256)
- local c=char(n%256)
- n=floor(n/256)
- local d=char(n%256)
- f:write(a,b,c,d)
- end
-end
-function files.writestring(f,s)
- f:write(char(byte(s,1,#s)))
-end
-function files.writebyte(f,b)
- f:write(char(b))
-end
-if fio and fio.readcardinal1 then
- files.readcardinal1=fio.readcardinal1
- files.readcardinal2=fio.readcardinal2
- files.readcardinal3=fio.readcardinal3
- files.readcardinal4=fio.readcardinal4
- files.readcardinal1le=fio.readcardinal1le or files.readcardinal1le
- files.readcardinal2le=fio.readcardinal2le or files.readcardinal2le
- files.readcardinal3le=fio.readcardinal3le or files.readcardinal3le
- files.readcardinal4le=fio.readcardinal4le or files.readcardinal4le
- files.readinteger1=fio.readinteger1
- files.readinteger2=fio.readinteger2
- files.readinteger3=fio.readinteger3
- files.readinteger4=fio.readinteger4
- files.readinteger1le=fio.readinteger1le or files.readinteger1le
- files.readinteger2le=fio.readinteger2le or files.readinteger2le
- files.readinteger3le=fio.readinteger3le or files.readinteger3le
- files.readinteger4le=fio.readinteger4le or files.readinteger4le
- files.readfixed2=fio.readfixed2
- files.readfixed4=fio.readfixed4
- files.read2dot14=fio.read2dot14
- files.setposition=fio.setposition
- files.getposition=fio.getposition
- files.readbyte=files.readcardinal1
- files.readsignedbyte=files.readinteger1
- files.readcardinal=files.readcardinal1
- files.readinteger=files.readinteger1
- local skipposition=fio.skipposition
- files.skipposition=skipposition
- files.readbytes=fio.readbytes
- files.readbytetable=fio.readbytetable
- function files.skipshort(f,n)
- skipposition(f,2*(n or 1))
- end
- function files.skiplong(f,n)
- skipposition(f,4*(n or 1))
- end
-end
-if fio and fio.writecardinal1 then
- files.writecardinal1=fio.writecardinal1
- files.writecardinal2=fio.writecardinal2
- files.writecardinal3=fio.writecardinal3
- files.writecardinal4=fio.writecardinal4
- files.writecardinal1le=fio.writecardinal1le
- files.writecardinal2le=fio.writecardinal2le
- files.writecardinal3le=fio.writecardinal3le
- files.writecardinal4le=fio.writecardinal4le
- files.writeinteger1=fio.writeinteger1 or fio.writecardinal1
- files.writeinteger2=fio.writeinteger2 or fio.writecardinal2
- files.writeinteger3=fio.writeinteger3 or fio.writecardinal3
- files.writeinteger4=fio.writeinteger4 or fio.writecardinal4
- files.writeinteger1le=files.writeinteger1le or fio.writecardinal1le
- files.writeinteger2le=files.writeinteger2le or fio.writecardinal2le
- files.writeinteger3le=files.writeinteger3le or fio.writecardinal3le
- files.writeinteger4le=files.writeinteger4le or fio.writecardinal4le
-end
-if fio and fio.readcardinaltable then
- files.readcardinaltable=fio.readcardinaltable
- files.readintegertable=fio.readintegertable
-else
- local readcardinal1=files.readcardinal1
- local readcardinal2=files.readcardinal2
- local readcardinal3=files.readcardinal3
- local readcardinal4=files.readcardinal4
- function files.readcardinaltable(f,n,b)
- local t={}
- if b==1 then for i=1,n do t[i]=readcardinal1(f) end
- elseif b==2 then for i=1,n do t[i]=readcardinal2(f) end
- elseif b==3 then for i=1,n do t[i]=readcardinal3(f) end
- elseif b==4 then for i=1,n do t[i]=readcardinal4(f) end end
- return t
- end
- local readinteger1=files.readinteger1
- local readinteger2=files.readinteger2
- local readinteger3=files.readinteger3
- local readinteger4=files.readinteger4
- function files.readintegertable(f,n,b)
- local t={}
- if b==1 then for i=1,n do t[i]=readinteger1(f) end
- elseif b==2 then for i=1,n do t[i]=readinteger2(f) end
- elseif b==3 then for i=1,n do t[i]=readinteger3(f) end
- elseif b==4 then for i=1,n do t[i]=readinteger4(f) end end
- return t
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-sac"] = package.loaded["util-sac"] or true
-
--- original size: 12968, stripped down to: 9523
-
-if not modules then modules={} end modules ['util-sac']={
- version=1.001,
- optimize=true,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local byte,sub=string.byte,string.sub
-local tonumber=tonumber
-utilities=utilities or {}
-local streams={}
-utilities.streams=streams
-function streams.open(filename,zerobased)
- local f=filename and io.loaddata(filename)
- if f then
- return { f,1,#f,zerobased or false }
- end
-end
-function streams.openstring(f,zerobased)
- if f then
- return { f,1,#f,zerobased or false }
- end
-end
-function streams.getstring(f)
- if f then
- return f[1]
- end
-end
-function streams.close()
-end
-function streams.size(f)
- return f and f[3] or 0
-end
-streams.getsize=streams.size
-function streams.setposition(f,i)
- if f[4] then
- if i<=0 then
- f[2]=1
- else
- f[2]=i+1
- end
- else
- if i<=1 then
- f[2]=1
- else
- f[2]=i
- end
- end
-end
-function streams.getposition(f)
- if f[4] then
- return f[2]-1
- else
- return f[2]
- end
-end
-function streams.look(f,n,chars)
- local b=f[2]
- local e=b+n-1
- if chars then
- return sub(f[1],b,e)
- else
- return byte(f[1],b,e)
- end
-end
-function streams.skip(f,n)
- f[2]=f[2]+n
-end
-function streams.readbyte(f)
- local i=f[2]
- f[2]=i+1
- return byte(f[1],i)
-end
-function streams.readbytes(f,n)
- local i=f[2]
- local j=i+n
- f[2]=j
- return byte(f[1],i,j-1)
-end
-function streams.readbytetable(f,n)
- local i=f[2]
- local j=i+n
- f[2]=j
- return { byte(f[1],i,j-1) }
-end
-function streams.skipbytes(f,n)
- f[2]=f[2]+n
-end
-function streams.readchar(f)
- local i=f[2]
- f[2]=i+1
- return sub(f[1],i,i)
-end
-function streams.readstring(f,n)
- local i=f[2]
- local j=i+n
- f[2]=j
- return sub(f[1],i,j-1)
-end
-function streams.readinteger1(f)
- local i=f[2]
- f[2]=i+1
- local n=byte(f[1],i)
- if n>=0x80 then
- return n-0x100
- else
- return n
- end
-end
-streams.readcardinal1=streams.readbyte
-streams.readcardinal=streams.readcardinal1
-streams.readinteger=streams.readinteger1
-function streams.readcardinal2(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- return 0x100*a+b
-end
-function streams.readcardinal2le(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local b,a=byte(f[1],i,j)
- return 0x100*a+b
-end
-function streams.readinteger2(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function streams.readinteger2le(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local b,a=byte(f[1],i,j)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function streams.readcardinal3(f)
- local i=f[2]
- local j=i+2
- f[2]=j+1
- local a,b,c=byte(f[1],i,j)
- return 0x10000*a+0x100*b+c
-end
-function streams.readcardinal3le(f)
- local i=f[2]
- local j=i+2
- f[2]=j+1
- local c,b,a=byte(f[1],i,j)
- return 0x10000*a+0x100*b+c
-end
-function streams.readinteger3(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c=byte(f[1],i,j)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function streams.readinteger3le(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local c,b,a=byte(f[1],i,j)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function streams.readcardinal4(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c,d=byte(f[1],i,j)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function streams.readcardinal4le(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local d,c,b,a=byte(f[1],i,j)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function streams.readinteger4(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c,d=byte(f[1],i,j)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function streams.readinteger4le(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local d,c,b,a=byte(f[1],i,j)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function streams.readfixed2(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- if a>=0x80 then
- return tonumber((a-0x100).."."..b) or 0
- else
- return tonumber((a ).."."..b) or 0
- end
-end
-function streams.readfixed4(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c,d=byte(f[1],i,j)
- if a>=0x80 then
- return tonumber((0x100*a+b-0x10000).."."..(0x100*c+d)) or 0
- else
- return tonumber((0x100*a+b ).."."..(0x100*c+d)) or 0
- end
-end
-if bit32 then
- local extract=bit32.extract
- local band=bit32.band
- function streams.read2dot14(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- if a>=0x80 then
- local n=-(0x100*a+b)
- return-(extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- else
- local n=0x100*a+b
- return (extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- end
- end
-end
-function streams.skipshort(f,n)
- f[2]=f[2]+2*(n or 1)
-end
-function streams.skiplong(f,n)
- f[2]=f[2]+4*(n or 1)
-end
-if sio and sio.readcardinal2 then
- local readcardinal1=sio.readcardinal1
- local readcardinal2=sio.readcardinal2
- local readcardinal3=sio.readcardinal3
- local readcardinal4=sio.readcardinal4
- local readinteger1=sio.readinteger1
- local readinteger2=sio.readinteger2
- local readinteger3=sio.readinteger3
- local readinteger4=sio.readinteger4
- local readfixed2=sio.readfixed2
- local readfixed4=sio.readfixed4
- local read2dot14=sio.read2dot14
- local readbytes=sio.readbytes
- local readbytetable=sio.readbytetable
- function streams.readcardinal1(f)
- local i=f[2]
- f[2]=i+1
- return readcardinal1(f[1],i)
- end
- function streams.readcardinal2(f)
- local i=f[2]
- f[2]=i+2
- return readcardinal2(f[1],i)
- end
- function streams.readcardinal3(f)
- local i=f[2]
- f[2]=i+3
- return readcardinal3(f[1],i)
- end
- function streams.readcardinal4(f)
- local i=f[2]
- f[2]=i+4
- return readcardinal4(f[1],i)
- end
- function streams.readinteger1(f)
- local i=f[2]
- f[2]=i+1
- return readinteger1(f[1],i)
- end
- function streams.readinteger2(f)
- local i=f[2]
- f[2]=i+2
- return readinteger2(f[1],i)
- end
- function streams.readinteger3(f)
- local i=f[2]
- f[2]=i+3
- return readinteger3(f[1],i)
- end
- function streams.readinteger4(f)
- local i=f[2]
- f[2]=i+4
- return readinteger4(f[1],i)
- end
- function streams.readfixed2(f)
- local i=f[2]
- f[2]=i+2
- return readfixed2(f[1],i)
- end
- function streams.readfixed4(f)
- local i=f[2]
- f[2]=i+4
- return readfixed4(f[1],i)
- end
- function streams.read2dot4(f)
- local i=f[2]
- f[2]=i+2
- return read2dot4(f[1],i)
- end
- function streams.readbytes(f,n)
- local i=f[2]
- local s=f[3]
- local p=i+n
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readbytes(f[1],i,n)
- end
- function streams.readbytetable(f,n)
- local i=f[2]
- local s=f[3]
- local p=i+n
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readbytetable(f[1],i,n)
- end
- streams.readbyte=streams.readcardinal1
- streams.readsignedbyte=streams.readinteger1
- streams.readcardinal=streams.readcardinal1
- streams.readinteger=streams.readinteger1
-end
-if sio and sio.readcardinaltable then
- local readcardinaltable=sio.readcardinaltable
- local readintegertable=sio.readintegertable
- function utilities.streams.readcardinaltable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readcardinaltable(f[1],i,n,b)
- end
- function utilities.streams.readintegertable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readintegertable(f[1],i,n,b)
- end
-else
- local readcardinal1=streams.readcardinal1
- local readcardinal2=streams.readcardinal2
- local readcardinal3=streams.readcardinal3
- local readcardinal4=streams.readcardinal4
- function streams.readcardinaltable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- local t={}
- if b==1 then for i=1,n do t[i]=readcardinal1(f[1],i) end
- elseif b==2 then for i=1,n do t[i]=readcardinal2(f[1],i) end
- elseif b==3 then for i=1,n do t[i]=readcardinal3(f[1],i) end
- elseif b==4 then for i=1,n do t[i]=readcardinal4(f[1],i) end end
- return t
- end
- local readinteger1=streams.readinteger1
- local readinteger2=streams.readinteger2
- local readinteger3=streams.readinteger3
- local readinteger4=streams.readinteger4
- function streams.readintegertable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- local t={}
- if b==1 then for i=1,n do t[i]=readinteger1(f[1],i) end
- elseif b==2 then for i=1,n do t[i]=readinteger2(f[1],i) end
- elseif b==3 then for i=1,n do t[i]=readinteger3(f[1],i) end
- elseif b==4 then for i=1,n do t[i]=readinteger4(f[1],i) end end
- return t
- end
-end
-do
- local files=utilities.files
- if files then
- local openfile=files.open
- local openstream=streams.open
- local openstring=streams.openstring
- local setmetatable=setmetatable
- function io.newreader(str,method)
- local f,m
- if method=="string" then
- f=openstring(str)
- m=streams
- elseif method=="stream" then
- f=openstream(str)
- m=streams
- else
- f=openfile(str,"rb")
- m=files
- end
- if f then
- local t={}
- setmetatable(t,{
- __index=function(t,k)
- local r=m[k]
- if k=="close" then
- if f then
- m.close(f)
- f=nil
- end
- return function() end
- elseif r then
- local v=function(_,a,b) return r(f,a,b) end
- t[k]=v
- return v
- else
- print("unknown key",k)
- end
- end
- } )
- return t
- end
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-sto"] = package.loaded["util-sto"] or true
-
--- original size: 6661, stripped down to: 3074
-
-if not modules then modules={} end modules ['util-sto']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local setmetatable,getmetatable,rawset,type=setmetatable,getmetatable,rawset,type
-utilities=utilities or {}
-utilities.storage=utilities.storage or {}
-local storage=utilities.storage
-function storage.mark(t)
- if not t then
- print("\nfatal error: storage cannot be marked\n")
- os.exit()
- return
- end
- local m=getmetatable(t)
- if not m then
- m={}
- setmetatable(t,m)
- end
- m.__storage__=true
- return t
-end
-function storage.allocate(t)
- t=t or {}
- local m=getmetatable(t)
- if not m then
- m={}
- setmetatable(t,m)
- end
- m.__storage__=true
- return t
-end
-function storage.marked(t)
- local m=getmetatable(t)
- return m and m.__storage__
-end
-function storage.checked(t)
- if not t then
- report("\nfatal error: storage has not been allocated\n")
- os.exit()
- return
- end
- return t
-end
-function storage.setinitializer(data,initialize)
- local m=getmetatable(data) or {}
- m.__index=function(data,k)
- m.__index=nil
- initialize()
- return data[k]
- end
- setmetatable(data,m)
-end
-local keyisvalue={ __index=function(t,k)
- t[k]=k
- return k
-end }
-function storage.sparse(t)
- t=t or {}
- setmetatable(t,keyisvalue)
- return t
-end
-local function f_empty () return "" end
-local function f_self (t,k) t[k]=k return k end
-local function f_table (t,k) local v={} t[k]=v return v end
-local function f_number(t,k) t[k]=0 return 0 end
-local function f_ignore() end
-local f_index={
- ["empty"]=f_empty,
- ["self"]=f_self,
- ["table"]=f_table,
- ["number"]=f_number,
-}
-function table.setmetatableindex(t,f)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- local i=f_index[f] or f
- if m then
- m.__index=i
- else
- setmetatable(t,{ __index=i })
- end
- return t
-end
-local f_index={
- ["ignore"]=f_ignore,
-}
-function table.setmetatablenewindex(t,f)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- local i=f_index[f] or f
- if m then
- m.__newindex=i
- else
- setmetatable(t,{ __newindex=i })
- end
- return t
-end
-function table.setmetatablecall(t,f)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- if m then
- m.__call=f
- else
- setmetatable(t,{ __call=f })
- end
- return t
-end
-function table.setmetatableindices(t,f,n,c)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- local i=f_index[f] or f
- if m then
- m.__index=i
- m.__newindex=n
- m.__call=c
- else
- setmetatable(t,{
- __index=i,
- __newindex=n,
- __call=c,
- })
- end
- return t
-end
-function table.setmetatablekey(t,key,value)
- local m=getmetatable(t)
- if not m then
- m={}
- setmetatable(t,m)
- end
- m[key]=value
- return t
-end
-function table.getmetatablekey(t,key,value)
- local m=getmetatable(t)
- return m and m[key]
-end
-function table.makeweak(t)
- if not t then
- t={}
- end
- local m=getmetatable(t)
- if m then
- m.__mode="v"
- else
- setmetatable(t,{ __mode="v" })
- end
- return t
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-prs"] = package.loaded["util-prs"] or true
-
--- original size: 24683, stripped down to: 16431
-
-if not modules then modules={} end modules ['util-prs']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local lpeg,table,string=lpeg,table,string
-local P,R,V,S,C,Ct,Cs,Carg,Cc,Cg,Cf,Cp=lpeg.P,lpeg.R,lpeg.V,lpeg.S,lpeg.C,lpeg.Ct,lpeg.Cs,lpeg.Carg,lpeg.Cc,lpeg.Cg,lpeg.Cf,lpeg.Cp
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local concat,gmatch,find=table.concat,string.gmatch,string.find
-local tonumber,tostring,type,next,rawset=tonumber,tostring,type,next,rawset
-local mod,div=math.mod,math.div
-utilities=utilities or {}
-local parsers=utilities.parsers or {}
-utilities.parsers=parsers
-local patterns=parsers.patterns or {}
-parsers.patterns=patterns
-local setmetatableindex=table.setmetatableindex
-local sortedhash=table.sortedhash
-local sortedkeys=table.sortedkeys
-local tohash=table.tohash
-local hashes={}
-parsers.hashes=hashes
-local digit=R("09")
-local space=P(' ')
-local equal=P("=")
-local colon=P(":")
-local comma=P(",")
-local lbrace=P("{")
-local rbrace=P("}")
-local lparent=P("(")
-local rparent=P(")")
-local lbracket=P("[")
-local rbracket=P("]")
-local period=S(".")
-local punctuation=S(".,:;")
-local spacer=lpegpatterns.spacer
-local whitespace=lpegpatterns.whitespace
-local newline=lpegpatterns.newline
-local anything=lpegpatterns.anything
-local endofstring=lpegpatterns.endofstring
-local nobrace=1-(lbrace+rbrace )
-local noparent=1-(lparent+rparent)
-local nobracket=1-(lbracket+rbracket)
-local escape,left,right=P("\\"),P('{'),P('}')
-lpegpatterns.balanced=P {
- [1]=((escape*(left+right))+(1-(left+right))+V(2))^0,
- [2]=left*V(1)*right
-}
-local nestedbraces=P { lbrace*(nobrace+V(1))^0*rbrace }
-local nestedparents=P { lparent*(noparent+V(1))^0*rparent }
-local nestedbrackets=P { lbracket*(nobracket+V(1))^0*rbracket }
-local spaces=space^0
-local argument=Cs((lbrace/"")*((nobrace+nestedbraces)^0)*(rbrace/""))
-local content=(1-endofstring)^0
-lpegpatterns.nestedbraces=nestedbraces
-lpegpatterns.nestedparents=nestedparents
-lpegpatterns.nested=nestedbraces
-lpegpatterns.argument=argument
-lpegpatterns.content=content
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+(1-comma))^0)
-local key=C((1-equal-comma)^1)
-local pattern_a=(space+comma)^0*(key*equal*value+key*C(""))
-local pattern_c=(space+comma)^0*(key*equal*value)
-local pattern_d=(space+comma)^0*(key*(equal+colon)*value+key*C(""))
-local key=C((1-space-equal-comma)^1)
-local pattern_b=spaces*comma^0*spaces*(key*((spaces*equal*spaces*value)+C("")))
-local hash={}
-local function set(key,value)
- hash[key]=value
-end
-local pattern_a_s=(pattern_a/set)^1
-local pattern_b_s=(pattern_b/set)^1
-local pattern_c_s=(pattern_c/set)^1
-local pattern_d_s=(pattern_d/set)^1
-patterns.settings_to_hash_a=pattern_a_s
-patterns.settings_to_hash_b=pattern_b_s
-patterns.settings_to_hash_c=pattern_c_s
-patterns.settings_to_hash_d=pattern_d_s
-function parsers.make_settings_to_hash_pattern(set,how)
- if how=="strict" then
- return (pattern_c/set)^1
- elseif how=="tolerant" then
- return (pattern_b/set)^1
- else
- return (pattern_a/set)^1
- end
-end
-function parsers.settings_to_hash(str,existing)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- if existing then
- for k,v in next,str do
- existing[k]=v
- end
- return exiting
- else
- return str
- end
- else
- hash=existing or {}
- lpegmatch(pattern_a_s,str)
- return hash
- end
-end
-function parsers.settings_to_hash_colon_too(str)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- return str
- else
- hash={}
- lpegmatch(pattern_d_s,str)
- return hash
- end
-end
-function parsers.settings_to_hash_tolerant(str,existing)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- if existing then
- for k,v in next,str do
- existing[k]=v
- end
- return exiting
- else
- return str
- end
- else
- hash=existing or {}
- lpegmatch(pattern_b_s,str)
- return hash
- end
-end
-function parsers.settings_to_hash_strict(str,existing)
- if not str or str=="" then
- return nil
- elseif type(str)=="table" then
- if existing then
- for k,v in next,str do
- existing[k]=v
- end
- return exiting
- else
- return str
- end
- elseif str and str~="" then
- hash=existing or {}
- lpegmatch(pattern_c_s,str)
- return next(hash) and hash
- end
-end
-local separator=comma*space^0
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+(1-comma))^0)
-local pattern=spaces*Ct(value*(separator*value)^0)
-patterns.settings_to_array=pattern
-function parsers.settings_to_array(str,strict)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- return str
- elseif strict then
- if find(str,"{",1,true) then
- return lpegmatch(pattern,str)
- else
- return { str }
- end
- elseif find(str,",",1,true) then
- return lpegmatch(pattern,str)
- else
- return { str }
- end
-end
-function parsers.settings_to_numbers(str)
- if not str or str=="" then
- return {}
- end
- if type(str)=="table" then
- elseif find(str,",",1,true) then
- str=lpegmatch(pattern,str)
- else
- return { tonumber(str) }
- end
- for i=1,#str do
- str[i]=tonumber(str[i])
- end
- return str
-end
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+nestedbrackets+nestedparents+(1-comma))^0)
-local pattern=spaces*Ct(value*(separator*value)^0)
-function parsers.settings_to_array_obey_fences(str)
- return lpegmatch(pattern,str)
-end
-local cache_a={}
-local cache_b={}
-function parsers.groupedsplitat(symbol,withaction)
- if not symbol then
- symbol=","
- end
- local pattern=(withaction and cache_b or cache_a)[symbol]
- if not pattern then
- local symbols=S(symbol)
- local separator=space^0*symbols*space^0
- local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+(1-(space^0*(symbols+P(-1)))))^0)
- if withaction then
- local withvalue=Carg(1)*value/function(f,s) return f(s) end
- pattern=spaces*withvalue*(separator*withvalue)^0
- cache_b[symbol]=pattern
- else
- pattern=spaces*Ct(value*(separator*value)^0)
- cache_a[symbol]=pattern
- end
- end
- return pattern
-end
-local pattern_a=parsers.groupedsplitat(",",false)
-local pattern_b=parsers.groupedsplitat(",",true)
-function parsers.stripped_settings_to_array(str)
- if not str or str=="" then
- return {}
- else
- return lpegmatch(pattern_a,str)
- end
-end
-function parsers.process_stripped_settings(str,action)
- if not str or str=="" then
- return {}
- else
- return lpegmatch(pattern_b,str,1,action)
- end
-end
-local function set(t,v)
- t[#t+1]=v
-end
-local value=P(Carg(1)*value)/set
-local pattern=value*(separator*value)^0*Carg(1)
-function parsers.add_settings_to_array(t,str)
- return lpegmatch(pattern,str,nil,t)
-end
-function parsers.hash_to_string(h,separator,yes,no,strict,omit)
- if h then
- local t={}
- local tn=0
- local s=sortedkeys(h)
- omit=omit and tohash(omit)
- for i=1,#s do
- local key=s[i]
- if not omit or not omit[key] then
- local value=h[key]
- if type(value)=="boolean" then
- if yes and no then
- if value then
- tn=tn+1
- t[tn]=key..'='..yes
- elseif not strict then
- tn=tn+1
- t[tn]=key..'='..no
- end
- elseif value or not strict then
- tn=tn+1
- t[tn]=key..'='..tostring(value)
- end
- else
- tn=tn+1
- t[tn]=key..'='..value
- end
- end
- end
- return concat(t,separator or ",")
- else
- return ""
- end
-end
-function parsers.array_to_string(a,separator)
- if a then
- return concat(a,separator or ",")
- else
- return ""
- end
-end
-local pattern=Cf(Ct("")*Cg(C((1-S(", "))^1)*S(", ")^0*Cc(true))^1,rawset)
-function parsers.settings_to_set(str)
- return str and lpegmatch(pattern,str) or {}
-end
-hashes.settings_to_set=table.setmetatableindex(function(t,k)
- local v=k and lpegmatch(pattern,k) or {}
- t[k]=v
- return v
-end)
-getmetatable(hashes.settings_to_set).__mode="kv"
-function parsers.simple_hash_to_string(h,separator)
- local t={}
- local tn=0
- for k,v in sortedhash(h) do
- if v then
- tn=tn+1
- t[tn]=k
- end
- end
- return concat(t,separator or ",")
-end
-local str=Cs(lpegpatterns.unquoted)+C((1-whitespace-equal)^1)
-local setting=Cf(Carg(1)*(whitespace^0*Cg(str*whitespace^0*(equal*whitespace^0*str+Cc(""))))^1,rawset)
-local splitter=setting^1
-function parsers.options_to_hash(str,target)
- return str and lpegmatch(splitter,str,1,target or {}) or {}
-end
-local splitter=lpeg.tsplitat(" ")
-function parsers.options_to_array(str)
- return str and lpegmatch(splitter,str) or {}
-end
-local value=P(lbrace*C((nobrace+nestedbraces)^0)*rbrace)+C(digit^1*lparent*(noparent+nestedparents)^1*rparent)+C((nestedbraces+(1-comma))^1)
-local pattern_a=spaces*Ct(value*(separator*value)^0)
-local function repeater(n,str)
- if not n then
- return str
- else
- local s=lpegmatch(pattern_a,str)
- if n==1 then
- return unpack(s)
- else
- local t={}
- local tn=0
- for i=1,n do
- for j=1,#s do
- tn=tn+1
- t[tn]=s[j]
- end
- end
- return unpack(t)
- end
- end
-end
-local value=P(lbrace*C((nobrace+nestedbraces)^0)*rbrace)+(C(digit^1)/tonumber*lparent*Cs((noparent+nestedparents)^1)*rparent)/repeater+C((nestedbraces+(1-comma))^1)
-local pattern_b=spaces*Ct(value*(separator*value)^0)
-function parsers.settings_to_array_with_repeat(str,expand)
- if expand then
- return lpegmatch(pattern_b,str) or {}
- else
- return lpegmatch(pattern_a,str) or {}
- end
-end
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace
-local pattern=Ct((space+value)^0)
-function parsers.arguments_to_table(str)
- return lpegmatch(pattern,str)
-end
-function parsers.getparameters(self,class,parentclass,settings)
- local sc=self[class]
- if not sc then
- sc={}
- self[class]=sc
- if parentclass then
- local sp=self[parentclass]
- if not sp then
- sp={}
- self[parentclass]=sp
- end
- setmetatableindex(sc,sp)
- end
- end
- parsers.settings_to_hash(settings,sc)
-end
-function parsers.listitem(str)
- return gmatch(str,"[^, ]+")
-end
-local pattern=Cs { "start",
- start=V("one")+V("two")+V("three"),
- rest=(Cc(",")*V("thousand"))^0*(P(".")+endofstring)*anything^0,
- thousand=digit*digit*digit,
- one=digit*V("rest"),
- two=digit*digit*V("rest"),
- three=V("thousand")*V("rest"),
-}
-lpegpatterns.splitthousands=pattern
-function parsers.splitthousands(str)
- return lpegmatch(pattern,str) or str
-end
-local optionalwhitespace=whitespace^0
-lpegpatterns.words=Ct((Cs((1-punctuation-whitespace)^1)+anything)^1)
-lpegpatterns.sentences=Ct((optionalwhitespace*Cs((1-period)^0*period))^1)
-lpegpatterns.paragraphs=Ct((optionalwhitespace*Cs((whitespace^1*endofstring/""+1-(spacer^0*newline*newline))^1))^1)
-local dquote=P('"')
-local equal=P('=')
-local escape=P('\\')
-local separator=S(' ,')
-local key=C((1-equal)^1)
-local value=dquote*C((1-dquote-escape*dquote)^0)*dquote
-local pattern=Cf(Ct("")*(Cg(key*equal*value)*separator^0)^1,rawset)^0*P(-1)
-function parsers.keq_to_hash(str)
- if str and str~="" then
- return lpegmatch(pattern,str)
- else
- return {}
- end
-end
-local defaultspecification={ separator=",",quote='"' }
-function parsers.csvsplitter(specification)
- specification=specification and setmetatableindex(specification,defaultspecification) or defaultspecification
- local separator=specification.separator
- local quotechar=specification.quote
- local numbers=specification.numbers
- local separator=S(separator~="" and separator or ",")
- local whatever=C((1-separator-newline)^0)
- if quotechar and quotechar~="" then
- local quotedata=nil
- for chr in gmatch(quotechar,".") do
- local quotechar=P(chr)
- local quoteitem=(1-quotechar)^0
- local quoteword=quotechar*(numbers and (quoteitem/tonumber) or C(quoteitem))*quotechar
- if quotedata then
- quotedata=quotedata+quoteword
- else
- quotedata=quoteword
- end
- end
- whatever=quotedata+whatever
- end
- local parser=Ct((Ct(whatever*(separator*whatever)^0)*S("\n\r")^1)^0 )
- return function(data)
- return lpegmatch(parser,data)
- end
-end
-function parsers.rfc4180splitter(specification)
- specification=specification and setmetatableindex(specification,defaultspecification) or defaultspecification
- local numbers=specification.numbers
- local separator=specification.separator
- local quotechar=P(specification.quote)
- local dquotechar=quotechar*quotechar
-/specification.quote
- local separator=S(separator~="" and separator or ",")
- local whatever=(dquotechar+(1-quotechar))^0
- local escaped=quotechar*(numbers and (whatever/tonumber) or Cs(whatever))*quotechar
- local non_escaped=C((1-quotechar-newline-separator)^1)
- local field=escaped+non_escaped+Cc("")
- local record=Ct(field*(separator*field)^1)
- local headerline=record*Cp()
- local morerecords=(newline^(specification.strict and -1 or 1)*record)^0
- local headeryes=Ct(morerecords)
- local headernop=Ct(record*morerecords)
- return function(data,getheader)
- if getheader then
- local header,position=lpegmatch(headerline,data)
- local data=lpegmatch(headeryes,data,position)
- return data,header
- else
- return lpegmatch(headernop,data)
- end
- end
-end
-local function ranger(first,last,n,action)
- if not first then
- elseif last==true then
- for i=first,n or first do
- action(i)
- end
- elseif last then
- for i=first,last do
- action(i)
- end
- else
- action(first)
- end
-end
-local cardinal=lpegpatterns.cardinal/tonumber
-local spacers=lpegpatterns.spacer^0
-local endofstring=lpegpatterns.endofstring
-local stepper=spacers*(cardinal*(spacers*S(":-")*spacers*(cardinal+Cc(true) )+Cc(false) )*Carg(1)*Carg(2)/ranger*S(", ")^0 )^1
-local stepper=spacers*(cardinal*(spacers*S(":-")*spacers*(cardinal+(P("*")+endofstring)*Cc(true) )+Cc(false) )*Carg(1)*Carg(2)/ranger*S(", ")^0 )^1*endofstring
-function parsers.stepper(str,n,action)
- if type(n)=="function" then
- lpegmatch(stepper,str,1,false,n or print)
- else
- lpegmatch(stepper,str,1,n,action or print)
- end
-end
-local pattern_math=Cs((P("%")/"\\percent "+P("^")*Cc("{")*lpegpatterns.integer*Cc("}")+anything)^0)
-local pattern_text=Cs((P("%")/"\\percent "+(P("^")/"\\high")*Cc("{")*lpegpatterns.integer*Cc("}")+anything)^0)
-patterns.unittotex=pattern
-function parsers.unittotex(str,textmode)
- return lpegmatch(textmode and pattern_text or pattern_math,str)
-end
-local pattern=Cs((P("^")/"<sup>"*lpegpatterns.integer*Cc("</sup>")+anything)^0)
-function parsers.unittoxml(str)
- return lpegmatch(pattern,str)
-end
-local cache={}
-local spaces=lpegpatterns.space^0
-local dummy=function() end
-setmetatableindex(cache,function(t,k)
- local separator=P(k)
- local value=(1-separator)^0
- local pattern=spaces*C(value)*separator^0*Cp()
- t[k]=pattern
- return pattern
-end)
-local commalistiterator=cache[","]
-function parsers.iterator(str,separator)
- local n=#str
- if n==0 then
- return dummy
- else
- local pattern=separator and cache[separator] or commalistiterator
- local p=1
- return function()
- if p<=n then
- local s,e=lpegmatch(pattern,str,p)
- if e then
- p=e
- return s
- end
- end
- end
- end
-end
-local function initialize(t,name)
- local source=t[name]
- if source then
- local result={}
- for k,v in next,t[name] do
- result[k]=v
- end
- return result
- else
- return {}
- end
-end
-local function fetch(t,name)
- return t[name] or {}
-end
-local function process(result,more)
- for k,v in next,more do
- result[k]=v
- end
- return result
-end
-local name=C((1-S(", "))^1)
-local parser=(Carg(1)*name/initialize)*(S(", ")^1*(Carg(1)*name/fetch))^0
-local merge=Cf(parser,process)
-function parsers.mergehashes(hash,list)
- return lpegmatch(merge,list,1,hash)
-end
-function parsers.runtime(time)
- if not time then
- time=os.runtime()
- end
- local days=div(time,24*60*60)
- time=mod(time,24*60*60)
- local hours=div(time,60*60)
- time=mod(time,60*60)
- local minutes=div(time,60)
- local seconds=mod(time,60)
- return days,hours,minutes,seconds
-end
-local spacing=whitespace^0
-local apply=P("->")
-local method=C((1-apply)^1)
-local token=lbrace*C((1-rbrace)^1)*rbrace+C(anything^1)
-local pattern=spacing*(method*spacing*apply+Carg(1))*spacing*token
-function parsers.splitmethod(str,default)
- if str then
- return lpegmatch(pattern,str,1,default or false)
- else
- return default or false,""
- end
-end
-local p_year=lpegpatterns.digit^4/tonumber
-local pattern=Cf(Ct("")*(
- (Cg(Cc("year")*p_year)*S("-/")*Cg(Cc("month")*cardinal)*S("-/")*Cg(Cc("day")*cardinal)
- )+(Cg(Cc("day")*cardinal)*S("-/")*Cg(Cc("month")*cardinal)*S("-/")*Cg(Cc("year")*p_year)
- )
- )*P(" ")*Cg(Cc("hour")*cardinal)*P(":")*Cg(Cc("min")*cardinal)*(P(":")*Cg(Cc("sec")*cardinal))^-1
-,rawset)
-lpegpatterns.splittime=pattern
-function parsers.totime(str)
- return lpegmatch(pattern,str)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-fmt"] = package.loaded["util-fmt"] or true
-
--- original size: 2541, stripped down to: 1624
-
-if not modules then modules={} end modules ['util-fmt']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities=utilities or {}
-utilities.formatters=utilities.formatters or {}
-local formatters=utilities.formatters
-local concat,format=table.concat,string.format
-local tostring,type=tostring,type
-local strip=string.strip
-local lpegmatch=lpeg.match
-local stripper=lpeg.patterns.stripzeros
-function formatters.stripzeros(str)
- return lpegmatch(stripper,str)
-end
-function formatters.formatcolumns(result,between)
- if result and #result>0 then
- between=between or " "
- local widths,numbers={},{}
- local first=result[1]
- local n=#first
- for i=1,n do
- widths[i]=0
- end
- for i=1,#result do
- local r=result[i]
- for j=1,n do
- local rj=r[j]
- local tj=type(rj)
- if tj=="number" then
- numbers[j]=true
- rj=tostring(rj)
- elseif tj~="string" then
- rj=tostring(rj)
- r[j]=rj
- end
- local w=#rj
- if w>widths[j] then
- widths[j]=w
- end
- end
- end
- for i=1,n do
- local w=widths[i]
- if numbers[i] then
- if w>80 then
- widths[i]="%s"..between
- else
- widths[i]="%0"..w.."i"..between
- end
- else
- if w>80 then
- widths[i]="%s"..between
- elseif w>0 then
- widths[i]="%-"..w.."s"..between
- else
- widths[i]="%s"
- end
- end
- end
- local template=strip(concat(widths))
- for i=1,#result do
- local str=format(template,unpack(result[i]))
- result[i]=strip(str)
- end
- end
- return result
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-reset"] = package.loaded["util-soc-imp-reset"] or true
-
--- original size: 374, stripped down to: 282
-
-local loaded=package.loaded
-loaded["socket"]=nil
-loaded["copas"]=nil
-loaded["ltn12"]=nil
-loaded["mbox"]=nil
-loaded["mime"]=nil
-loaded["socket.url"]=nil
-loaded["socket.headers"]=nil
-loaded["socket.tp"]=nil
-loaded["socket.http"]=nil
-loaded["socket.ftp"]=nil
-loaded["socket.smtp"]=nil
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-socket"] = package.loaded["util-soc-imp-socket"] or true
-
--- original size: 4905, stripped down to: 3562
-
-
-local type,tostring,setmetatable=type,tostring,setmetatable
-local min=math.min
-local format=string.format
-local socket=socket or package.loaded.socket or require("socket.core")
-local connect=socket.connect
-local tcp4=socket.tcp4
-local tcp6=socket.tcp6
-local getaddrinfo=socket.dns.getaddrinfo
-local defaulthost="0.0.0.0"
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("socket")
- report(fmt,first,...)
- elseif fmt then
- fmt="socket: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-socket.report=report
-function socket.connect4(address,port,laddress,lport)
- return connect(address,port,laddress,lport,"inet")
-end
-function socket.connect6(address,port,laddress,lport)
- return connect(address,port,laddress,lport,"inet6")
-end
-function socket.bind(host,port,backlog)
- if host=="*" or host=="" then
- host=defaulthost
- end
- local addrinfo,err=getaddrinfo(host)
- if not addrinfo then
- return nil,err
- end
- for i=1,#addrinfo do
- local alt=addrinfo[i]
- local sock,err=(alt.family=="inet" and tcp4 or tcp6)()
- if not sock then
- return nil,err or "unknown error"
- end
- sock:setoption("reuseaddr",true)
- local res,err=sock:bind(alt.addr,port)
- if res then
- res,err=sock:listen(backlog)
- if res then
- return sock
- else
- sock:close()
- end
- else
- sock:close()
- end
- end
- return nil,"invalid address"
-end
-socket.try=socket.newtry()
-function socket.choose(list)
- return function(name,opt1,opt2)
- if type(name)~="string" then
- name,opt1,opt2="default",name,opt1
- end
- local f=list[name or "nil"]
- if f then
- return f(opt1,opt2)
- else
- report("error: unknown key '%s'",tostring(name))
- end
- end
-end
-local sourcet={}
-local sinkt={}
-socket.sourcet=sourcet
-socket.sinkt=sinkt
-socket.BLOCKSIZE=2048
-sinkt["close-when-done"]=function(sock)
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },
- {
- __call=function(self,chunk,err)
- if chunk then
- return sock:send(chunk)
- else
- sock:close()
- return 1
- end
- end
- }
- )
-end
-sinkt["keep-open"]=function(sock)
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },{
- __call=function(self,chunk,err)
- if chunk then
- return sock:send(chunk)
- else
- return 1
- end
- end
- }
- )
-end
-sinkt["default"]=sinkt["keep-open"]
-socket.sink=socket.choose(sinkt)
-sourcet["by-length"]=function(sock,length)
- local blocksize=socket.BLOCKSIZE
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },
- {
- __call=function()
- if length<=0 then
- return nil
- end
- local chunk,err=sock:receive(min(blocksize,length))
- if err then
- return nil,err
- end
- length=length-#chunk
- return chunk
- end
- }
- )
-end
-sourcet["until-closed"]=function(sock)
- local blocksize=socket.BLOCKSIZE
- local done=false
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },{
- __call=function()
- if done then
- return nil
- end
- local chunk,status,partial=sock:receive(blocksize)
- if not status then
- return chunk
- elseif status=="closed" then
- sock:close()
- done=true
- return partial
- else
- return nil,status
- end
- end
- }
- )
-end
-sourcet["default"]=sourcet["until-closed"]
-socket.source=socket.choose(sourcet)
-_G.socket=socket
-package.loaded["socket"]=socket
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-copas"] = package.loaded["util-soc-imp-copas"] or true
-
--- original size: 26186, stripped down to: 14893
-
-
-local socket=socket or require("socket")
-local ssl=ssl or nil
-local WATCH_DOG_TIMEOUT=120
-local UDP_DATAGRAM_MAX=8192
-local type,next,pcall,getmetatable,tostring=type,next,pcall,getmetatable,tostring
-local min,max,random=math.min,math.max,math.random
-local find=string.find
-local insert,remove=table.insert,table.remove
-local gettime=socket.gettime
-local selectsocket=socket.select
-local createcoroutine=coroutine.create
-local resumecoroutine=coroutine.resume
-local yieldcoroutine=coroutine.yield
-local runningcoroutine=coroutine.running
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("copas")
- report(fmt,first,...)
- elseif fmt then
- fmt="copas: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-local copas={
- _COPYRIGHT="Copyright (C) 2005-2016 Kepler Project",
- _DESCRIPTION="Coroutine Oriented Portable Asynchronous Services",
- _VERSION="Copas 2.0.1",
- autoclose=true,
- running=false,
- report=report,
- trace=false,
-}
-local function statushandler(status,...)
- if status then
- return...
- end
- local err=(...)
- if type(err)=="table" then
- err=err[1]
- end
- if copas.trace then
- report("error: %s",tostring(err))
- end
- return nil,err
-end
-function socket.protect(func)
- return function(...)
- return statushandler(pcall(func,...))
- end
-end
-function socket.newtry(finalizer)
- return function (...)
- local status=(...)
- if not status then
- local detail=select(2,...)
- pcall(finalizer,detail)
- if copas.trace then
- report("error: %s",tostring(detail))
- end
- return
- end
- return...
- end
-end
-local function newset()
- local reverse={}
- local set={}
- local queue={}
- setmetatable(set,{
- __index={
- insert=function(set,value)
- if not reverse[value] then
- local n=#set+1
- set[n]=value
- reverse[value]=n
- end
- end,
- remove=function(set,value)
- local index=reverse[value]
- if index then
- reverse[value]=nil
- local n=#set
- local top=set[n]
- set[n]=nil
- if top~=value then
- reverse[top]=index
- set[index]=top
- end
- end
- end,
- push=function (set,key,itm)
- local entry=queue[key]
- if entry==nil then
- queue[key]={ itm }
- else
- entry[#entry+1]=itm
- end
- end,
- pop=function (set,key)
- local top=queue[key]
- if top~=nil then
- local ret=remove(top,1)
- if top[1]==nil then
- queue[key]=nil
- end
- return ret
- end
- end
- }
- } )
- return set
-end
-local _sleeping={
- times={},
- cos={},
- lethargy={},
- insert=function()
- end,
- remove=function()
- end,
- push=function(self,sleeptime,co)
- if not co then
- return
- end
- if sleeptime<0 then
- self.lethargy[co]=true
- return
- else
- sleeptime=gettime()+sleeptime
- end
- local t=self.times
- local c=self.cos
- local i=1
- local n=#t
- while i<=n and t[i]<=sleeptime do
- i=i+1
- end
- insert(t,i,sleeptime)
- insert(c,i,co)
- end,
- getnext=
- function(self)
- local t=self.times
- local delay=t[1] and t[1]-gettime() or nil
- return delay and max(delay,0) or nil
- end,
- pop=
- function(self,time)
- local t=self.times
- local c=self.cos
- if #t==0 or time<t[1] then
- return
- end
- local co=c[1]
- remove(t,1)
- remove(c,1)
- return co
- end,
- wakeup=function(self,co)
- local let=self.lethargy
- if let[co] then
- self:push(0,co)
- let[co]=nil
- else
- local c=self.cos
- local t=self.times
- for i=1,#c do
- if c[i]==co then
- remove(c,i)
- remove(t,i)
- self:push(0,co)
- return
- end
- end
- end
- end
-}
-local _servers=newset()
-local _reading=newset()
-local _writing=newset()
-local _reading_log={}
-local _writing_log={}
-local _is_timeout={
- timeout=true,
- wantread=true,
- wantwrite=true,
-}
-local function isTCP(socket)
- return not find(tostring(socket),"^udp")
-end
-local function copasreceive(client,pattern,part)
- if not pattern or pattern=="" then
- pattern="*l"
- end
- local current_log=_reading_log
- local s,err
- repeat
- s,err,part=client:receive(pattern,part)
- if s or (not _is_timeout[err]) then
- current_log[client]=nil
- return s,err,part
- end
- if err=="wantwrite" then
- current_log=_writing_log
- current_log[client]=gettime()
- yieldcoroutine(client,_writing)
- else
- current_log=_reading_log
- current_log[client]=gettime()
- yieldcoroutine(client,_reading)
- end
- until false
-end
-local function copasreceivefrom(client,size)
- local s,err,port
- if not size or size==0 then
- size=UDP_DATAGRAM_MAX
- end
- repeat
- s,err,port=client:receivefrom(size)
- if s or err~="timeout" then
- _reading_log[client]=nil
- return s,err,port
- end
- _reading_log[client]=gettime()
- yieldcoroutine(client,_reading)
- until false
-end
-local function copasreceivepartial(client,pattern,part)
- if not pattern or pattern=="" then
- pattern="*l"
- end
- local logger=_reading_log
- local queue=_reading
- local s,err
- repeat
- s,err,part=client:receive(pattern,part)
- if s or (type(pattern)=="number" and part~="" and part) or not _is_timeout[err] then
- logger[client]=nil
- return s,err,part
- end
- if err=="wantwrite" then
- logger=_writing_log
- queue=_writing
- else
- logger=_reading_log
- queue=_reading
- end
- logger[client]=gettime()
- yieldcoroutine(client,queue)
- until false
-end
-local function copassend(client,data,from,to)
- if not from then
- from=1
- end
- local lastIndex=from-1
- local logger=_writing_log
- local queue=_writing
- local s,err
- repeat
- s,err,lastIndex=client:send(data,lastIndex+1,to)
- if random(100)>90 then
- logger[client]=gettime()
- yieldcoroutine(client,queue)
- end
- if s or not _is_timeout[err] then
- logger[client]=nil
- return s,err,lastIndex
- end
- if err=="wantread" then
- logger=_reading_log
- queue=_reading
- else
- logger=_writing_log
- queue=_writing
- end
- logger[client]=gettime()
- yieldcoroutine(client,queue)
- until false
-end
-local function copassendto(client,data,ip,port)
- repeat
- local s,err=client:sendto(data,ip,port)
- if random(100)>90 then
- _writing_log[client]=gettime()
- yieldcoroutine(client,_writing)
- end
- if s or err~="timeout" then
- _writing_log[client]=nil
- return s,err
- end
- _writing_log[client]=gettime()
- yieldcoroutine(client,_writing)
- until false
-end
-local function copasconnect(skt,host,port)
- skt:settimeout(0)
- local ret,err,tried_more_than_once
- repeat
- ret,err=skt:connect (host,port)
- if ret or (err~="timeout" and err~="Operation already in progress") then
- if not ret and err=="already connected" and tried_more_than_once then
- ret=1
- err=nil
- end
- _writing_log[skt]=nil
- return ret,err
- end
- tried_more_than_once=tried_more_than_once or true
- _writing_log[skt]=gettime()
- yieldcoroutine(skt,_writing)
- until false
-end
-local function copasdohandshake(skt,sslt)
- if not ssl then
- ssl=require("ssl")
- end
- if not ssl then
- report("error: no ssl library")
- return
- end
- local nskt,err=ssl.wrap(skt,sslt)
- if not nskt then
- report("error: %s",tostring(err))
- return
- end
- nskt:settimeout(0)
- local queue
- repeat
- local success,err=nskt:dohandshake()
- if success then
- return nskt
- elseif err=="wantwrite" then
- queue=_writing
- elseif err=="wantread" then
- queue=_reading
- else
- report("error: %s",tostring(err))
- return
- end
- yieldcoroutine(nskt,queue)
- until false
-end
-local function copasflush(client)
-end
-copas.connect=copassconnect
-copas.send=copassend
-copas.sendto=copassendto
-copas.receive=copasreceive
-copas.receivefrom=copasreceivefrom
-copas.copasreceivepartial=copasreceivepartial
-copas.copasreceivePartial=copasreceivepartial
-copas.dohandshake=copasdohandshake
-copas.flush=copasflush
-local function _skt_mt_tostring(self)
- return tostring(self.socket).." (copas wrapped)"
-end
-local _skt_mt_tcp_index={
- send=function(self,data,from,to)
- return copassend (self.socket,data,from,to)
- end,
- receive=function (self,pattern,prefix)
- if self.timeout==0 then
- return copasreceivePartial(self.socket,pattern,prefix)
- else
- return copasreceive(self.socket,pattern,prefix)
- end
- end,
- flush=function (self)
- return copasflush(self.socket)
- end,
- settimeout=function (self,time)
- self.timeout=time
- return true
- end,
- connect=function(self,...)
- local res,err=copasconnect(self.socket,...)
- if res and self.ssl_params then
- res,err=self:dohandshake()
- end
- return res,err
- end,
- close=function(self,...)
- return self.socket:close(...)
- end,
- bind=function(self,...)
- return self.socket:bind(...)
- end,
- getsockname=function(self,...)
- return self.socket:getsockname(...)
- end,
- getstats=function(self,...)
- return self.socket:getstats(...)
- end,
- setstats=function(self,...)
- return self.socket:setstats(...)
- end,
- listen=function(self,...)
- return self.socket:listen(...)
- end,
- accept=function(self,...)
- return self.socket:accept(...)
- end,
- setoption=function(self,...)
- return self.socket:setoption(...)
- end,
- getpeername=function(self,...)
- return self.socket:getpeername(...)
- end,
- shutdown=function(self,...)
- return self.socket:shutdown(...)
- end,
- dohandshake=function(self,sslt)
- self.ssl_params=sslt or self.ssl_params
- local nskt,err=copasdohandshake(self.socket,self.ssl_params)
- if not nskt then
- return nskt,err
- end
- self.socket=nskt
- return self
- end,
-}
-local _skt_mt_tcp={
- __tostring=_skt_mt_tostring,
- __index=_skt_mt_tcp_index,
-}
-local _skt_mt_udp_index={
- sendto=function (self,...)
- return copassendto(self.socket,...)
- end,
- receive=function (self,size)
- return copasreceive(self.socket,size or UDP_DATAGRAM_MAX)
- end,
- receivefrom=function (self,size)
- return copasreceivefrom(self.socket,size or UDP_DATAGRAM_MAX)
- end,
- setpeername=function(self,...)
- return self.socket:getpeername(...)
- end,
- setsockname=function(self,...)
- return self.socket:setsockname(...)
- end,
- close=function(self,...)
- return true
- end
-}
-local _skt_mt_udp={
- __tostring=_skt_mt_tostring,
- __index=_skt_mt_udp_index,
-}
-for k,v in next,_skt_mt_tcp_index do
- if not _skt_mt_udp_index[k] then
- _skt_mt_udp_index[k]=v
- end
-end
-local function wrap(skt,sslt)
- if getmetatable(skt)==_skt_mt_tcp or getmetatable(skt)==_skt_mt_udp then
- return skt
- end
- skt:settimeout(0)
- if isTCP(skt) then
- return setmetatable ({ socket=skt,ssl_params=sslt },_skt_mt_tcp)
- else
- return setmetatable ({ socket=skt },_skt_mt_udp)
- end
-end
-copas.wrap=wrap
-function copas.handler(handler,sslparams)
- return function (skt,...)
- skt=wrap(skt)
- if sslparams then
- skt:dohandshake(sslparams)
- end
- return handler(skt,...)
- end
-end
-local _errhandlers={}
-function copas.setErrorHandler(err)
- local co=runningcoroutine()
- if co then
- _errhandlers[co]=err
- end
-end
-local function _deferror (msg,co,skt)
- report("%s (%s) (%s)",msg,tostring(co),tostring(skt))
-end
-local function _doTick (co,skt,...)
- if not co then
- return
- end
- local ok,res,new_q=resumecoroutine(co,skt,...)
- if ok and res and new_q then
- new_q:insert(res)
- new_q:push(res,co)
- else
- if not ok then
- pcall(_errhandlers[co] or _deferror,res,co,skt)
- end
- if skt and copas.autoclose and isTCP(skt) then
- skt:close()
- end
- _errhandlers[co]=nil
- end
-end
-local function _accept(input,handler)
- local client=input:accept()
- if client then
- client:settimeout(0)
- local co=createcoroutine(handler)
- _doTick (co,client)
- end
- return client
-end
-local function _tickRead(skt)
- _doTick(_reading:pop(skt),skt)
-end
-local function _tickWrite(skt)
- _doTick(_writing:pop(skt),skt)
-end
-local function addTCPserver(server,handler,timeout)
- server:settimeout(timeout or 0)
- _servers[server]=handler
- _reading:insert(server)
-end
-local function addUDPserver(server,handler,timeout)
- server:settimeout(timeout or 0)
- local co=createcoroutine(handler)
- _reading:insert(server)
- _doTick(co,server)
-end
-function copas.addserver(server,handler,timeout)
- if isTCP(server) then
- addTCPserver(server,handler,timeout)
- else
- addUDPserver(server,handler,timeout)
- end
-end
-function copas.removeserver(server,keep_open)
- local s=server
- local mt=getmetatable(server)
- if mt==_skt_mt_tcp or mt==_skt_mt_udp then
- s=server.socket
- end
- _servers[s]=nil
- _reading:remove(s)
- if keep_open then
- return true
- end
- return server:close()
-end
-function copas.addthread(handler,...)
- local thread=createcoroutine(function(_,...) return handler(...) end)
- _doTick(thread,nil,...)
- return thread
-end
-local _tasks={}
-local function addtaskRead(task)
- task.def_tick=_tickRead
- _tasks[task]=true
-end
-local function addtaskWrite(task)
- task.def_tick=_tickWrite
- _tasks[task]=true
-end
-local function tasks()
- return next,_tasks
-end
-local _readable_t={
- events=function(self)
- local i=0
- return function ()
- i=i+1
- return self._evs[i]
- end
- end,
- tick=function(self,input)
- local handler=_servers[input]
- if handler then
- input=_accept(input,handler)
- else
- _reading:remove(input)
- self.def_tick(input)
- end
- end
-}
-addtaskRead(_readable_t)
-local _writable_t={
- events=function(self)
- local i=0
- return function()
- i=i+1
- return self._evs[i]
- end
- end,
- tick=function(self,output)
- _writing:remove(output)
- self.def_tick(output)
- end
-}
-addtaskWrite(_writable_t)
-local _sleeping_t={
- tick=function(self,time,...)
- _doTick(_sleeping:pop(time),...)
- end
-}
-function copas.sleep(sleeptime)
- yieldcoroutine((sleeptime or 0),_sleeping)
-end
-function copas.wakeup(co)
- _sleeping:wakeup(co)
-end
-local last_cleansing=0
-local function _select(timeout)
- local now=gettime()
- local r_evs,w_evs,err=selectsocket(_reading,_writing,timeout)
- _readable_t._evs=r_evs
- _writable_t._evs=w_evs
- if (last_cleansing-now)>WATCH_DOG_TIMEOUT then
- last_cleansing=now
- for skt,time in next,_reading_log do
- if not r_evs[skt] and (time-now)>WATCH_DOG_TIMEOUT then
- local n=#r_evs+1
- _reading_log[skt]=nil
- r_evs[n]=skt
- r_evs[skt]=n
- end
- end
- for skt,time in next,_writing_log do
- if not w_evs[skt] and (time-now)>WATCH_DOG_TIMEOUT then
- local n=#w_evs+1
- _writing_log[skt]=nil
- w_evs[n]=skt
- w_evs[skt]=n
- end
- end
- end
- if err=="timeout" and #r_evs+#w_evs>0 then
- return nil
- else
- return err
- end
-end
-local function copasfinished()
- return not (next(_reading) or next(_writing) or _sleeping:getnext())
-end
-local function copasstep(timeout)
- _sleeping_t:tick(gettime())
- local nextwait=_sleeping:getnext()
- if nextwait then
- timeout=timeout and min(nextwait,timeout) or nextwait
- elseif copasfinished() then
- return false
- end
- local err=_select(timeout)
- if err then
- if err=="timeout" then
- return false
- end
- return nil,err
- end
- for task in tasks() do
- for event in task:events() do
- task:tick(event)
- end
- end
- return true
-end
-copas.finished=copasfinished
-copas.step=copasstep
-function copas.loop(timeout)
- copas.running=true
- while not copasfinished() do
- copasstep(timeout)
- end
- copas.running=false
-end
-package.loaded["copas"]=copas
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-ltn12"] = package.loaded["util-soc-imp-ltn12"] or true
-
--- original size: 8709, stripped down to: 5411
-
-
-local select,unpack=select,unpack
-local insert,remove=table.insert,table.remove
-local sub=string.sub
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("ltn12")
- report(fmt,first,...)
- elseif fmt then
- fmt="ltn12: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-local filter={}
-local source={}
-local sink={}
-local pump={}
-local ltn12={
- _VERSION="LTN12 1.0.3",
- BLOCKSIZE=2048,
- filter=filter,
- source=source,
- sink=sink,
- pump=pump,
- report=report,
-}
-function filter.cycle(low,ctx,extra)
- if low then
- return function(chunk)
- return (low(ctx,chunk,extra))
- end
- end
-end
-function filter.chain(...)
- local arg={... }
- local n=select('#',...)
- local top=1
- local index=1
- local retry=""
- return function(chunk)
- retry=chunk and retry
- while true do
- local action=arg[index]
- if index==top then
- chunk=action(chunk)
- if chunk=="" or top==n then
- return chunk
- elseif chunk then
- index=index+1
- else
- top=top+1
- index=top
- end
- else
- chunk=action(chunk or "")
- if chunk=="" then
- index=index-1
- chunk=retry
- elseif chunk then
- if index==n then
- return chunk
- else
- index=index+1
- end
- else
- report("error: filter returned inappropriate 'nil'")
- return
- end
- end
- end
- end
-end
-local function empty()
- return nil
-end
-function source.empty()
- return empty
-end
-local function sourceerror(err)
- return function()
- return nil,err
- end
-end
-source.error=sourceerror
-function source.file(handle,io_err)
- if handle then
- local blocksize=ltn12.BLOCKSIZE
- return function()
- local chunk=handle:read(blocksize)
- if not chunk then
- handle:close()
- end
- return chunk
- end
- else
- return sourceerror(io_err or "unable to open file")
- end
-end
-function source.simplify(src)
- return function()
- local chunk,err_or_new=src()
- if err_or_new then
- src=err_or_new
- end
- if chunk then
- return chunk
- else
- return nil,err_or_new
- end
- end
-end
-function source.string(s)
- if s then
- local blocksize=ltn12.BLOCKSIZE
- local i=1
- return function()
- local nexti=i+blocksize
- local chunk=sub(s,i,nexti-1)
- i=nexti
- if chunk~="" then
- return chunk
- else
- return nil
- end
- end
- else return source.empty() end
-end
-function source.rewind(src)
- local t={}
- return function(chunk)
- if chunk then
- insert(t,chunk)
- else
- chunk=remove(t)
- if chunk then
- return chunk
- else
- return src()
- end
- end
- end
-end
-function source.chain(src,f,...)
- if... then
- f=filter.chain(f,...)
- end
- local last_in=""
- local last_out=""
- local state="feeding"
- local err
- return function()
- if not last_out then
- report("error: source is empty")
- return
- end
- while true do
- if state=="feeding" then
- last_in,err=src()
- if err then
- return nil,err
- end
- last_out=f(last_in)
- if not last_out then
- if last_in then
- report("error: filter returned inappropriate 'nil'")
- end
- return nil
- elseif last_out~="" then
- state="eating"
- if last_in then
- last_in=""
- end
- return last_out
- end
- else
- last_out=f(last_in)
- if last_out=="" then
- if last_in=="" then
- state="feeding"
- else
- report("error: filter returned nothing")
- return
- end
- elseif not last_out then
- if last_in then
- report("filter returned inappropriate 'nil'")
- end
- return nil
- else
- return last_out
- end
- end
- end
- end
-end
-function source.cat(...)
- local arg={... }
- local src=remove(arg,1)
- return function()
- while src do
- local chunk,err=src()
- if chunk then
- return chunk
- end
- if err then
- return nil,err
- end
- src=remove(arg,1)
- end
- end
-end
-function sink.table(t)
- if not t then
- t={}
- end
- local f=function(chunk,err)
- if chunk then
- insert(t,chunk)
- end
- return 1
- end
- return f,t
-end
-function sink.simplify(snk)
- return function(chunk,err)
- local ret,err_or_new=snk(chunk,err)
- if not ret then
- return nil,err_or_new
- end
- if err_or_new then
- snk=err_or_new
- end
- return 1
- end
-end
-local function null()
- return 1
-end
-function sink.null()
- return null
-end
-local function sinkerror(err)
- return function()
- return nil,err
- end
-end
-sink.error=sinkerror
-function sink.file(handle,io_err)
- if handle then
- return function(chunk,err)
- if not chunk then
- handle:close()
- return 1
- else
- return handle:write(chunk)
- end
- end
- else
- return sinkerror(io_err or "unable to open file")
- end
-end
-function sink.chain(f,snk,...)
- if... then
- local args={ f,snk,... }
- snk=remove(args,#args)
- f=filter.chain(unpack(args))
- end
- return function(chunk,err)
- if chunk~="" then
- local filtered=f(chunk)
- local done=chunk and ""
- while true do
- local ret,snkerr=snk(filtered,err)
- if not ret then
- return nil,snkerr
- end
- if filtered==done then
- return 1
- end
- filtered=f(done)
- end
- else
- return 1
- end
- end
-end
-function pump.step(src,snk)
- local chunk,src_err=src()
- local ret,snk_err=snk(chunk,src_err)
- if chunk and ret then
- return 1
- else
- return nil,src_err or snk_err
- end
-end
-function pump.all(src,snk,step)
- if not step then
- step=pump.step
- end
- while true do
- local ret,err=step(src,snk)
- if not ret then
- if err then
- return nil,err
- else
- return 1
- end
- end
- end
-end
-package.loaded["ltn12"]=ltn12
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-mime"] = package.loaded["util-soc-imp-mime"] or true
-
--- original size: 2373, stripped down to: 1931
-
-
-local type,tostring=type,tostring
-local mime=mime or package.loaded.mime or require("mime.core")
-local ltn12=ltn12 or package.loaded.ltn12 or require("ltn12")
-local filtercycle=ltn12.filter.cycle
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("mime")
- report(fmt,first,...)
- elseif fmt then
- fmt="mime: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-mime.report=report
-local encodet={}
-local decodet={}
-local wrapt={}
-mime.encodet=encodet
-mime.decodet=decodet
-mime.wrapt=wrapt
-local mime_b64=mime.b64
-local mime_qp=mime.qp
-local mime_unb64=mime.unb64
-local mime_unqp=mime.unqp
-local mime_wrp=mime.wrp
-local mime_qpwrp=mime.qpwrp
-local mime_eol=mime_eol
-local mime_dot=mime_dot
-encodet['base64']=function()
- return filtercycle(mime_b64,"")
-end
-encodet['quoted-printable']=function(mode)
- return filtercycle(mime_qp,"",mode=="binary" and "=0D=0A" or "\r\n")
-end
-decodet['base64']=function()
- return filtercycle(mime_unb64,"")
-end
-decodet['quoted-printable']=function()
- return filtercycle(mime_unqp,"")
-end
-local wraptext=function(length)
- if not length then
- length=76
- end
- return filtercycle(mime_wrp,length,length)
-end
-local wrapquoted=function()
- return filtercycle(mime_qpwrp,76,76)
-end
-wrapt['text']=wraptext
-wrapt['base64']=wraptext
-wrapt['default']=wraptext
-wrapt['quoted-printable']=wrapquoted
-function mime.normalize(marker)
- return filtercycle(mime_eol,0,marker)
-end
-function mime.stuff()
- return filtercycle(mime_dot,2)
-end
-local function choose(list)
- return function(name,opt1,opt2)
- if type(name)~="string" then
- name,opt1,opt2="default",name,opt1
- end
- local filter=list[name or "nil"]
- if filter then
- return filter(opt1,opt2)
- else
- report("error: unknown key '%s'",tostring(name))
- end
- end
-end
-mime.encode=choose(encodet)
-mime.decode=choose(decodet)
-mime.wrap=choose(wrapt)
-package.loaded["mime"]=mime
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-url"] = package.loaded["util-soc-imp-url"] or true
-
--- original size: 6863, stripped down to: 5269
-
-
-local tonumber,tostring,type=tonumber,tostring,type
-local gsub,sub,match,find,format,byte,char=string.gsub,string.sub,string.match,string.find,string.format,string.byte,string.char
-local insert=table.insert
-local socket=socket or require("socket")
-local url={
- _VERSION="URL 1.0.3",
-}
-socket.url=url
-function url.escape(s)
- return (gsub(s,"([^A-Za-z0-9_])",function(c)
- return format("%%%02x",byte(c))
- end))
-end
-local function make_set(t)
- local s={}
- for i=1,#t do
- s[t[i]]=true
- end
- return s
-end
-local segment_set=make_set {
- "-","_",".","!","~","*","'","(",
- ")",":","@","&","=","+","$",",",
-}
-local function protect_segment(s)
- return gsub(s,"([^A-Za-z0-9_])",function(c)
- if segment_set[c] then
- return c
- else
- return format("%%%02X",byte(c))
- end
- end)
-end
-function url.unescape(s)
- return (gsub(s,"%%(%x%x)",function(hex)
- return char(tonumber(hex,16))
- end))
-end
-local function absolute_path(base_path,relative_path)
- if find(relative_path,"^/") then
- return relative_path
- end
- local path=gsub(base_path,"[^/]*$","")
- path=path..relative_path
- path=gsub(path,"([^/]*%./)",function (s)
- if s~="./" then
- return s
- else
- return ""
- end
- end)
- path=gsub(path,"/%.$","/")
- local reduced
- while reduced~=path do
- reduced=path
- path=gsub(reduced,"([^/]*/%.%./)",function (s)
- if s~="../../" then
- return ""
- else
- return s
- end
- end)
- end
- path=gsub(reduced,"([^/]*/%.%.)$",function (s)
- if s~="../.." then
- return ""
- else
- return s
- end
- end)
- return path
-end
-function url.parse(url,default)
- local parsed={}
- for k,v in next,default or parsed do
- parsed[k]=v
- end
- if not url or url=="" then
- return nil,"invalid url"
- end
- url=gsub(url,"#(.*)$",function(f)
- parsed.fragment=f
- return ""
- end)
- url=gsub(url,"^([%w][%w%+%-%.]*)%:",function(s)
- parsed.scheme=s
- return ""
- end)
- url=gsub(url,"^//([^/]*)",function(n)
- parsed.authority=n
- return ""
- end)
- url=gsub(url,"%?(.*)",function(q)
- parsed.query=q
- return ""
- end)
- url=gsub(url,"%;(.*)",function(p)
- parsed.params=p
- return ""
- end)
- if url~="" then
- parsed.path=url
- end
- local authority=parsed.authority
- if not authority then
- return parsed
- end
- authority=gsub(authority,"^([^@]*)@",function(u)
- parsed.userinfo=u
- return ""
- end)
- authority=gsub(authority,":([^:%]]*)$",function(p)
- parsed.port=p
- return ""
- end)
- if authority~="" then
- parsed.host=match(authority,"^%[(.+)%]$") or authority
- end
- local userinfo=parsed.userinfo
- if not userinfo then
- return parsed
- end
- userinfo=gsub(userinfo,":([^:]*)$",function(p)
- parsed.password=p
- return ""
- end)
- parsed.user=userinfo
- return parsed
-end
-function url.build(parsed)
- local url=parsed.path or ""
- if parsed.params then
- url=url..";"..parsed.params
- end
- if parsed.query then
- url=url.."?"..parsed.query
- end
- local authority=parsed.authority
- if parsed.host then
- authority=parsed.host
- if find(authority,":") then
- authority="["..authority.."]"
- end
- if parsed.port then
- authority=authority..":"..tostring(parsed.port)
- end
- local userinfo=parsed.userinfo
- if parsed.user then
- userinfo=parsed.user
- if parsed.password then
- userinfo=userinfo..":"..parsed.password
- end
- end
- if userinfo then authority=userinfo.."@"..authority end
- end
- if authority then
- url="//"..authority..url
- end
- if parsed.scheme then
- url=parsed.scheme..":"..url
- end
- if parsed.fragment then
- url=url.."#"..parsed.fragment
- end
- return url
-end
-function url.absolute(base_url,relative_url)
- local base_parsed
- if type(base_url)=="table" then
- base_parsed=base_url
- base_url=url.build(base_parsed)
- else
- base_parsed=url.parse(base_url)
- end
- local relative_parsed=url.parse(relative_url)
- if not base_parsed then
- return relative_url
- elseif not relative_parsed then
- return base_url
- elseif relative_parsed.scheme then
- return relative_url
- else
- relative_parsed.scheme=base_parsed.scheme
- if not relative_parsed.authority then
- relative_parsed.authority=base_parsed.authority
- if not relative_parsed.path then
- relative_parsed.path=base_parsed.path
- if not relative_parsed.params then
- relative_parsed.params=base_parsed.params
- if not relative_parsed.query then
- relative_parsed.query=base_parsed.query
- end
- end
- else
- relative_parsed.path=absolute_path(base_parsed.path or "",relative_parsed.path)
- end
- end
- return url.build(relative_parsed)
- end
-end
-function url.parse_path(path)
- local parsed={}
- path=path or ""
- gsub(path,"([^/]+)",function (s)
- insert(parsed,s)
- end)
- for i=1,#parsed do
- parsed[i]=url.unescape(parsed[i])
- end
- if sub(path,1,1)=="/" then
- parsed.is_absolute=1
- end
- if sub(path,-1,-1)=="/" then
- parsed.is_directory=1
- end
- return parsed
-end
-function url.build_path(parsed,unsafe)
- local path=""
- local n=#parsed
- if unsafe then
- for i=1,n-1 do
- path=path..parsed[i].."/"
- end
- if n>0 then
- path=path..parsed[n]
- if parsed.is_directory then
- path=path.."/"
- end
- end
- else
- for i=1,n-1 do
- path=path..protect_segment(parsed[i]).."/"
- end
- if n>0 then
- path=path..protect_segment(parsed[n])
- if parsed.is_directory then
- path=path.."/"
- end
- end
- end
- if parsed.is_absolute then
- path="/"..path
- end
- return path
-end
-package.loaded["socket.url"]=url
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-headers"] = package.loaded["util-soc-imp-headers"] or true
-
--- original size: 5721, stripped down to: 3754
-
-
-local next=next
-local lower=string.lower
-local concat=table.concat
-local socket=socket or require("socket")
-local headers={}
-socket.headers=headers
-local canonic={
- ["accept"]="Accept",
- ["accept-charset"]="Accept-Charset",
- ["accept-encoding"]="Accept-Encoding",
- ["accept-language"]="Accept-Language",
- ["accept-ranges"]="Accept-Ranges",
- ["action"]="Action",
- ["alternate-recipient"]="Alternate-Recipient",
- ["age"]="Age",
- ["allow"]="Allow",
- ["arrival-date"]="Arrival-Date",
- ["authorization"]="Authorization",
- ["bcc"]="Bcc",
- ["cache-control"]="Cache-Control",
- ["cc"]="Cc",
- ["comments"]="Comments",
- ["connection"]="Connection",
- ["content-description"]="Content-Description",
- ["content-disposition"]="Content-Disposition",
- ["content-encoding"]="Content-Encoding",
- ["content-id"]="Content-ID",
- ["content-language"]="Content-Language",
- ["content-length"]="Content-Length",
- ["content-location"]="Content-Location",
- ["content-md5"]="Content-MD5",
- ["content-range"]="Content-Range",
- ["content-transfer-encoding"]="Content-Transfer-Encoding",
- ["content-type"]="Content-Type",
- ["cookie"]="Cookie",
- ["date"]="Date",
- ["diagnostic-code"]="Diagnostic-Code",
- ["dsn-gateway"]="DSN-Gateway",
- ["etag"]="ETag",
- ["expect"]="Expect",
- ["expires"]="Expires",
- ["final-log-id"]="Final-Log-ID",
- ["final-recipient"]="Final-Recipient",
- ["from"]="From",
- ["host"]="Host",
- ["if-match"]="If-Match",
- ["if-modified-since"]="If-Modified-Since",
- ["if-none-match"]="If-None-Match",
- ["if-range"]="If-Range",
- ["if-unmodified-since"]="If-Unmodified-Since",
- ["in-reply-to"]="In-Reply-To",
- ["keywords"]="Keywords",
- ["last-attempt-date"]="Last-Attempt-Date",
- ["last-modified"]="Last-Modified",
- ["location"]="Location",
- ["max-forwards"]="Max-Forwards",
- ["message-id"]="Message-ID",
- ["mime-version"]="MIME-Version",
- ["original-envelope-id"]="Original-Envelope-ID",
- ["original-recipient"]="Original-Recipient",
- ["pragma"]="Pragma",
- ["proxy-authenticate"]="Proxy-Authenticate",
- ["proxy-authorization"]="Proxy-Authorization",
- ["range"]="Range",
- ["received"]="Received",
- ["received-from-mta"]="Received-From-MTA",
- ["references"]="References",
- ["referer"]="Referer",
- ["remote-mta"]="Remote-MTA",
- ["reply-to"]="Reply-To",
- ["reporting-mta"]="Reporting-MTA",
- ["resent-bcc"]="Resent-Bcc",
- ["resent-cc"]="Resent-Cc",
- ["resent-date"]="Resent-Date",
- ["resent-from"]="Resent-From",
- ["resent-message-id"]="Resent-Message-ID",
- ["resent-reply-to"]="Resent-Reply-To",
- ["resent-sender"]="Resent-Sender",
- ["resent-to"]="Resent-To",
- ["retry-after"]="Retry-After",
- ["return-path"]="Return-Path",
- ["sender"]="Sender",
- ["server"]="Server",
- ["smtp-remote-recipient"]="SMTP-Remote-Recipient",
- ["status"]="Status",
- ["subject"]="Subject",
- ["te"]="TE",
- ["to"]="To",
- ["trailer"]="Trailer",
- ["transfer-encoding"]="Transfer-Encoding",
- ["upgrade"]="Upgrade",
- ["user-agent"]="User-Agent",
- ["vary"]="Vary",
- ["via"]="Via",
- ["warning"]="Warning",
- ["will-retry-until"]="Will-Retry-Until",
- ["www-authenticate"]="WWW-Authenticate",
- ["x-mailer"]="X-Mailer",
-}
-headers.canonic=setmetatable(canonic,{
- __index=function(t,k)
- socket.report("invalid header: %s",k)
- t[k]=k
- return k
- end
-})
-function headers.normalize(headers)
- if not headers then
- return {}
- end
- local normalized={}
- for k,v in next,headers do
- normalized[#normalized+1]=canonic[k]..": "..v
- end
- normalized[#normalized+1]=""
- normalized[#normalized+1]=""
- return concat(normalized,"\r\n")
-end
-function headers.lower(lowered,headers)
- if not lowered then
- return {}
- end
- if not headers then
- lowered,headers={},lowered
- end
- for k,v in next,headers do
- lowered[lower(k)]=v
- end
- return lowered
-end
-socket.headers=headers
-package.loaded["socket.headers"]=headers
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-tp"] = package.loaded["util-soc-imp-tp"] or true
-
--- original size: 3116, stripped down to: 2533
-
-
-local setmetatable,next,type,tonumber=setmetatable,next,type,tonumber
-local find,upper=string.find,string.upper
-local socket=socket or require("socket")
-local ltn12=ltn12 or require("ltn12")
-local skipsocket=socket.skip
-local sinksocket=socket.sink
-local tcpsocket=socket.tcp
-local ltn12pump=ltn12.pump
-local pumpall=ltn12pump.all
-local pumpstep=ltn12pump.step
-local tp={
- TIMEOUT=60,
-}
-socket.tp=tp
-local function get_reply(c)
- local line,err=c:receive()
- local reply=line
- if err then return
- nil,err
- end
- local code,sep=skipsocket(2,find(line,"^(%d%d%d)(.?)"))
- if not code then
- return nil,"invalid server reply"
- end
- if sep=="-" then
- local current
- repeat
- line,err=c:receive()
- if err then
- return nil,err
- end
- current,sep=skipsocket(2,find(line,"^(%d%d%d)(.?)"))
- reply=reply.."\n"..line
- until code==current and sep==" "
- end
- return code,reply
-end
-local methods={}
-local mt={ __index=methods }
-function methods.getpeername(self)
- return self.c:getpeername()
-end
-function methods.getsockname(self)
- return self.c:getpeername()
-end
-function methods.check(self,ok)
- local code,reply=get_reply(self.c)
- if not code then
- return nil,reply
- end
- local c=tonumber(code)
- local t=type(ok)
- if t=="function" then
- return ok(c,reply)
- elseif t=="table" then
- for i=1,#ok do
- if find(code,ok[i]) then
- return c,reply
- end
- end
- return nil,reply
- elseif find(code,ok) then
- return c,reply
- else
- return nil,reply
- end
-end
-function methods.command(self,cmd,arg)
- cmd=upper(cmd)
- if arg then
- cmd=cmd.." "..arg.."\r\n"
- else
- cmd=cmd.."\r\n"
- end
- return self.c:send(cmd)
-end
-function methods.sink(self,snk,pat)
- local chunk,err=self.c:receive(pat)
- return snk(chunk,err)
-end
-function methods.send(self,data)
- return self.c:send(data)
-end
-function methods.receive(self,pat)
- return self.c:receive(pat)
-end
-function methods.getfd(self)
- return self.c:getfd()
-end
-function methods.dirty(self)
- return self.c:dirty()
-end
-function methods.getcontrol(self)
- return self.c
-end
-function methods.source(self,source,step)
- local sink=sinksocket("keep-open",self.c)
- local ret,err=pumpall(source,sink,step or pumpstep)
- return ret,err
-end
-function methods.close(self)
- self.c:close()
- return 1
-end
-function tp.connect(host,port,timeout,create)
- local c,e=(create or tcpsocket)()
- if not c then
- return nil,e
- end
- c:settimeout(timeout or tp.TIMEOUT)
- local r,e=c:connect(host,port)
- if not r then
- c:close()
- return nil,e
- end
- return setmetatable({ c=c },mt)
-end
-package.loaded["socket.tp"]=tp
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-http"] = package.loaded["util-soc-imp-http"] or true
-
--- original size: 12624, stripped down to: 9598
-
-
-local tostring,tonumber,setmetatable,next,type=tostring,tonumber,setmetatable,next,type
-local find,lower,format,gsub,match=string.find,string.lower,string.format,string.gsub,string.match
-local concat=table.concat
-local socket=socket or require("socket")
-local url=socket.url or require("socket.url")
-local ltn12=ltn12 or require("ltn12")
-local mime=mime or require("mime")
-local headers=socket.headers or require("socket.headers")
-local normalizeheaders=headers.normalize
-local parseurl=url.parse
-local buildurl=url.build
-local absoluteurl=url.absolute
-local unescapeurl=url.unescape
-local skipsocket=socket.skip
-local sinksocket=socket.sink
-local sourcesocket=socket.source
-local trysocket=socket.try
-local tcpsocket=socket.tcp
-local newtrysocket=socket.newtry
-local protectsocket=socket.protect
-local emptysource=ltn12.source.empty
-local stringsource=ltn12.source.string
-local rewindsource=ltn12.source.rewind
-local pumpstep=ltn12.pump.step
-local pumpall=ltn12.pump.all
-local sinknull=ltn12.sink.null
-local sinktable=ltn12.sink.table
-local lowerheaders=headers.lower
-local mimeb64=mime.b64
-local http={
- TIMEOUT=60,
- USERAGENT=socket._VERSION,
-}
-socket.http=http
-local PORT=80
-local SCHEMES={
- http=true,
-}
-local function receiveheaders(sock,headers)
- if not headers then
- headers={}
- end
- local line,err=sock:receive("*l")
- if err then
- return nil,err
- end
- while line~="" do
- local name,value=skipsocket(2,find(line,"^(.-):%s*(.*)"))
- if not (name and value) then
- return nil,"malformed reponse headers"
- end
- name=lower(name)
- line,err=sock:receive("*l")
- if err then
- return nil,err
- end
- while find(line,"^%s") do
- value=value..line
- line=sock:receive("*l")
- if err then
- return nil,err
- end
- end
- local found=headers[name]
- if found then
- value=found..", "..value
- end
- headers[name]=value
- end
- return headers
-end
-socket.sourcet["http-chunked"]=function(sock,headers)
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },{
- __call=function()
- local line,err=sock:receive("*l")
- if err then
- return nil,err
- end
- local size=tonumber(gsub(line,";.*",""),16)
- if not size then
- return nil,"invalid chunk size"
- end
- if size>0 then
- local chunk,err,part=sock:receive(size)
- if chunk then
- sock:receive("*a")
- end
- return chunk,err
- else
- headers,err=receiveheaders(sock,headers)
- if not headers then
- return nil,err
- end
- end
- end
- }
- )
-end
-socket.sinkt["http-chunked"]=function(sock)
- return setmetatable(
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },
- {
- __call=function(self,chunk,err)
- if not chunk then
- chunk=""
- end
- return sock:send(format("%X\r\n%s\r\n",#chunk,chunk))
- end
- })
-end
-local methods={}
-local mt={ __index=methods }
-local function openhttp(host,port,create)
- local c=trysocket((create or tcpsocket)())
- local h=setmetatable({ c=c },mt)
- local try=newtrysocket(function() h:close() end)
- h.try=try
- try(c:settimeout(http.TIMEOUT))
- try(c:connect(host,port or PORT))
- return h
-end
-http.open=openhttp
-function methods.sendrequestline(self,method,uri)
- local requestline=format("%s %s HTTP/1.1\r\n",method or "GET",uri)
- return self.try(self.c:send(requestline))
-end
-function methods.sendheaders(self,headers)
- self.try(self.c:send(normalizeheaders(headers)))
- return 1
-end
-function methods.sendbody(self,headers,source,step)
- if not source then
- source=emptysource()
- end
- if not step then
- step=pumpstep
- end
- local mode="http-chunked"
- if headers["content-length"] then
- mode="keep-open"
- end
- return self.try(pumpall(source,sinksocket(mode,self.c),step))
-end
-function methods.receivestatusline(self)
- local try=self.try
- local status=try(self.c:receive(5))
- if status~="HTTP/" then
- return nil,status
- end
- status=try(self.c:receive("*l",status))
- local code=skipsocket(2,find(status,"HTTP/%d*%.%d* (%d%d%d)"))
- return try(tonumber(code),status)
-end
-function methods.receiveheaders(self)
- return self.try(receiveheaders(self.c))
-end
-function methods.receivebody(self,headers,sink,step)
- if not sink then
- sink=sinknull()
- end
- if not step then
- step=pumpstep
- end
- local length=tonumber(headers["content-length"])
- local encoding=headers["transfer-encoding"]
- local mode="default"
- if encoding and encoding~="identity" then
- mode="http-chunked"
- elseif length then
- mode="by-length"
- end
- return self.try(pumpall(sourcesocket(mode,self.c,length),sink,step))
-end
-function methods.receive09body(self,status,sink,step)
- local source=rewindsource(sourcesocket("until-closed",self.c))
- source(status)
- return self.try(pumpall(source,sink,step))
-end
-function methods.close(self)
- return self.c:close()
-end
-local function adjusturi(request)
- if not request.proxy and not http.PROXY then
- request={
- path=trysocket(request.path,"invalid path 'nil'"),
- params=request.params,
- query=request.query,
- fragment=request.fragment,
- }
- end
- return buildurl(request)
-end
-local function adjustheaders(request)
- local headers={
- ["user-agent"]=http.USERAGENT,
- ["host"]=gsub(request.authority,"^.-@",""),
- ["connection"]="close, TE",
- ["te"]="trailers"
- }
- local username=request.user
- local password=request.password
- if username and password then
- headers["authorization"]="Basic "..(mimeb64(username..":"..unescapeurl(password)))
- end
- local proxy=request.proxy or http.PROXY
- if proxy then
- proxy=parseurl(proxy)
- local username=proxy.user
- local password=proxy.password
- if username and password then
- headers["proxy-authorization"]="Basic "..(mimeb64(username..":"..password))
- end
- end
- local requestheaders=request.headers
- if requestheaders then
- headers=lowerheaders(headers,requestheaders)
- end
- return headers
-end
-local default={
- host="",
- port=PORT,
- path="/",
- scheme="http"
-}
-local function adjustrequest(originalrequest)
- local url=originalrequest.url
- local request=url and parseurl(url,default) or {}
- for k,v in next,originalrequest do
- request[k]=v
- end
- local host=request.host
- local port=request.port
- local uri=request.uri
- if not host or host=="" then
- trysocket(nil,"invalid host '"..tostring(host).."'")
- end
- if port=="" then
- request.port=PORT
- end
- if not uri or uri=="" then
- request.uri=adjusturi(request)
- end
- request.headers=adjustheaders(request)
- local proxy=request.proxy or http.PROXY
- if proxy then
- proxy=parseurl(proxy)
- request.host=proxy.host
- request.port=proxy.port or 3128
- end
- return request
-end
-local maxredericts=4
-local validredirects={ [301]=true,[302]=true,[303]=true,[307]=true }
-local validmethods={ [false]=true,GET=true,HEAD=true }
-local function shouldredirect(request,code,headers)
- local location=headers.location
- if not location then
- return false
- end
- location=gsub(location,"%s","")
- if location=="" then
- return false
- end
- local scheme=match(location,"^([%w][%w%+%-%.]*)%:")
- if scheme and not SCHEMES[scheme] then
- return false
- end
- local method=request.method
- local redirect=request.redirect
- local redirects=request.nredirects or 0
- return redirect and validredirects[code] and validmethods[method] and redirects<=maxredericts
-end
-local function shouldreceivebody(request,code)
- if request.method=="HEAD" then
- return nil
- end
- if code==204 or code==304 then
- return nil
- end
- if code>=100 and code<200 then
- return nil
- end
- return 1
-end
-local tredirect,trequest,srequest
-tredirect=function(request,location)
- local result,code,headers,status=trequest {
- url=absoluteurl(request.url,location),
- source=request.source,
- sink=request.sink,
- headers=request.headers,
- proxy=request.proxy,
- nredirects=(request.nredirects or 0)+1,
- create=request.create,
- }
- if not headers then
- headers={}
- end
- if not headers.location then
- headers.location=location
- end
- return result,code,headers,status
-end
-trequest=function(originalrequest)
- local request=adjustrequest(originalrequest)
- local connection=openhttp(request.host,request.port,request.create)
- local headers=request.headers
- connection:sendrequestline(request.method,request.uri)
- connection:sendheaders(headers)
- if request.source then
- connection:sendbody(headers,request.source,request.step)
- end
- local code,status=connection:receivestatusline()
- if not code then
- connection:receive09body(status,request.sink,request.step)
- return 1,200
- end
- while code==100 do
- headers=connection:receiveheaders()
- code,status=connection:receivestatusline()
- end
- headers=connection:receiveheaders()
- if shouldredirect(request,code,headers) and not request.source then
- connection:close()
- return tredirect(originalrequest,headers.location)
- end
- if shouldreceivebody(request,code) then
- connection:receivebody(headers,request.sink,request.step)
- end
- connection:close()
- return 1,code,headers,status
-end
-local function genericform(url,body)
- local buffer={}
- local request={
- url=url,
- sink=sinktable(buffer),
- target=buffer,
- }
- if body then
- request.source=stringsource(body)
- request.method="POST"
- request.headers={
- ["content-length"]=#body,
- ["content-type"]="application/x-www-form-urlencoded"
- }
- end
- return request
-end
-http.genericform=genericform
-srequest=function(url,body)
- local request=genericform(url,body)
- local _,code,headers,status=trequest(request)
- return concat(request.target),code,headers,status
-end
-http.request=protectsocket(function(request,body)
- if type(request)=="string" then
- return srequest(request,body)
- else
- return trequest(request)
- end
-end)
-package.loaded["socket.http"]=http
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-ftp"] = package.loaded["util-soc-imp-ftp"] or true
-
--- original size: 10357, stripped down to: 8548
-
-
-local setmetatable,type,next=setmetatable,type,next
-local find,format,gsub,match=string.find,string.format,string.gsub,string.match
-local concat=table.concat
-local mod=math.mod
-local socket=socket or require("socket")
-local url=socket.url or require("socket.url")
-local tp=socket.tp or require("socket.tp")
-local ltn12=ltn12 or require("ltn12")
-local tcpsocket=socket.tcp
-local trysocket=socket.try
-local skipsocket=socket.skip
-local sinksocket=socket.sink
-local selectsocket=socket.select
-local bindsocket=socket.bind
-local newtrysocket=socket.newtry
-local sourcesocket=socket.source
-local protectsocket=socket.protect
-local parseurl=url.parse
-local unescapeurl=url.unescape
-local pumpall=ltn12.pump.all
-local pumpstep=ltn12.pump.step
-local sourcestring=ltn12.source.string
-local sinktable=ltn12.sink.table
-local ftp={
- TIMEOUT=60,
- USER="ftp",
- PASSWORD="anonymous@anonymous.org",
-}
-socket.ftp=ftp
-local PORT=21
-local methods={}
-local mt={ __index=methods }
-function ftp.open(server,port,create)
- local tp=trysocket(tp.connect(server,port or PORT,ftp.TIMEOUT,create))
- local f=setmetatable({ tp=tp },metat)
- f.try=newtrysocket(function() f:close() end)
- return f
-end
-function methods.portconnect(self)
- local try=self.try
- local server=self.server
- try(server:settimeout(ftp.TIMEOUT))
- self.data=try(server:accept())
- try(self.data:settimeout(ftp.TIMEOUT))
-end
-function methods.pasvconnect(self)
- local try=self.try
- self.data=try(tcpsocket())
- self(self.data:settimeout(ftp.TIMEOUT))
- self(self.data:connect(self.pasvt.address,self.pasvt.port))
-end
-function methods.login(self,user,password)
- local try=self.try
- local tp=self.tp
- try(tp:command("user",user or ftp.USER))
- local code,reply=try(tp:check{"2..",331})
- if code==331 then
- try(tp:command("pass",password or ftp.PASSWORD))
- try(tp:check("2.."))
- end
- return 1
-end
-function methods.pasv(self)
- local try=self.try
- local tp=self.tp
- try(tp:command("pasv"))
- local code,reply=try(self.tp:check("2.."))
- local pattern="(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)"
- local a,b,c,d,p1,p2=skipsocket(2,find(reply,pattern))
- try(a and b and c and d and p1 and p2,reply)
- local address=format("%d.%d.%d.%d",a,b,c,d)
- local port=p1*256+p2
- local server=self.server
- self.pasvt={
- address=address,
- port=port,
- }
- if server then
- server:close()
- self.server=nil
- end
- return address,port
-end
-function methods.epsv(self)
- local try=self.try
- local tp=self.tp
- try(tp:command("epsv"))
- local code,reply=try(tp:check("229"))
- local pattern="%((.)(.-)%1(.-)%1(.-)%1%)"
- local d,prt,address,port=match(reply,pattern)
- try(port,"invalid epsv response")
- local address=tp:getpeername()
- local server=self.server
- self.pasvt={
- address=address,
- port=port,
- }
- if self.server then
- server:close()
- self.server=nil
- end
- return address,port
-end
-function methods.port(self,address,port)
- local try=self.try
- local tp=self.tp
- self.pasvt=nil
- if not address then
- address,port=try(tp:getsockname())
- self.server=try(bindsocket(address,0))
- address,port=try(self.server:getsockname())
- try(self.server:settimeout(ftp.TIMEOUT))
- end
- local pl=mod(port,256)
- local ph=(port-pl)/256
- local arg=gsub(format("%s,%d,%d",address,ph,pl),"%.",",")
- try(tp:command("port",arg))
- try(tp:check("2.."))
- return 1
-end
-function methods.eprt(self,family,address,port)
- local try=self.try
- local tp=self.tp
- self.pasvt=nil
- if not address then
- address,port=try(tp:getsockname())
- self.server=try(bindsocket(address,0))
- address,port=try(self.server:getsockname())
- try(self.server:settimeout(ftp.TIMEOUT))
- end
- local arg=format("|%s|%s|%d|",family,address,port)
- try(tp:command("eprt",arg))
- try(tp:check("2.."))
- return 1
-end
-function methods.send(self,sendt)
- local try=self.try
- local tp=self.tp
- try(self.pasvt or self.server,"need port or pasv first")
- if self.pasvt then
- self:pasvconnect()
- end
- local argument=sendt.argument or unescapeurl(gsub(sendt.path or "","^[/\\]",""))
- if argument=="" then
- argument=nil
- end
- local command=sendt.command or "stor"
- try(tp:command(command,argument))
- local code,reply=try(tp:check{"2..","1.."})
- if not self.pasvt then
- self:portconnect()
- end
- local step=sendt.step or pumpstep
- local readt={ tp }
- local checkstep=function(src,snk)
- local readyt=selectsocket(readt,nil,0)
- if readyt[tp] then
- code=try(tp:check("2.."))
- end
- return step(src,snk)
- end
- local sink=sinksocket("close-when-done",self.data)
- try(pumpall(sendt.source,sink,checkstep))
- if find(code,"1..") then
- try(tp:check("2.."))
- end
- self.data:close()
- local sent=skipsocket(1,self.data:getstats())
- self.data=nil
- return sent
-end
-function methods.receive(self,recvt)
- local try=self.try
- local tp=self.tp
- try(self.pasvt or self.server,"need port or pasv first")
- if self.pasvt then self:pasvconnect() end
- local argument=recvt.argument or unescapeurl(gsub(recvt.path or "","^[/\\]",""))
- if argument=="" then
- argument=nil
- end
- local command=recvt.command or "retr"
- try(tp:command(command,argument))
- local code,reply=try(tp:check{"1..","2.."})
- if code>=200 and code<=299 then
- recvt.sink(reply)
- return 1
- end
- if not self.pasvt then
- self:portconnect()
- end
- local source=sourcesocket("until-closed",self.data)
- local step=recvt.step or pumpstep
- try(pumpall(source,recvt.sink,step))
- if find(code,"1..") then
- try(tp:check("2.."))
- end
- self.data:close()
- self.data=nil
- return 1
-end
-function methods.cwd(self,dir)
- local try=self.try
- local tp=self.tp
- try(tp:command("cwd",dir))
- try(tp:check(250))
- return 1
-end
-function methods.type(self,typ)
- local try=self.try
- local tp=self.tp
- try(tp:command("type",typ))
- try(tp:check(200))
- return 1
-end
-function methods.greet(self)
- local try=self.try
- local tp=self.tp
- local code=try(tp:check{"1..","2.."})
- if find(code,"1..") then
- try(tp:check("2.."))
- end
- return 1
-end
-function methods.quit(self)
- local try=self.try
- try(self.tp:command("quit"))
- try(self.tp:check("2.."))
- return 1
-end
-function methods.close(self)
- local data=self.data
- if data then
- data:close()
- end
- local server=self.server
- if server then
- server:close()
- end
- local tp=self.tp
- if tp then
- tp:close()
- end
-end
-local function override(t)
- if t.url then
- local u=parseurl(t.url)
- for k,v in next,t do
- u[k]=v
- end
- return u
- else
- return t
- end
-end
-local function tput(putt)
- putt=override(putt)
- local host=putt.host
- trysocket(host,"missing hostname")
- local f=ftp.open(host,putt.port,putt.create)
- f:greet()
- f:login(putt.user,putt.password)
- local typ=putt.type
- if typ then
- f:type(typ)
- end
- f:epsv()
- local sent=f:send(putt)
- f:quit()
- f:close()
- return sent
-end
-local default={
- path="/",
- scheme="ftp",
-}
-local function genericform(u)
- local t=trysocket(parseurl(u,default))
- trysocket(t.scheme=="ftp","wrong scheme '"..t.scheme.."'")
- trysocket(t.host,"missing hostname")
- local pat="^type=(.)$"
- if t.params then
- local typ=skipsocket(2,find(t.params,pat))
- t.type=typ
- trysocket(typ=="a" or typ=="i","invalid type '"..typ.."'")
- end
- return t
-end
-ftp.genericform=genericform
-local function sput(u,body)
- local putt=genericform(u)
- putt.source=sourcestring(body)
- return tput(putt)
-end
-ftp.put=protectsocket(function(putt,body)
- if type(putt)=="string" then
- return sput(putt,body)
- else
- return tput(putt)
- end
-end)
-local function tget(gett)
- gett=override(gett)
- local host=gett.host
- trysocket(host,"missing hostname")
- local f=ftp.open(host,gett.port,gett.create)
- f:greet()
- f:login(gett.user,gett.password)
- if gett.type then
- f:type(gett.type)
- end
- f:epsv()
- f:receive(gett)
- f:quit()
- return f:close()
-end
-local function sget(u)
- local gett=genericform(u)
- local t={}
- gett.sink=sinktable(t)
- tget(gett)
- return concat(t)
-end
-ftp.command=protectsocket(function(cmdt)
- cmdt=override(cmdt)
- local command=cmdt.command
- local argument=cmdt.argument
- local check=cmdt.check
- local host=cmdt.host
- trysocket(host,"missing hostname")
- trysocket(command,"missing command")
- local f=ftp.open(host,cmdt.port,cmdt.create)
- local try=f.try
- local tp=f.tp
- f:greet()
- f:login(cmdt.user,cmdt.password)
- if type(command)=="table" then
- local argument=argument or {}
- for i=1,#command do
- local cmd=command[i]
- try(tp:command(cmd,argument[i]))
- if check and check[i] then
- try(tp:check(check[i]))
- end
- end
- else
- try(tp:command(command,argument))
- if check then
- try(tp:check(check))
- end
- end
- f:quit()
- return f:close()
-end)
-ftp.get=protectsocket(function(gett)
- if type(gett)=="string" then
- return sget(gett)
- else
- return tget(gett)
- end
-end)
-package.loaded["socket.ftp"]=ftp
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-smtp"] = package.loaded["util-soc-imp-smtp"] or true
-
--- original size: 7018, stripped down to: 5883
-
-
-local type,setmetatable,next=type,setmetatable,next
-local find,lower,format=string.find,string.lower,string.format
-local osdate,osgetenv=os.date,os.getenv
-local random=math.random
-local socket=socket or require("socket")
-local headers=socket.headers or require("socket.headers")
-local ltn12=ltn12 or require("ltn12")
-local tp=socket.tp or require("socket.tp")
-local mime=mime or require("mime")
-local mimeb64=mime.b64
-local mimestuff=mime.stuff
-local skipsocket=socket.skip
-local trysocket=socket.try
-local newtrysocket=socket.newtry
-local protectsocket=socket.protect
-local normalizeheaders=headers.normalize
-local lowerheaders=headers.lower
-local createcoroutine=coroutine.create
-local resumecoroutine=coroutine.resume
-local yieldcoroutine=coroutine.resume
-local smtp={
- TIMEOUT=60,
- SERVER="localhost",
- PORT=25,
- DOMAIN=osgetenv("SERVER_NAME") or "localhost",
- ZONE="-0000",
-}
-socket.smtp=smtp
-local methods={}
-local mt={ __index=methods }
-function methods.greet(self,domain)
- local try=self.try
- local tp=self.tp
- try(tp:check("2.."))
- try(tp:command("EHLO",domain or _M.DOMAIN))
- return skipsocket(1,try(tp:check("2..")))
-end
-function methods.mail(self,from)
- local try=self.try
- local tp=self.tp
- try(tp:command("MAIL","FROM:"..from))
- return try(tp:check("2.."))
-end
-function methods.rcpt(self,to)
- local try=self.try
- local tp=self.tp
- try(tp:command("RCPT","TO:"..to))
- return try(tp:check("2.."))
-end
-function methods.data(self,src,step)
- local try=self.try
- local tp=self.tp
- try(tp:command("DATA"))
- try(tp:check("3.."))
- try(tp:source(src,step))
- try(tp:send("\r\n.\r\n"))
- return try(tp:check("2.."))
-end
-function methods.quit(self)
- local try=self.try
- local tp=self.tp
- try(tp:command("QUIT"))
- return try(tp:check("2.."))
-end
-function methods.close(self)
- return self.tp:close()
-end
-function methods.login(self,user,password)
- local try=self.try
- local tp=self.tp
- try(tp:command("AUTH","LOGIN"))
- try(tp:check("3.."))
- try(tp:send(mimeb64(user).."\r\n"))
- try(tp:check("3.."))
- try(tp:send(mimeb64(password).."\r\n"))
- return try(tp:check("2.."))
-end
-function methods.plain(self,user,password)
- local try=self.try
- local tp=self.tp
- local auth="PLAIN "..mimeb64("\0"..user.."\0"..password)
- try(tp:command("AUTH",auth))
- return try(tp:check("2.."))
-end
-function methods.auth(self,user,password,ext)
- if not user or not password then
- return 1
- end
- local try=self.try
- if find(ext,"AUTH[^\n]+LOGIN") then
- return self:login(user,password)
- elseif find(ext,"AUTH[^\n]+PLAIN") then
- return self:plain(user,password)
- else
- try(nil,"authentication not supported")
- end
-end
-function methods.send(self,mail)
- self:mail(mail.from)
- local receipt=mail.rcpt
- if type(receipt)=="table" then
- for i=1,#receipt do
- self:rcpt(receipt[i])
- end
- elseif receipt then
- self:rcpt(receipt)
- end
- self:data(ltn12.source.chain(mail.source,mimestuff()),mail.step)
-end
-local function opensmtp(self,server,port,create)
- if not server or server=="" then
- server=smtp.SERVER
- end
- if not port or port=="" then
- port=smtp.PORT
- end
- local s={
- tp=trysocket(tp.connect(server,port,smtp.TIMEOUT,create)),
- try=newtrysocket(function()
- s:close()
- end),
- }
- setmetatable(s,mt)
- return s
-end
-smtp.open=opensmtp
-local nofboundaries=0
-local function newboundary()
- nofboundaries=nofboundaries+1
- return format('%s%05d==%05u',osdate('%d%m%Y%H%M%S'),random(0,99999),nofboundaries)
-end
-local send_message
-local function send_headers(headers)
- yieldcoroutine(normalizeheaders(headers))
-end
-local function send_multipart(message)
- local boundary=newboundary()
- local headers=lowerheaders(message.headers)
- local body=message.body
- local preamble=body.preamble
- local epilogue=body.epilogue
- local content=headers['content-type'] or 'multipart/mixed'
- headers['content-type']=content..'; boundary="'..boundary..'"'
- send_headers(headers)
- if preamble then
- yieldcoroutine(preamble)
- yieldcoroutine("\r\n")
- end
- for i=1,#body do
- yieldcoroutine("\r\n--"..boundary.."\r\n")
- send_message(body[i])
- end
- yieldcoroutine("\r\n--"..boundary.."--\r\n\r\n")
- if epilogue then
- yieldcoroutine(epilogue)
- yieldcoroutine("\r\n")
- end
-end
-local default_content_type='text/plain; charset="UTF-8"'
-local function send_source(message)
- local headers=lowerheaders(message.headers)
- if not headers['content-type'] then
- headers['content-type']=default_content_type
- end
- send_headers(headers)
- local getchunk=message.body
- while true do
- local chunk,err=getchunk()
- if err then
- yieldcoroutine(nil,err)
- elseif chunk then
- yieldcoroutine(chunk)
- else
- break
- end
- end
-end
-local function send_string(message)
- local headers=lowerheaders(message.headers)
- if not headers['content-type'] then
- headers['content-type']=default_content_type
- end
- send_headers(headers)
- yieldcoroutine(message.body)
-end
-function send_message(message)
- local body=message.body
- if type(body)=="table" then
- send_multipart(message)
- elseif type(body)=="function" then
- send_source(message)
- else
- send_string(message)
- end
-end
-local function adjust_headers(message)
- local headers=lowerheaders(message.headers)
- if not headers["date"] then
- headers["date"]=osdate("!%a, %d %b %Y %H:%M:%S ")..(message.zone or smtp.ZONE)
- end
- if not headers["x-mailer"] then
- headers["x-mailer"]=socket._VERSION
- end
- headers["mime-version"]="1.0"
- return headers
-end
-function smtp.message(message)
- message.headers=adjust_headers(message)
- local action=createcoroutine(function()
- send_message(message)
- end)
- return function()
- local ret,a,b=resumecoroutine(action)
- if ret then
- return a,b
- else
- return nil,a
- end
- end
-end
-smtp.send=protectsocket(function(mail)
- local snd=opensmtp(smtp,mail.server,mail.port,mail.create)
- local ext=snd:greet(mail.domain)
- snd:auth(mail.user,mail.password,ext)
- snd:send(mail)
- snd:quit()
- return snd:close()
-end)
-package.loaded["socket.smtp"]=smtp
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-set"] = package.loaded["trac-set"] or true
-
--- original size: 13901, stripped down to: 9175
-
-if not modules then modules={} end modules ['trac-set']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,next,tostring,tonumber=type,next,tostring,tonumber
-local print=print
-local concat,sortedhash=table.concat,table.sortedhash
-local formatters,find,lower,gsub,topattern=string.formatters,string.find,string.lower,string.gsub,string.topattern
-local is_boolean=string.is_boolean
-local settings_to_hash=utilities.parsers.settings_to_hash
-local allocate=utilities.storage.allocate
-utilities=utilities or {}
-local utilities=utilities
-local setters=utilities.setters or {}
-utilities.setters=setters
-local data={}
-local trace_initialize=false
-local frozen=true
-local function initialize_setter(filename,name,values)
- local setter=data[name]
- if setter then
- local data=setter.data
- if data then
- for key,newvalue in sortedhash(values) do
- local newvalue=is_boolean(newvalue,newvalue,true)
- local functions=data[key]
- if functions then
- local oldvalue=functions.value
- if functions.frozen then
- if trace_initialize then
- setter.report("%s: %a is %s to %a",filename,key,"frozen",oldvalue)
- end
- elseif #functions>0 and not oldvalue then
- if trace_initialize then
- setter.report("%s: %a is %s to %a",filename,key,"set",newvalue)
- end
- for i=1,#functions do
- functions[i](newvalue)
- end
- functions.value=newvalue
- functions.frozen=functions.frozen or frozen
- else
- if trace_initialize then
- setter.report("%s: %a is %s as %a",filename,key,"kept",oldvalue)
- end
- end
- else
- functions={ default=newvalue,frozen=frozen }
- data[key]=functions
- if trace_initialize then
- setter.report("%s: %a is %s to %a",filename,key,"defaulted",newvalue)
- end
- end
- end
- return true
- end
- end
-end
-local function set(t,what,newvalue)
- local data=t.data
- if data and not data.frozen then
- local done=t.done
- if type(what)=="string" then
- what=settings_to_hash(what)
- end
- if type(what)~="table" then
- return
- end
- if not done then
- done={}
- t.done=done
- end
- for w,value in sortedhash(what) do
- if value=="" then
- value=newvalue
- elseif not value then
- value=false
- else
- value=is_boolean(value,value,true)
- end
- w=topattern(w,true,true)
- for name,functions in sortedhash(data) do
- if done[name] then
- elseif find(name,w) then
- done[name]=true
- for i=1,#functions do
- functions[i](value)
- end
- functions.value=value
- end
- end
- end
- end
-end
-local function reset(t)
- local data=t.data
- if data and not data.frozen then
- for name,functions in sortedthash(data) do
- for i=1,#functions do
- functions[i](false)
- end
- functions.value=false
- end
- end
-end
-local function enable(t,what)
- set(t,what,true)
-end
-local function disable(t,what)
- local data=t.data
- if not what or what=="" then
- t.done={}
- reset(t)
- else
- set(t,what,false)
- end
-end
-local function register_setter(t,what,...)
- local data=t.data
- what=lower(what)
- local functions=data[what]
- if not functions then
- functions={}
- data[what]=functions
- if trace_initialize then
- t.report("defining %a",what)
- end
- end
- local default=functions.default
- for i=1,select("#",...) do
- local fnc=select(i,...)
- local typ=type(fnc)
- if typ=="string" then
- if trace_initialize then
- t.report("coupling %a to %a",what,fnc)
- end
- local s=fnc
- fnc=function(value) set(t,s,value) end
- elseif typ~="function" then
- fnc=nil
- end
- if fnc then
- functions[#functions+1]=fnc
- local value=functions.value or default
- if value~=nil then
- fnc(value)
- functions.value=value
- end
- end
- end
- return false
-end
-local function enable_setter(t,what)
- local e=t.enable
- t.enable,t.done=enable,{}
- set(t,what,true)
- enable(t,what)
- t.enable,t.done=e,{}
-end
-local function disable_setter(t,what)
- local e=t.disable
- t.disable,t.done=disable,{}
- disable(t,what)
- t.disable,t.done=e,{}
-end
-local function reset_setter(t)
- t.done={}
- reset(t)
-end
-local function list_setter(t)
- local list=table.sortedkeys(t.data)
- local user,system={},{}
- for l=1,#list do
- local what=list[l]
- if find(what,"^%*") then
- system[#system+1]=what
- else
- user[#user+1]=what
- end
- end
- return user,system
-end
-local function show_setter(t)
- local list=list_setter(t)
- t.report()
- for k=1,#list do
- local name=list[k]
- local functions=t.data[name]
- if functions then
- local value=functions.value
- local default=functions.default
- local modules=#functions
- if default==nil then
- default="unset"
- elseif type(default)=="table" then
- default=concat(default,"|")
- else
- default=tostring(default)
- end
- if value==nil then
- value="unset"
- elseif type(value)=="table" then
- value=concat(value,"|")
- else
- value=tostring(value)
- end
- t.report(name)
- t.report(" modules : %i",modules)
- t.report(" default : %s",default)
- t.report(" value : %s",value)
- t.report()
- end
- end
-end
-function setters.report(setter,fmt,...)
- if fmt then
- print(formatters["%-15s : %s"](setter.name,formatters[fmt](...)))
- else
- print("")
- end
-end
-local function setter_default(setter,name)
- local d=setter.data[name]
- return d and d.default
-end
-local function setter_value(setter,name)
- local d=setter.data[name]
- return d and (d.value or d.default)
-end
-local function new_setter(name)
- local setter
- setter={
- data=allocate(),
- name=name,
- report=function(...) setters.report (setter,...) end,
- enable=function(...) enable_setter (setter,...) end,
- disable=function(...) disable_setter (setter,...) end,
- reset=function(...) reset_setter (setter,...) end,
- register=function(...) register_setter(setter,...) end,
- list=function(...) return list_setter (setter,...) end,
- show=function(...) show_setter (setter,...) end,
- default=function(...) return setter_default (setter,...) end,
- value=function(...) return setter_value (setter,...) end,
- }
- data[name]=setter
- return setter
-end
-setters.enable=enable_setter
-setters.disable=disable_setter
-setters.register=register_setter
-setters.list=list_setter
-setters.show=show_setter
-setters.reset=reset_setter
-setters.new=new_setter
-setters.initialize=initialize_setter
-trackers=new_setter("trackers")
-directives=new_setter("directives")
-experiments=new_setter("experiments")
-local t_enable,t_disable=trackers .enable,trackers .disable
-local d_enable,d_disable=directives .enable,directives .disable
-local e_enable,e_disable=experiments.enable,experiments.disable
-local trace_directives=false local trace_directives=false trackers.register("system.directives",function(v) trace_directives=v end)
-local trace_experiments=false local trace_experiments=false trackers.register("system.experiments",function(v) trace_experiments=v end)
-function directives.enable(...)
- if trace_directives then
- directives.report("enabling: % t",{...})
- end
- d_enable(...)
-end
-function directives.disable(...)
- if trace_directives then
- directives.report("disabling: % t",{...})
- end
- d_disable(...)
-end
-function experiments.enable(...)
- if trace_experiments then
- experiments.report("enabling: % t",{...})
- end
- e_enable(...)
-end
-function experiments.disable(...)
- if trace_experiments then
- experiments.report("disabling: % t",{...})
- end
- e_disable(...)
-end
-directives.register("system.nostatistics",function(v)
- if statistics then
- statistics.enable=not v
- else
- end
-end)
-directives.register("system.nolibraries",function(v)
- if libraries then
- libraries=nil
- else
- end
-end)
-if environment then
- local engineflags=environment.engineflags
- if engineflags then
- local list=engineflags["c:trackers"] or engineflags["trackers"]
- if type(list)=="string" then
- initialize_setter("commandline flags","trackers",settings_to_hash(list))
- end
- local list=engineflags["c:directives"] or engineflags["directives"]
- if type(list)=="string" then
- initialize_setter("commandline flags","directives",settings_to_hash(list))
- end
- end
-end
-if texconfig then
- local function set(k,v)
- v=tonumber(v)
- if v then
- texconfig[k]=v
- end
- end
- directives.register("luatex.expanddepth",function(v) set("expand_depth",v) end)
- directives.register("luatex.hashextra",function(v) set("hash_extra",v) end)
- directives.register("luatex.nestsize",function(v) set("nest_size",v) end)
- directives.register("luatex.maxinopen",function(v) set("max_in_open",v) end)
- directives.register("luatex.maxprintline",function(v) set("max_print_line",v) end)
- directives.register("luatex.maxstrings",function(v) set("max_strings",v) end)
- directives.register("luatex.paramsize",function(v) set("param_size",v) end)
- directives.register("luatex.savesize",function(v) set("save_size",v) end)
- directives.register("luatex.stacksize",function(v) set("stack_size",v) end)
-end
-local data=table.setmetatableindex("table")
-updaters={
- register=function(what,f)
- local d=data[what]
- d[#d+1]=f
- end,
- apply=function(what,...)
- local d=data[what]
- for i=1,#d do
- d[i](...)
- end
- end,
-}
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-log"] = package.loaded["trac-log"] or true
-
--- original size: 16017, stripped down to: 11045
-
-if not modules then modules={} end modules ['trac-log']={
- version=1.001,
- comment="companion to trac-log.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local next,type,select,print=next,type,select,print
-local format,gmatch,find=string.format,string.gmatch,string.find
-local concat,insert,remove=table.concat,table.insert,table.remove
-local topattern=string.topattern
-local utfchar=utf.char
-local datetime=os.date
-local openfile=io.open
-local write_nl=print
-local write=io.write
-local setmetatableindex=table.setmetatableindex
-local formatters=string.formatters
-local settings_to_hash=utilities.parsers.settings_to_hash
-local sortedkeys=table.sortedkeys
-local variant="default"
-logs=logs or {}
-local logs=logs
-local moreinfo=[[
-More information about ConTeXt and the tools that come with it can be found at:
-]].."\n"..[[
-maillist : ntg-context@ntg.nl / http://www.ntg.nl/mailman/listinfo/ntg-context
-webpage : http://www.pragma-ade.nl / http://tex.aanhet.net
-wiki : http://contextgarden.net
-]]
-formatters.add (
- formatters,"unichr",
- [["U+" .. format("%%05X",%s) .. " (" .. utfchar(%s) .. ")"]]
-)
-formatters.add (
- formatters,"chruni",
- [[utfchar(%s) .. " (U+" .. format("%%05X",%s) .. ")"]]
-)
-local function ignore() end
-setmetatableindex(logs,function(t,k) t[k]=ignore;return ignore end)
-local report,subreport,status,settarget,setformats,settranslations
-local direct,subdirect,writer,pushtarget,poptarget,setlogfile,settimedlog,setprocessor,setformatters,newline
-local function ansisupported(specification)
- if specification~="ansi" and specification~="ansilog" then
- return false
- elseif os and os.enableansi then
- return os.enableansi()
- else
- return false
- end
-end
-do
- local report_yes,subreport_yes,status_yes
- local report_nop,subreport_nop,status_nop
- local variants={
- default={
- formats={
- report_yes=formatters["%-15s | %s"],
- report_nop=formatters["%-15s |"],
- subreport_yes=formatters["%-15s | %s | %s"],
- subreport_nop=formatters["%-15s | %s |"],
- status_yes=formatters["%-15s : %s\n"],
- status_nop=formatters["%-15s :\n"],
- },
- },
- ansi={
- formats={
- report_yes=formatters["%-15s | %s"],
- report_nop=formatters["%-15s |"],
- subreport_yes=formatters["%-15s | %s | %s"],
- subreport_nop=formatters["%-15s | %s |"],
- status_yes=formatters["%-15s : %s\n"],
- status_nop=formatters["%-15s :\n"],
- },
- },
- }
- logs.flush=ignore
- writer=function(s)
- write_nl(s)
- end
- newline=function()
- write_nl("\n")
- end
- report=function(a,b,c,...)
- if c then
- write_nl(report_yes(a,formatters[b](c,...)))
- elseif b then
- write_nl(report_yes(a,b))
- elseif a then
- write_nl(report_nop(a))
- else
- write_nl("")
- end
- end
- subreport=function(a,sub,b,c,...)
- if c then
- write_nl(subreport_yes(a,sub,formatters[b](c,...)))
- elseif b then
- write_nl(subreport_yes(a,sub,b))
- elseif a then
- write_nl(subreport_nop(a,sub))
- else
- write_nl("")
- end
- end
- status=function(a,b,c,...)
- if c then
- write_nl(status_yes(a,formatters[b](c,...)))
- elseif b then
- write_nl(status_yes(a,b))
- elseif a then
- write_nl(status_nop(a))
- else
- write_nl("\n")
- end
- end
- direct=ignore
- subdirect=ignore
- settarget=ignore
- pushtarget=ignore
- poptarget=ignore
- setformats=ignore
- settranslations=ignore
- setprocessor=function(f)
- local writeline=write_nl
- write_nl=function(s)
- writeline(f(s))
- end
- end
- setformatters=function(specification)
- local f=nil
- local d=variants.default
- if specification then
- if type(specification)=="table" then
- f=specification.formats or specification
- else
- if not ansisupported(specification) then
- specification="default"
- end
- local v=variants[specification]
- if v then
- f=v.formats
- end
- end
- end
- if f then
- d=d.formats
- else
- f=d.formats
- d=f
- end
- setmetatableindex(f,d)
- report_yes=f.report_yes
- report_nop=f.report_nop
- subreport_yes=f.subreport_yes
- subreport_nop=f.subreport_nop
- status_yes=f.status_yes
- status_nop=f.status_nop
- end
- setformatters(variant)
- setlogfile=function(name,keepopen)
- if name and name~="" then
- local localtime=os.localtime
- local writeline=write_nl
- if keepopen then
- local f=io.open(name,"ab")
- write_nl=function(s)
- writeline(s)
- f:write(localtime()," | ",s,"\n")
- end
- else
- write_nl=function(s)
- writeline(s)
- local f=io.open(name,"ab")
- f:write(localtime()," | ",s,"\n")
- f:close()
- end
- end
- end
- setlogfile=ignore
- end
- settimedlog=function()
- local localtime=os.localtime
- local writeline=write_nl
- write_nl=function(s)
- writeline(localtime().." | "..s)
- end
- settimedlog=ignore
- end
-end
-logs.report=report
-logs.subreport=subreport
-logs.status=status
-logs.settarget=settarget
-logs.pushtarget=pushtarget
-logs.poptarget=poptarget
-logs.setformats=setformats
-logs.settranslations=settranslations
-logs.setlogfile=setlogfile
-logs.settimedlog=settimedlog
-logs.setprocessor=setprocessor
-logs.setformatters=setformatters
-logs.direct=direct
-logs.subdirect=subdirect
-logs.writer=writer
-logs.newline=newline
-local data={}
-local states=nil
-local force=false
-function logs.reporter(category,subcategory)
- local logger=data[category]
- if not logger then
- local state=states==true
- if not state and type(states)=="table" then
- for c,_ in next,states do
- if find(category,c) then
- state=true
- break
- end
- end
- end
- logger={
- reporters={},
- state=state,
- }
- data[category]=logger
- end
- local reporter=logger.reporters[subcategory or "default"]
- if not reporter then
- if subcategory then
- reporter=function(...)
- if force or not logger.state then
- subreport(category,subcategory,...)
- end
- end
- logger.reporters[subcategory]=reporter
- else
- local tag=category
- reporter=function(...)
- if force or not logger.state then
- report(category,...)
- end
- end
- logger.reporters.default=reporter
- end
- end
- return reporter
-end
-logs.new=logs.reporter
-local ctxreport=logs.writer
-function logs.setmessenger(m)
- ctxreport=m
-end
-function logs.messenger(category,subcategory)
- if subcategory then
- return function(...)
- ctxreport(subdirect(category,subcategory,...))
- end
- else
- return function(...)
- ctxreport(direct(category,...))
- end
- end
-end
-local function setblocked(category,value)
- if category==true or category=="all" then
- category,value="*",true
- elseif category==false then
- category,value="*",false
- elseif value==nil then
- value=true
- end
- if category=="*" then
- states=value
- for k,v in next,data do
- v.state=value
- end
- else
- alllocked=false
- states=settings_to_hash(category,type(states)=="table" and states or nil)
- for c in next,states do
- local v=data[c]
- if v then
- v.state=value
- else
- c=topattern(c,true,true)
- for k,v in next,data do
- if find(k,c) then
- v.state=value
- end
- end
- end
- end
- end
-end
-function logs.disable(category,value)
- setblocked(category,value==nil and true or value)
-end
-function logs.enable(category)
- setblocked(category,false)
-end
-function logs.categories()
- return sortedkeys(data)
-end
-function logs.show()
- local n,c,s,max=0,0,0,0
- for category,v in table.sortedpairs(data) do
- n=n+1
- local state=v.state
- local reporters=v.reporters
- local nc=#category
- if nc>c then
- c=nc
- end
- for subcategory,_ in next,reporters do
- local ns=#subcategory
- if ns>c then
- s=ns
- end
- local m=nc+ns
- if m>max then
- max=m
- end
- end
- local subcategories=concat(sortedkeys(reporters),", ")
- if state==true then
- state="disabled"
- elseif state==false then
- state="enabled"
- else
- state="unknown"
- end
- report("logging","category %a, subcategories %a, state %a",category,subcategories,state)
- end
- report("logging","categories: %s, max category: %s, max subcategory: %s, max combined: %s",n,c,s,max)
-end
-local delayed_reporters={}
-setmetatableindex(delayed_reporters,function(t,k)
- local v=logs.reporter(k.name)
- t[k]=v
- return v
-end)
-function utilities.setters.report(setter,...)
- delayed_reporters[setter](...)
-end
-directives.register("logs.blocked",function(v)
- setblocked(v,true)
-end)
-directives.register("logs.target",function(v)
- settarget(v)
-end)
-local nesting=0
-local verbose=false
-local hasscheme=url.hasscheme
-local simple=logs.reporter("comment")
-logs.simple=simple
-logs.simpleline=simple
-logs.setprogram=ignore
-logs.extendbanner=ignore
-logs.reportlines=ignore
-logs.reportbanner=ignore
-logs.reportline=ignore
-logs.simplelines=ignore
-logs.help=ignore
-local Carg,C,lpegmatch=lpeg.Carg,lpeg.C,lpeg.match
-local p_newline=lpeg.patterns.newline
-local linewise=(
- Carg(1)*C((1-p_newline)^1)/function(t,s) t.report(s) end+Carg(1)*p_newline^2/function(t) t.report() end+p_newline
-)^1
-local function reportlines(t,str)
- if str then
- lpegmatch(linewise,str,1,t)
- end
-end
-local function reportbanner(t)
- local banner=t.banner
- if banner then
- t.report(banner)
- t.report()
- end
-end
-local function reportversion(t)
- local banner=t.banner
- if banner then
- t.report(banner)
- end
-end
-local function reporthelp(t,...)
- local helpinfo=t.helpinfo
- if type(helpinfo)=="string" then
- reportlines(t,helpinfo)
- elseif type(helpinfo)=="table" then
- for i=1,select("#",...) do
- reportlines(t,t.helpinfo[select(i,...)])
- if i<n then
- t.report()
- end
- end
- end
-end
-local function reportinfo(t)
- t.report()
- reportlines(t,t.moreinfo)
-end
-local function reportexport(t,method)
- report(t.helpinfo)
-end
-local reporters={
- lines=reportlines,
- banner=reportbanner,
- version=reportversion,
- help=reporthelp,
- info=reportinfo,
- export=reportexport,
-}
-local exporters={
-}
-logs.reporters=reporters
-logs.exporters=exporters
-function logs.application(t)
- local arguments=environment and environment.arguments
- if arguments then
- local ansi=arguments.ansi or arguments.ansilog
- if ansi then
- logs.setformatters(arguments.ansi and "ansi" or "ansilog")
- end
- end
- t.name=t.name or "unknown"
- t.banner=t.banner
- t.moreinfo=moreinfo
- t.report=logs.reporter(t.name)
- t.help=function(...)
- reporters.banner(t)
- reporters.help(t,...)
- reporters.info(t)
- end
- t.export=function(...)
- reporters.export(t,...)
- end
- t.identify=function()
- reporters.banner(t)
- end
- t.version=function()
- reporters.version(t)
- end
- return t
-end
-local f_syslog=formatters["%s %s => %s => %s => %s\r"]
-function logs.system(whereto,process,jobname,category,fmt,arg,...)
- local message=f_syslog(datetime("%d/%m/%y %H:%m:%S"),process,jobname,category,arg==nil and fmt or format(fmt,arg,...))
- for i=1,10 do
- local f=openfile(whereto,"a")
- if f then
- f:write(message)
- f:close()
- break
- else
- sleep(0.1)
- end
- end
-end
-local report_system=logs.reporter("system","logs")
-if utilities then
- utilities.report=report_system
-end
-if package.helpers.report then
- package.helpers.report=logs.reporter("package loader")
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-inf"] = package.loaded["trac-inf"] or true
-
--- original size: 9740, stripped down to: 7296
-
-if not modules then modules={} end modules ['trac-inf']={
- version=1.001,
- comment="companion to trac-inf.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,tonumber,select=type,tonumber,select
-local format,lower,find=string.format,string.lower,string.find
-local concat=table.concat
-local clock=os.gettimeofday or os.clock
-local setmetatableindex=table.setmetatableindex
-local serialize=table.serialize
-local formatters=string.formatters
-statistics=statistics or {}
-local statistics=statistics
-statistics.enable=true
-statistics.threshold=0.01
-local statusinfo,n,registered,timers={},0,{},{}
-setmetatableindex(timers,function(t,k)
- local v={ timing=0,loadtime=0,offset=0 }
- t[k]=v
- return v
-end)
-local function hastiming(instance)
- return instance and timers[instance]
-end
-local function resettiming(instance)
- timers[instance or "notimer"]={ timing=0,loadtime=0,offset=0 }
-end
-local ticks=clock
-local seconds=function(n) return n or 0 end
-if os.type~="windows" then
-elseif lua.getpreciseticks then
- ticks=lua.getpreciseticks
- seconds=lua.getpreciseseconds
-elseif FFISUPPORTED then
- local okay,kernel=pcall(ffi.load,"kernel32")
- if kernel then
- local tonumber=ffi.number or tonumber
- ffi.cdef[[
- int QueryPerformanceFrequency(int64_t *lpFrequency);
- int QueryPerformanceCounter(int64_t *lpPerformanceCount);
- ]]
- local target=ffi.new("__int64[1]")
- ticks=function()
- if kernel.QueryPerformanceCounter(target)==1 then
- return tonumber(target[0])
- else
- return 0
- end
- end
- local target=ffi.new("__int64[1]")
- seconds=function(ticks)
- if kernel.QueryPerformanceFrequency(target)==1 then
- return ticks/tonumber(target[0])
- else
- return 0
- end
- end
- end
-else
-end
-local function starttiming(instance,reset)
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if reset then
- it=0
- timer.loadtime=0
- end
- if it==0 then
- timer.starttime=ticks()
- if not timer.loadtime then
- timer.loadtime=0
- end
- end
- timer.timing=it+1
-end
-local function stoptiming(instance)
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if it>1 then
- timer.timing=it-1
- else
- local starttime=timer.starttime
- if starttime and starttime>0 then
- local stoptime=ticks()
- local loadtime=stoptime-starttime
- timer.stoptime=stoptime
- timer.loadtime=timer.loadtime+loadtime
- timer.timing=0
- timer.starttime=0
- end
- end
-end
-local function benchmarktimer(instance)
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if it>1 then
- timer.timing=it-1
- else
- local starttime=timer.starttime
- if starttime and starttime>0 then
- timer.offset=ticks()-starttime
- else
- timer.offset=0
- end
- end
-end
-local function elapsed(instance)
- if type(instance)=="number" then
- return instance
- else
- local timer=timers[instance or "notimer"]
- return timer and seconds(timer.loadtime-2*(timer.offset or 0)) or 0
- end
-end
-local function currenttime(instance)
- if type(instance)=="number" then
- return instance
- else
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if it>1 then
- else
- local starttime=timer.starttime
- if starttime and starttime>0 then
- return seconds(timer.loadtime+ticks()-starttime-2*(timer.offset or 0))
- end
- end
- return 0
- end
-end
-local function elapsedtime(instance)
- return format("%0.3f",elapsed(instance))
-end
-local function elapsedindeed(instance)
- return elapsed(instance)>statistics.threshold
-end
-local function elapsedseconds(instance,rest)
- if elapsedindeed(instance) then
- return format("%0.3f seconds %s",elapsed(instance),rest or "")
- end
-end
-statistics.hastiming=hastiming
-statistics.resettiming=resettiming
-statistics.starttiming=starttiming
-statistics.stoptiming=stoptiming
-statistics.currenttime=currenttime
-statistics.elapsed=elapsed
-statistics.elapsedtime=elapsedtime
-statistics.elapsedindeed=elapsedindeed
-statistics.elapsedseconds=elapsedseconds
-statistics.benchmarktimer=benchmarktimer
-function statistics.register(tag,fnc)
- if statistics.enable and type(fnc)=="function" then
- local rt=registered[tag] or (#statusinfo+1)
- statusinfo[rt]={ tag,fnc }
- registered[tag]=rt
- if #tag>n then n=#tag end
- end
-end
-local report=logs.reporter("mkiv lua stats")
-function statistics.show()
- if statistics.enable then
- local register=statistics.register
- register("used platform",function()
- return format("%s, type: %s, binary subtree: %s",
- os.platform or "unknown",os.type or "unknown",environment.texos or "unknown")
- end)
- register("used engine",function()
- return format("%s version: %s, functionality level: %s, banner: %s",
- LUATEXENGINE,LUATEXVERSION,LUATEXFUNCTIONALITY,lower(status.banner))
- end)
- register("used hash slots",function()
- return format("%s of %s + %s",status.cs_count,status.hash_size,status.hash_extra)
- end)
- register("callbacks",statistics.callbacks)
- if JITSUPPORTED then
- local jitstatus=jit.status
- if jitstatus then
- local jitstatus={ jitstatus() }
- if jitstatus[1] then
- register("luajit options",concat(jitstatus," ",2))
- end
- end
- end
- register("lua properties",function()
- local hash=2^status.luatex_hashchars
- local mask=load([[τεχ = 1]]) and "utf" or "ascii"
- return format("engine: %s %s, used memory: %s, hash chars: min(%i,40), symbol mask: %s (%s)",
- jit and "luajit" or "lua",LUAVERSION,statistics.memused(),hash,mask,mask=="utf" and "τεχ" or "tex")
- end)
- register("runtime",statistics.runtime)
- logs.newline()
- for i=1,#statusinfo do
- local s=statusinfo[i]
- local r=s[2]()
- if r then
- report("%s: %s",s[1],r)
- end
- end
- statistics.enable=false
- end
-end
-function statistics.memused()
- local round=math.round or math.floor
- return format("%s MB, ctx: %s MB, max: %s MB",
- round(collectgarbage("count")/1000),
- round(status.luastate_bytes/1000000),
- status.luastate_bytes_max and round(status.luastate_bytes_max/1000000) or "unknown"
- )
-end
-starttiming(statistics)
-function statistics.formatruntime(runtime)
- return format("%s seconds",runtime)
-end
-function statistics.runtime()
- stoptiming(statistics)
- local runtime=lua.getruntime and lua.getruntime() or elapsedtime(statistics)
- return statistics.formatruntime(runtime)
-end
-local report=logs.reporter("system")
-function statistics.timed(action,all)
- starttiming("run")
- action()
- stoptiming("run")
- local runtime=tonumber(elapsedtime("run"))
- if all then
- local alltime=tonumber(lua.getruntime and lua.getruntime() or elapsedtime(statistics))
- if alltime and alltime>0 then
- report("total runtime: %0.3f seconds of %0.3f seconds",runtime,alltime)
- return
- end
- end
- report("total runtime: %0.3f seconds",runtime)
-end
-function statistics.tracefunction(base,tag,...)
- for i=1,select("#",...) do
- local name=select(i,...)
- local stat={}
- local func=base[name]
- setmetatableindex(stat,function(t,k) t[k]=0 return 0 end)
- base[name]=function(n,k,v) stat[k]=stat[k]+1 return func(n,k,v) end
- statistics.register(formatters["%s.%s"](tag,name),function() return serialize(stat,"calls") end)
- end
-end
-function status.getreadstate()
- return {
- filename=status.filename or "?",
- linenumber=status.linenumber or 0,
- iocode=status.inputid or 0,
- }
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-pro"] = package.loaded["trac-pro"] or true
-
--- original size: 5841, stripped down to: 3352
-
-if not modules then modules={} end modules ['trac-pro']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local getmetatable,setmetatable,rawset,type,next=getmetatable,setmetatable,rawset,type,next
-local trace_namespaces=false trackers.register("system.namespaces",function(v) trace_namespaces=v end)
-local report_system=logs.reporter("system","protection")
-namespaces=namespaces or {}
-local namespaces=namespaces
-local registered={}
-local function report_index(k,name)
- if trace_namespaces then
- report_system("reference to %a in protected namespace %a: %s",k,name)
- debugger.showtraceback(report_system)
- else
- report_system("reference to %a in protected namespace %a",k,name)
- end
-end
-local function report_newindex(k,name)
- if trace_namespaces then
- report_system("assignment to %a in protected namespace %a: %s",k,name)
- debugger.showtraceback(report_system)
- else
- report_system("assignment to %a in protected namespace %a",k,name)
- end
-end
-local function register(name)
- local data=name=="global" and _G or _G[name]
- if not data then
- return
- end
- registered[name]=data
- local m=getmetatable(data)
- if not m then
- m={}
- setmetatable(data,m)
- end
- local index,newindex={},{}
- m.__saved__index=m.__index
- m.__no__index=function(t,k)
- if not index[k] then
- index[k]=true
- report_index(k,name)
- end
- return nil
- end
- m.__saved__newindex=m.__newindex
- m.__no__newindex=function(t,k,v)
- if not newindex[k] then
- newindex[k]=true
- report_newindex(k,name)
- end
- rawset(t,k,v)
- end
- m.__protection__depth=0
-end
-local function private(name)
- local data=registered[name]
- if not data then
- data=_G[name]
- if not data then
- data={}
- _G[name]=data
- end
- register(name)
- end
- return data
-end
-local function protect(name)
- local data=registered[name]
- if not data then
- return
- end
- local m=getmetatable(data)
- local pd=m.__protection__depth
- if pd>0 then
- m.__protection__depth=pd+1
- else
- m.__save_d_index,m.__saved__newindex=m.__index,m.__newindex
- m.__index,m.__newindex=m.__no__index,m.__no__newindex
- m.__protection__depth=1
- end
-end
-local function unprotect(name)
- local data=registered[name]
- if not data then
- return
- end
- local m=getmetatable(data)
- local pd=m.__protection__depth
- if pd>1 then
- m.__protection__depth=pd-1
- else
- m.__index,m.__newindex=m.__saved__index,m.__saved__newindex
- m.__protection__depth=0
- end
-end
-local function protectall()
- for name,_ in next,registered do
- if name~="global" then
- protect(name)
- end
- end
-end
-local function unprotectall()
- for name,_ in next,registered do
- if name~="global" then
- unprotect(name)
- end
- end
-end
-namespaces.register=register
-namespaces.private=private
-namespaces.protect=protect
-namespaces.unprotect=unprotect
-namespaces.protectall=protectall
-namespaces.unprotectall=unprotectall
-namespaces.private("namespaces") registered={} register("global")
-directives.register("system.protect",function(v)
- if v then
- protectall()
- else
- unprotectall()
- end
-end)
-directives.register("system.checkglobals",function(v)
- if v then
- report_system("enabling global namespace guard")
- protect("global")
- else
- report_system("disabling global namespace guard")
- unprotect("global")
- end
-end)
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-lua"] = package.loaded["util-lua"] or true
-
--- original size: 7149, stripped down to: 4997
-
-if not modules then modules={} end modules ['util-lua']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- comment="the strip code is written by Peter Cawley",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local rep,sub,byte,dump,format=string.rep,string.sub,string.byte,string.dump,string.format
-local load,loadfile,type,collectgarbage=load,loadfile,type,collectgarbage
-utilities=utilities or {}
-utilities.lua=utilities.lua or {}
-local luautilities=utilities.lua
-local report_lua=logs.reporter("system","lua")
-local report_mem=logs.reporter("system","lua memory")
-local tracestripping=false
-local tracememory=false
-luautilities.stripcode=true
-luautilities.alwaysstripcode=false
-luautilities.nofstrippedchunks=0
-luautilities.nofstrippedbytes=0
-local strippedchunks={}
-luautilities.strippedchunks=strippedchunks
-if not LUATEXENGINE then
- LUATEXENGINE=status.luatex_engine and string.lower(status.luatex_engine)
- JITSUPPORTED=LUATEXENGINE=="luajittex" or jit
- CONTEXTLMTXMODE=CONTEXTLMTXMODE or (LUATEXENGINE=="luametatex" and 1) or 0
-end
-luautilities.suffixes={
- tma="tma",
- tmc=(CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and "tmd") or (jit and "tmb") or "tmc",
- lua="lua",
- luc=(CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and "lud") or (jit and "lub") or "luc",
- lui="lui",
- luv="luv",
- luj="luj",
- tua="tua",
- tuc=(CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and "tud") or (jit and "tub") or "tuc",
-}
-local function register(name)
- if tracestripping then
- report_lua("stripped bytecode from %a",name or "unknown")
- end
- strippedchunks[#strippedchunks+1]=name
- luautilities.nofstrippedchunks=luautilities.nofstrippedchunks+1
-end
-local function stupidcompile(luafile,lucfile,strip)
- local code=io.loaddata(luafile)
- if code and code~="" then
- code=load(code)
- if code then
- code=dump(code,strip and luautilities.stripcode or luautilities.alwaysstripcode)
- if code and code~="" then
- register(name)
- io.savedata(lucfile,code)
- return true,0
- end
- else
- report_lua("fatal error %a in file %a",1,luafile)
- end
- else
- report_lua("fatal error %a in file %a",2,luafile)
- end
- return false,0
-end
-function luautilities.loadedluacode(fullname,forcestrip,name,macros)
- name=name or fullname
- if macros then
- macros=lua.macros
- end
- local code,message
- if macros then
- code,message=macros.loaded(fullname,true,false)
- else
- code,message=loadfile(fullname)
- end
- if code then
- code()
- else
- report_lua("loading of file %a failed:\n\t%s",fullname,message or "no message")
- code,message=loadfile(fullname)
- end
- if forcestrip and luautilities.stripcode then
- if type(forcestrip)=="function" then
- forcestrip=forcestrip(fullname)
- end
- if forcestrip or luautilities.alwaysstripcode then
- register(name)
- return load(dump(code,true)),0
- else
- return code,0
- end
- elseif luautilities.alwaysstripcode then
- register(name)
- return load(dump(code,true)),0
- else
- return code,0
- end
-end
-function luautilities.strippedloadstring(code,name,forcestrip)
- local code,message=load(code)
- if not code then
- report_lua("loading of file %a failed:\n\t%s",name,message or "no message")
- end
- if forcestrip and luautilities.stripcode or luautilities.alwaysstripcode then
- register(name)
- return load(dump(code,true)),0
- else
- return code,0
- end
-end
-function luautilities.loadstring(code,name)
- local code,message=load(code)
- if not code then
- report_lua("loading of file %a failed:\n\t%s",name,message or "no message")
- end
- return code,0
-end
-function luautilities.compile(luafile,lucfile,cleanup,strip,fallback)
- report_lua("compiling %a into %a",luafile,lucfile)
- os.remove(lucfile)
- local done=stupidcompile(luafile,lucfile,strip~=false)
- if done then
- report_lua("dumping %a into %a stripped",luafile,lucfile)
- if cleanup==true and lfs.isfile(lucfile) and lfs.isfile(luafile) then
- report_lua("removing %a",luafile)
- os.remove(luafile)
- end
- end
- return done
-end
-function luautilities.loadstripped(...)
- local l=load(...)
- if l then
- return load(dump(l,true))
- end
-end
-local finalizers={}
-setmetatable(finalizers,{
- __gc=function(t)
- for i=1,#t do
- pcall(t[i])
- end
- end
-} )
-function luautilities.registerfinalizer(f)
- finalizers[#finalizers+1]=f
-end
-function luautilities.checkmemory(previous,threshold,trace)
- local current=collectgarbage("count")
- if previous then
- local checked=(threshold or 64)*1024
- local delta=current-previous
- if current-previous>checked then
- collectgarbage("collect")
- local afterwards=collectgarbage("count")
- if trace or tracememory then
- report_mem("previous %r MB, current %r MB, delta %r MB, threshold %r MB, afterwards %r MB",
- previous/1024,current/1024,delta/1024,threshold,afterwards)
- end
- return afterwards
- elseif trace or tracememory then
- report_mem("previous %r MB, current %r MB, delta %r MB, threshold %r MB",
- previous/1024,current/1024,delta/1024,threshold)
- end
- end
- return current
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-deb"] = package.loaded["util-deb"] or true
-
--- original size: 10136, stripped down to: 6832
-
-if not modules then modules={} end modules ['util-deb']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,next,tostring,tonumber=type,next,tostring,tonumber
-local format,find,sub,gsub=string.format,string.find,string.sub,string.gsub
-local insert,remove,sort=table.insert,table.remove,table.sort
-local setmetatableindex=table.setmetatableindex
-utilities=utilities or {}
-local debugger=utilities.debugger or {}
-utilities.debugger=debugger
-local report=logs.reporter("debugger")
-local ticks=os.gettimeofday or os.clock
-local seconds=function(n) return n or 0 end
-local overhead=0
-local dummycalls=10*1000
-local nesting=0
-local names={}
-local initialize=false
-if lua.getpreciseticks then
- initialize=function()
- ticks=lua.getpreciseticks
- seconds=lua.getpreciseseconds
- initialize=false
- end
-elseif not (FFISUPPORTED and ffi) then
-elseif os.type=="windows" then
- initialize=function()
- local kernel=ffilib("kernel32","system")
- if kernel then
- local tonumber=ffi.number or tonumber
- ffi.cdef[[
- int QueryPerformanceFrequency(int64_t *lpFrequency);
- int QueryPerformanceCounter(int64_t *lpPerformanceCount);
- ]]
- local target=ffi.new("__int64[1]")
- ticks=function()
- if kernel.QueryPerformanceCounter(target)==1 then
- return tonumber(target[0])
- else
- return 0
- end
- end
- local target=ffi.new("__int64[1]")
- seconds=function(ticks)
- if kernel.QueryPerformanceFrequency(target)==1 then
- return ticks/tonumber(target[0])
- else
- return 0
- end
- end
- end
- initialize=false
- end
-elseif os.type=="unix" then
- initialize=function()
- local C=ffi.C
- local tonumber=ffi.number or tonumber
- ffi.cdef [[
- /* what a mess */
- typedef int clk_id_t;
- typedef enum { CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID } clk_id;
- typedef struct timespec { long sec; long nsec; } ctx_timespec;
- int clock_gettime(clk_id_t timerid, struct timespec *t);
- ]]
- local target=ffi.new("ctx_timespec[?]",1)
- local clock=C.CLOCK_PROCESS_CPUTIME_ID
- ticks=function ()
- C.clock_gettime(clock,target)
- return tonumber(target[0].sec*1000000000+target[0].nsec)
- end
- seconds=function(ticks)
- return ticks/1000000000
- end
- initialize=false
- end
-end
-setmetatableindex(names,function(t,name)
- local v=setmetatableindex(function(t,source)
- local v=setmetatableindex(function(t,line)
- local v={ total=0,count=0,nesting=0 }
- t[line]=v
- return v
- end)
- t[source]=v
- return v
- end)
- t[name]=v
- return v
-end)
-local getinfo=nil
-local sethook=nil
-local function hook(where)
- local f=getinfo(2,"nSl")
- if f then
- local source=f.short_src
- if not source then
- return
- end
- local line=f.linedefined or 0
- local name=f.name
- if not name then
- local what=f.what
- if what=="C" then
- name="<anonymous>"
- else
- name=f.namewhat or what or "<unknown>"
- end
- end
- local data=names[name][source][line]
- if where=="call" then
- local nesting=data.nesting
- if nesting==0 then
- data.count=data.count+1
- insert(data,ticks())
- data.nesting=1
- else
- data.nesting=nesting+1
- end
- elseif where=="return" then
- local nesting=data.nesting
- if nesting==1 then
- local t=remove(data)
- if t then
- data.total=data.total+ticks()-t
- end
- data.nesting=0
- else
- data.nesting=nesting-1
- end
- end
- end
-end
-function debugger.showstats(printer,threshold)
- local printer=printer or report
- local calls=0
- local functions=0
- local dataset={}
- local length=0
- local realtime=0
- local totaltime=0
- local threshold=threshold or 0
- for name,sources in next,names do
- for source,lines in next,sources do
- for line,data in next,lines do
- local count=data.count
- if count>threshold then
- if #name>length then
- length=#name
- end
- local total=data.total
- local real=total
- if real>0 then
- real=total-(count*overhead/dummycalls)
- if real<0 then
- real=0
- end
- realtime=realtime+real
- end
- totaltime=totaltime+total
- if line<0 then
- line=0
- end
- dataset[#dataset+1]={ real,total,count,name,source,line }
- end
- end
- end
- end
- sort(dataset,function(a,b)
- if a[1]==b[1] then
- if a[2]==b[2] then
- if a[3]==b[3] then
- if a[4]==b[4] then
- if a[5]==b[5] then
- return a[6]<b[6]
- else
- return a[5]<b[5]
- end
- else
- return a[4]<b[4]
- end
- else
- return b[3]<a[3]
- end
- else
- return b[2]<a[2]
- end
- else
- return b[1]<a[1]
- end
- end)
- if length>50 then
- length=50
- end
- local fmt=string.formatters["%4.9k s %3.3k %% %4.9k s %3.3k %% %8i # %-"..length.."s %4i %s"]
- for i=1,#dataset do
- local data=dataset[i]
- local real=data[1]
- local total=data[2]
- local count=data[3]
- local name=data[4]
- local source=data[5]
- local line=data[6]
- calls=calls+count
- functions=functions+1
- name=gsub(name,"%s+"," ")
- if #name>length then
- name=sub(name,1,length)
- end
- printer(fmt(seconds(total),100*total/totaltime,seconds(real),100*real/realtime,count,name,line,source))
- end
- printer("")
- printer(format("functions : %i",functions))
- printer(format("calls : %i",calls))
- printer(format("overhead : %f",seconds(overhead/1000)))
-end
-local function getdebug()
- if sethook and getinfo then
- return
- end
- if not debug then
- local okay
- okay,debug=pcall(require,"debug")
- end
- if type(debug)~="table" then
- return
- end
- getinfo=debug.getinfo
- sethook=debug.sethook
- if type(getinfo)~="function" then
- getinfo=nil
- end
- if type(sethook)~="function" then
- sethook=nil
- end
-end
-function debugger.savestats(filename,threshold)
- local f=io.open(filename,'w')
- if f then
- debugger.showstats(function(str) f:write(str,"\n") end,threshold)
- f:close()
- end
-end
-function debugger.enable()
- getdebug()
- if sethook and getinfo and nesting==0 then
- running=true
- if initialize then
- initialize()
- end
- sethook(hook,"cr")
- local function dummy() end
- local t=ticks()
- for i=1,dummycalls do
- dummy()
- end
- overhead=ticks()-t
- end
- if nesting>0 then
- nesting=nesting+1
- end
-end
-function debugger.disable()
- if nesting>0 then
- nesting=nesting-1
- end
- if sethook and getinfo and nesting==0 then
- sethook()
- end
-end
-local function showtraceback(rep)
- getdebug()
- if getinfo then
- local level=2
- local reporter=rep or report
- while true do
- local info=getinfo(level,"Sl")
- if not info then
- break
- elseif info.what=="C" then
- reporter("%2i : %s",level-1,"C function")
- else
- reporter("%2i : %s : %s",level-1,info.short_src,info.currentline)
- end
- level=level+1
- end
- end
-end
-debugger.showtraceback=showtraceback
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-tpl"] = package.loaded["util-tpl"] or true
-
--- original size: 7722, stripped down to: 4212
-
-if not modules then modules={} end modules ['util-tpl']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities.templates=utilities.templates or {}
-local templates=utilities.templates
-local trace_template=false trackers.register("templates.trace",function(v) trace_template=v end)
-local report_template=logs.reporter("template")
-local tostring,next=tostring,next
-local format,sub,byte=string.format,string.sub,string.byte
-local P,C,R,Cs,Cc,Carg,lpegmatch,lpegpatterns=lpeg.P,lpeg.C,lpeg.R,lpeg.Cs,lpeg.Cc,lpeg.Carg,lpeg.match,lpeg.patterns
-local formatters=string.formatters
-local replacer
-local function replacekey(k,t,how,recursive)
- local v=t[k]
- if not v then
- if trace_template then
- report_template("unknown key %a",k)
- end
- return ""
- else
- v=tostring(v)
- if trace_template then
- report_template("setting key %a to value %a",k,v)
- end
- if recursive then
- return lpegmatch(replacer,v,1,t,how,recursive)
- else
- return v
- end
- end
-end
-local sqlescape=lpeg.replacer {
- { "'","''" },
- { "\\","\\\\" },
- { "\r\n","\\n" },
- { "\r","\\n" },
-}
-local sqlquoted=Cs(Cc("'")*sqlescape*Cc("'"))
-lpegpatterns.sqlescape=sqlescape
-lpegpatterns.sqlquoted=sqlquoted
-local luaescape=lpegpatterns.luaescape
-local escapers={
- lua=function(s)
- return lpegmatch(luaescape,s)
- end,
- sql=function(s)
- return lpegmatch(sqlescape,s)
- end,
-}
-local quotedescapers={
- lua=function(s)
- return format("%q",s)
- end,
- sql=function(s)
- return lpegmatch(sqlquoted,s)
- end,
-}
-local luaescaper=escapers.lua
-local quotedluaescaper=quotedescapers.lua
-local function replacekeyunquoted(s,t,how,recurse)
- if how==false then
- return replacekey(s,t,how,recurse)
- else
- local escaper=how and escapers[how] or luaescaper
- return escaper(replacekey(s,t,how,recurse))
- end
-end
-local function replacekeyquoted(s,t,how,recurse)
- if how==false then
- return replacekey(s,t,how,recurse)
- else
- local escaper=how and quotedescapers[how] or quotedluaescaper
- return escaper(replacekey(s,t,how,recurse))
- end
-end
-local function replaceoptional(l,m,r,t,how,recurse)
- local v=t[l]
- return v and v~="" and lpegmatch(replacer,r,1,t,how or "lua",recurse or false) or ""
-end
-local function replaceformatted(l,m,r,t,how,recurse)
- local v=t[r]
- return v and formatters[l](v)
-end
-local single=P("%")
-local double=P("%%")
-local lquoted=P("%[")
-local rquoted=P("]%")
-local lquotedq=P("%(")
-local rquotedq=P(")%")
-local escape=double/'%%'
-local nosingle=single/''
-local nodouble=double/''
-local nolquoted=lquoted/''
-local norquoted=rquoted/''
-local nolquotedq=lquotedq/''
-local norquotedq=rquotedq/''
-local nolformatted=P(":")/"%%"
-local norformatted=P(":")/""
-local noloptional=P("%?")/''
-local noroptional=P("?%")/''
-local nomoptional=P(":")/''
-local args=Carg(1)*Carg(2)*Carg(3)
-local key=nosingle*((C((1-nosingle)^1)*args)/replacekey)*nosingle
-local quoted=nolquotedq*((C((1-norquotedq)^1)*args)/replacekeyquoted)*norquotedq
-local unquoted=nolquoted*((C((1-norquoted)^1)*args)/replacekeyunquoted)*norquoted
-local optional=noloptional*((C((1-nomoptional)^1)*nomoptional*C((1-noroptional)^1)*args)/replaceoptional)*noroptional
-local formatted=nosingle*((Cs(nolformatted*(1-norformatted )^1)*norformatted*C((1-nosingle)^1)*args)/replaceformatted)*nosingle
-local any=P(1)
- replacer=Cs((unquoted+quoted+formatted+escape+optional+key+any)^0)
-local function replace(str,mapping,how,recurse)
- if mapping and str then
- return lpegmatch(replacer,str,1,mapping,how or "lua",recurse or false) or str
- else
- return str
- end
-end
-templates.replace=replace
-function templates.replacer(str,how,recurse)
- return function(mapping)
- return lpegmatch(replacer,str,1,mapping,how or "lua",recurse or false) or str
- end
-end
-function templates.load(filename,mapping,how,recurse)
- local data=io.loaddata(filename) or ""
- if mapping and next(mapping) then
- return replace(data,mapping,how,recurse)
- else
- return data
- end
-end
-function templates.resolve(t,mapping,how,recurse)
- if not mapping then
- mapping=t
- end
- for k,v in next,t do
- t[k]=replace(v,mapping,how,recurse)
- end
- return t
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-sbx"] = package.loaded["util-sbx"] or true
-
--- original size: 21084, stripped down to: 13214
-
-if not modules then modules={} end modules ['util-sbx']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if not sandbox then require("l-sandbox") end
-local next,type=next,type
-local replace=utilities.templates.replace
-local collapsepath=file.collapsepath
-local expandname=dir.expandname
-local sortedhash=table.sortedhash
-local lpegmatch=lpeg.match
-local platform=os.type
-local P,S,C=lpeg.P,lpeg.S,lpeg.C
-local gsub=string.gsub
-local lower=string.lower
-local find=string.find
-local concat=string.concat
-local unquoted=string.unquoted
-local optionalquoted=string.optionalquoted
-local basename=file.basename
-local nameonly=file.nameonly
-local sandbox=sandbox
-local validroots={}
-local validrunners={}
-local validbinaries=true
-local validlibraries=true
-local validators={}
-local finalized=nil
-local trace=false
-local p_validroot=nil
-local p_split=lpeg.firstofsplit(" ")
-local report=logs.reporter("sandbox")
-trackers.register("sandbox",function(v) trace=v end)
-sandbox.setreporter(report)
-sandbox.finalizer {
- category="files",
- action=function()
- finalized=true
- end
-}
-local function registerroot(root,what)
- if finalized then
- report("roots are already finalized")
- else
- if type(root)=="table" then
- root,what=root[1],root[2]
- end
- if type(root)=="string" and root~="" then
- root=collapsepath(expandname(root))
- if what=="r" or what=="ro" or what=="readable" then
- what="read"
- elseif what=="w" or what=="wo" or what=="writable" then
- what="write"
- end
- validroots[root]=what=="write" or false
- end
- end
-end
-sandbox.finalizer {
- category="files",
- action=function()
- if p_validroot then
- report("roots are already initialized")
- else
- sandbox.registerroot(".","write")
- for name in sortedhash(validroots) do
- if p_validroot then
- p_validroot=P(name)+p_validroot
- else
- p_validroot=P(name)
- end
- end
- p_validroot=p_validroot/validroots
- end
- end
-}
-local function registerbinary(name)
- if finalized then
- report("binaries are already finalized")
- elseif type(name)=="string" and name~="" then
- if not validbinaries then
- return
- end
- if validbinaries==true then
- validbinaries={ [name]=true }
- else
- validbinaries[name]=true
- end
- elseif name==true then
- validbinaries={}
- end
-end
-local function registerlibrary(name)
- if finalized then
- report("libraries are already finalized")
- elseif type(name)=="string" and name~="" then
- if not validlibraries then
- return
- end
- if validlibraries==true then
- validlibraries={ [nameonly(name)]=true }
- else
- validlibraries[nameonly(name)]=true
- end
- elseif name==true then
- validlibraries={}
- end
-end
-local p_write=S("wa") p_write=(1-p_write)^0*p_write
-local p_path=S("\\/~$%:") p_path=(1-p_path )^0*p_path
-local function normalized(name)
- if platform=="windows" then
- name=gsub(name,"/","\\")
- end
- return name
-end
-function sandbox.possiblepath(name)
- return lpegmatch(p_path,name) and true or false
-end
-local filenamelogger=false
-function sandbox.setfilenamelogger(l)
- filenamelogger=type(l)=="function" and l or false
-end
-local function validfilename(name,what)
- if p_validroot and type(name)=="string" and lpegmatch(p_path,name) then
- local asked=collapsepath(expandname(name))
- local okay=lpegmatch(p_validroot,asked)
- if okay==true then
- if filenamelogger then
- filenamelogger(name,"w",asked,true)
- end
- return name
- elseif okay==false then
- if not what then
- if filenamelogger then
- filenamelogger(name,"r",asked,true)
- end
- return name
- elseif lpegmatch(p_write,what) then
- if filenamelogger then
- filenamelogger(name,"w",asked,false)
- end
- return
- else
- if filenamelogger then
- filenamelogger(name,"r",asked,true)
- end
- return name
- end
- elseif filenamelogger then
- filenamelogger(name,"*",name,false)
- end
- else
- return name
- end
-end
-local function readable(name,finalized)
- return validfilename(name,"r")
-end
-local function normalizedreadable(name,finalized)
- local valid=validfilename(name,"r")
- if valid then
- return normalized(valid)
- end
-end
-local function writeable(name,finalized)
- return validfilename(name,"w")
-end
-local function normalizedwriteable(name,finalized)
- local valid=validfilename(name,"w")
- if valid then
- return normalized(valid)
- end
-end
-validators.readable=readable
-validators.writeable=normalizedwriteable
-validators.normalizedreadable=normalizedreadable
-validators.normalizedwriteable=writeable
-validators.filename=readable
-table.setmetatableindex(validators,function(t,k)
- if k then
- t[k]=readable
- end
- return readable
-end)
-function validators.string(s,finalized)
- if finalized and suspicious(s) then
- return ""
- else
- return s
- end
-end
-function validators.cache(s)
- if finalized then
- return basename(s)
- else
- return s
- end
-end
-function validators.url(s)
- if finalized and find("^file:") then
- return ""
- else
- return s
- end
-end
-local function filehandlerone(action,one,...)
- local checkedone=validfilename(one)
- if checkedone then
- return action(one,...)
- else
- end
-end
-local function filehandlertwo(action,one,two,...)
- local checkedone=validfilename(one)
- if checkedone then
- local checkedtwo=validfilename(two)
- if checkedtwo then
- return action(one,two,...)
- else
- end
- else
- end
-end
-local function iohandler(action,one,...)
- if type(one)=="string" then
- local checkedone=validfilename(one)
- if checkedone then
- return action(one,...)
- end
- elseif one then
- return action(one,...)
- else
- return action()
- end
-end
-local osexecute=sandbox.original(os.execute)
-local iopopen=sandbox.original(io.popen)
-local reported={}
-local function validcommand(name,program,template,checkers,defaults,variables,reporter,strict)
- if validbinaries~=false and (validbinaries==true or validbinaries[program]) then
- local binpath=nil
- if variables then
- for variable,value in next,variables do
- local chktype=checkers[variable]
- if chktype=="verbose" then
- else
- local checker=validators[chktype]
- if checker then
- value=checker(unquoted(value),strict)
- if value then
- variables[variable]=optionalquoted(value)
- else
- report("variable %a with value %a fails the check",variable,value)
- return
- end
- else
- report("variable %a has no checker",variable)
- return
- end
- end
- end
- for variable,default in next,defaults do
- local value=variables[variable]
- if not value or value=="" then
- local chktype=checkers[variable]
- if chktype=="verbose" then
- else
- local checker=validators[chktype]
- if checker then
- default=checker(unquoted(default),strict)
- if default then
- variables[variable]=optionalquoted(default)
- else
- report("variable %a with default %a fails the check",variable,default)
- return
- end
- end
- end
- end
- end
- binpath=variables.binarypath
- end
- if type(binpath)=="string" and binpath~="" then
- program=binpath.."/"..program
- end
- local command=program.." "..replace(template,variables)
- if reporter then
- reporter("executing runner %a: %s",name,command)
- elseif trace then
- report("executing runner %a: %s",name,command)
- end
- return command
- elseif not reported[name] then
- report("executing program %a of runner %a is not permitted",program,name)
- reported[name]=true
- end
-end
-local runners={
- resultof=function(...)
- local command=validcommand(...)
- if command then
- if trace then
- report("resultof: %s",command)
- end
- local handle=iopopen(command,"r")
- if handle then
- local result=handle:read("*all") or ""
- handle:close()
- return result
- end
- end
- end,
- execute=function(...)
- local command=validcommand(...)
- if command then
- if trace then
- report("execute: %s",command)
- end
- local okay=osexecute(command)
- return okay
- end
- end,
- pipeto=function(...)
- local command=validcommand(...)
- if command then
- if trace then
- report("pipeto: %s",command)
- end
- return iopopen(command,"w")
- end
- end,
-}
-function sandbox.registerrunner(specification)
- if type(specification)=="string" then
- local wrapped=validrunners[specification]
- inspect(table.sortedkeys(validrunners))
- if wrapped then
- return wrapped
- else
- report("unknown predefined runner %a",specification)
- return
- end
- end
- if type(specification)~="table" then
- report("specification should be a table (or string)")
- return
- end
- local name=specification.name
- if type(name)~="string" then
- report("invalid name, string expected",name)
- return
- end
- if validrunners[name] then
- report("invalid name, runner %a already defined",name)
- return
- end
- local program=specification.program
- if type(program)=="string" then
- elseif type(program)=="table" then
- program=program[platform] or program.default or program.unix
- end
- if type(program)~="string" or program=="" then
- report("invalid runner %a specified for platform %a",name,platform)
- return
- end
- local template=specification.template
- if not template then
- report("missing template for runner %a",name)
- return
- end
- local method=specification.method or "execute"
- local checkers=specification.checkers or {}
- local defaults=specification.defaults or {}
- local runner=runners[method]
- if runner then
- local finalized=finalized
- local wrapped=function(variables)
- return runner(name,program,template,checkers,defaults,variables,specification.reporter,finalized)
- end
- validrunners[name]=wrapped
- return wrapped
- else
- validrunners[name]=nil
- report("invalid method for runner %a",name)
- end
-end
-function sandbox.getrunner(name)
- return name and validrunners[name]
-end
-local function suspicious(str)
- return (find(str,"[/\\]") or find(command,"..",1,true)) and true or false
-end
-local function binaryrunner(action,command,...)
- if validbinaries==false then
- report("no binaries permitted, ignoring command: %s",command)
- return
- end
- if type(command)~="string" then
- report("command should be a string")
- return
- end
- local program=lpegmatch(p_split,command)
- if not program or program=="" then
- report("unable to filter binary from command: %s",command)
- return
- end
- if validbinaries==true then
- elseif not validbinaries[program] then
- report("binary not permitted, ignoring command: %s",command)
- return
- elseif suspicious(command) then
- report("/ \\ or .. found, ignoring command (use sandbox.registerrunner): %s",command)
- return
- end
- return action(command,...)
-end
-local function dummyrunner(action,command,...)
- if type(command)=="table" then
- command=concat(command," ",command[0] and 0 or 1)
- end
- report("ignoring command: %s",command)
-end
-sandbox.filehandlerone=filehandlerone
-sandbox.filehandlertwo=filehandlertwo
-sandbox.iohandler=iohandler
-function sandbox.disablerunners()
- validbinaries=false
-end
-function sandbox.disablelibraries()
- validlibraries=false
-end
-if FFISUPPORTED and ffi then
- function sandbox.disablelibraries()
- validlibraries=false
- for k,v in next,ffi do
- if k~="gc" then
- ffi[k]=nil
- end
- end
- end
- local fiiload=ffi.load
- if fiiload then
- local reported={}
- function ffi.load(name,...)
- if validlibraries==false then
- elseif validlibraries==true then
- return fiiload(name,...)
- elseif validlibraries[nameonly(name)] then
- return fiiload(name,...)
- else
- end
- if not reported[name] then
- report("using library %a is not permitted",name)
- reported[name]=true
- end
- return nil
- end
- end
-end
-local overload=sandbox.overload
-local register=sandbox.register
- overload(loadfile,filehandlerone,"loadfile")
-if io then
- overload(io.open,filehandlerone,"io.open")
- overload(io.popen,binaryrunner,"io.popen")
- overload(io.input,iohandler,"io.input")
- overload(io.output,iohandler,"io.output")
- overload(io.lines,filehandlerone,"io.lines")
-end
-if os then
- overload(os.execute,binaryrunner,"os.execute")
- overload(os.spawn,dummyrunner,"os.spawn")
- overload(os.exec,dummyrunner,"os.exec")
- overload(os.resultof,binaryrunner,"os.resultof")
- overload(os.pipeto,binaryrunner,"os.pipeto")
- overload(os.rename,filehandlertwo,"os.rename")
- overload(os.remove,filehandlerone,"os.remove")
-end
-if lfs then
- overload(lfs.chdir,filehandlerone,"lfs.chdir")
- overload(lfs.mkdir,filehandlerone,"lfs.mkdir")
- overload(lfs.rmdir,filehandlerone,"lfs.rmdir")
- overload(lfs.isfile,filehandlerone,"lfs.isfile")
- overload(lfs.isdir,filehandlerone,"lfs.isdir")
- overload(lfs.attributes,filehandlerone,"lfs.attributes")
- overload(lfs.dir,filehandlerone,"lfs.dir")
- overload(lfs.lock_dir,filehandlerone,"lfs.lock_dir")
- overload(lfs.touch,filehandlerone,"lfs.touch")
- overload(lfs.link,filehandlertwo,"lfs.link")
- overload(lfs.setmode,filehandlerone,"lfs.setmode")
- overload(lfs.readlink,filehandlerone,"lfs.readlink")
- overload(lfs.shortname,filehandlerone,"lfs.shortname")
- overload(lfs.symlinkattributes,filehandlerone,"lfs.symlinkattributes")
-end
-if zip then
- zip.open=register(zip.open,filehandlerone,"zip.open")
-end
-sandbox.registerroot=registerroot
-sandbox.registerbinary=registerbinary
-sandbox.registerlibrary=registerlibrary
-sandbox.validfilename=validfilename
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-mrg"] = package.loaded["util-mrg"] or true
-
--- original size: 7819, stripped down to: 5881
-
-if not modules then modules={} end modules ['util-mrg']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local gsub,format=string.gsub,string.format
-local concat=table.concat
-local type,next=type,next
-local P,R,S,V,Ct,C,Cs,Cc,Cp,Cmt,Cb,Cg=lpeg.P,lpeg.R,lpeg.S,lpeg.V,lpeg.Ct,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Cp,lpeg.Cmt,lpeg.Cb,lpeg.Cg
-local lpegmatch,patterns=lpeg.match,lpeg.patterns
-utilities=utilities or {}
-local merger=utilities.merger or {}
-utilities.merger=merger
-merger.strip_comment=true
-local report=logs.reporter("system","merge")
-utilities.report=report
-local m_begin_merge="begin library merge"
-local m_end_merge="end library merge"
-local m_begin_closure="do -- create closure to overcome 200 locals limit"
-local m_end_closure="end -- of closure"
-local m_pattern="%c+".."%-%-%s+"..m_begin_merge.."%c+(.-)%c+".."%-%-%s+"..m_end_merge.."%c+"
-local m_format="\n\n-- "..m_begin_merge.."\n%s\n".."-- "..m_end_merge.."\n\n"
-local m_faked="-- ".."created merged file".."\n\n".."-- "..m_begin_merge.."\n\n".."-- "..m_end_merge.."\n\n"
-local m_report=[[
--- used libraries : %s
--- skipped libraries : %s
--- original bytes : %s
--- stripped bytes : %s
-]]
-local m_preloaded=[[package.loaded[%q] = package.loaded[%q] or true]]
-local function self_fake()
- return m_faked
-end
-local function self_nothing()
- return ""
-end
-local function self_load(name)
- local data=io.loaddata(name) or ""
- if data=="" then
- report("unknown file %a",name)
- else
- report("inserting file %a",name)
- end
- return data or ""
-end
-local space=patterns.space
-local eol=patterns.newline
-local equals=P("=")^0
-local open=P("[")*Cg(equals,"init")*P("[")*P("\n")^-1
-local close=P("]")*C(equals)*P("]")
-local closeeq=Cmt(close*Cb("init"),function(s,i,a,b) return a==b end)
-local longstring=open*(1-closeeq)^0*close
-local quoted=patterns.quoted
-local digit=patterns.digit
-local emptyline=space^0*eol
-local operator1=P("<=")+P(">=")+P("~=")+P("..")+S("/^<>=*+%%")
-local operator2=S("*+/")
-local operator3=S("-")
-local operator4=P("..")
-local separator=S(",;")
-local ignore=(P("]")*space^1*P("=")*space^1*P("]"))/"]=["+(P("=")*space^1*P("{"))/"={"+(P("(")*space^1)/"("+(P("{")*(space+eol)^1*P("}"))/"{}"
-local strings=quoted
-local longcmt=(emptyline^0*P("--")*longstring*emptyline^0)/""
-local longstr=longstring
-local comment=emptyline^0*P("--")*P("-")^0*(1-eol)^0*emptyline^1/"\n"
-local optionalspaces=space^0/""
-local mandatespaces=space^1/""
-local optionalspacing=(eol+space)^0/""
-local mandatespacing=(eol+space)^1/""
-local pack=digit*space^1*operator4*optionalspacing+optionalspacing*operator1*optionalspacing+optionalspacing*operator2*optionalspaces+mandatespacing*operator3*mandatespaces+optionalspaces*separator*optionalspaces
-local lines=emptyline^2/"\n"
-local spaces=(space*space)/" "
-local spaces=(space*space*space*space)/" "
-local compact=Cs ((
- ignore+strings+longcmt+longstr+comment+pack+lines+spaces+1
-)^1 )
-local strip=Cs((emptyline^2/"\n"+1)^0)
-local stripreturn=Cs((1-P("return")*space^1*P(1-space-eol)^1*(space+eol)^0*P(-1))^1)
-function merger.compact(data)
- return lpegmatch(strip,lpegmatch(compact,data))
-end
-local function self_compact(data)
- local delta=0
- if merger.strip_comment then
- local before=#data
- data=lpegmatch(compact,data)
- data=lpegmatch(strip,data)
- local after=#data
- delta=before-after
- report("original size %s, compacted to %s, stripped %s",before,after,delta)
- data=format("-- original size: %s, stripped down to: %s\n\n%s",before,after,data)
- end
- return lpegmatch(stripreturn,data) or data,delta
-end
-local function self_save(name,data)
- if data~="" then
- io.savedata(name,data)
- report("saving %s with size %s",name,#data)
- end
-end
-local function self_swap(data,code)
- return data~="" and (gsub(data,m_pattern,function() return format(m_format,code) end,1)) or ""
-end
-local function self_libs(libs,list)
- local result,f,frozen,foundpath={},nil,false,nil
- result[#result+1]="\n"
- if type(libs)=='string' then libs={ libs } end
- if type(list)=='string' then list={ list } end
- for i=1,#libs do
- local lib=libs[i]
- for j=1,#list do
- local pth=gsub(list[j],"\\","/")
- report("checking library path %a",pth)
- local name=pth.."/"..lib
- if lfs.isfile(name) then
- foundpath=pth
- end
- end
- if foundpath then break end
- end
- if foundpath then
- report("using library path %a",foundpath)
- local right,wrong,original,stripped={},{},0,0
- for i=1,#libs do
- local lib=libs[i]
- local fullname=foundpath.."/"..lib
- if lfs.isfile(fullname) then
- report("using library %a",fullname)
- local preloaded=file.nameonly(lib)
- local data=io.loaddata(fullname,true)
- original=original+#data
- local data,delta=self_compact(data)
- right[#right+1]=lib
- result[#result+1]=m_begin_closure
- result[#result+1]=format(m_preloaded,preloaded,preloaded)
- result[#result+1]=data
- result[#result+1]=m_end_closure
- stripped=stripped+delta
- else
- report("skipping library %a",fullname)
- wrong[#wrong+1]=lib
- end
- end
- right=#right>0 and concat(right," ") or "-"
- wrong=#wrong>0 and concat(wrong," ") or "-"
- report("used libraries: %a",right)
- report("skipped libraries: %a",wrong)
- report("original bytes: %a",original)
- report("stripped bytes: %a",stripped)
- result[#result+1]=format(m_report,right,wrong,original,stripped)
- else
- report("no valid library path found")
- end
- return concat(result,"\n\n")
-end
-function merger.selfcreate(libs,list,target)
- if target then
- self_save(target,self_swap(self_fake(),self_libs(libs,list)))
- end
-end
-function merger.selfmerge(name,libs,list,target)
- self_save(target or name,self_swap(self_load(name),self_libs(libs,list)))
-end
-function merger.selfclean(name)
- self_save(name,self_swap(self_load(name),self_nothing()))
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-env"] = package.loaded["util-env"] or true
-
--- original size: 9738, stripped down to: 5531
-
-if not modules then modules={} end modules ['util-env']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local allocate,mark=utilities.storage.allocate,utilities.storage.mark
-local format,sub,match,gsub,find=string.format,string.sub,string.match,string.gsub,string.find
-local unquoted,quoted,optionalquoted=string.unquoted,string.quoted,string.optionalquoted
-local concat,insert,remove=table.concat,table.insert,table.remove
-environment=environment or {}
-local environment=environment
-local setlocale=os.setlocale
-setlocale(nil,nil)
-local report=logs.reporter("system")
-function os.setlocale(a,b)
- if a or b then
- if report then
- report()
- report("You're messing with os.locale in a supposedly locale neutral enviroment. From")
- report("now on are on your own and without support. Crashes or unexpected side effects")
- report("can happen but don't bother the luatex and context developer team with it.")
- report()
- report=nil
- end
- setlocale(a,b)
- end
-end
-local validengines=allocate {
- ["luatex"]=true,
- ["luajittex"]=true,
-}
-local basicengines=allocate {
- ["luatex"]="luatex",
- ["texlua"]="luatex",
- ["texluac"]="luatex",
- ["luajittex"]="luajittex",
- ["texluajit"]="luajittex",
-}
-local luaengines=allocate {
- ["lua"]=true,
- ["luajit"]=true,
-}
-environment.validengines=validengines
-environment.basicengines=basicengines
-if not arg then
- environment.used_as_library=true
-elseif luaengines[file.removesuffix(arg[-1])] then
-elseif validengines[file.removesuffix(arg[0])] then
- if arg[1]=="--luaonly" then
- arg[-1]=arg[0]
- arg[ 0]=arg[2]
- for k=3,#arg do
- arg[k-2]=arg[k]
- end
- remove(arg)
- remove(arg)
- else
- end
- local originalzero=file.basename(arg[0])
- local specialmapping={ luatools=="base" }
- if originalzero~="mtxrun" and originalzero~="mtxrun.lua" then
- arg[0]=specialmapping[originalzero] or originalzero
- insert(arg,0,"--script")
- insert(arg,0,"mtxrun")
- end
-end
-environment.arguments=allocate()
-environment.files=allocate()
-environment.sortedflags=nil
-function environment.initializearguments(arg)
- local arguments={}
- local files={}
- environment.arguments=arguments
- environment.files=files
- environment.sortedflags=nil
- for index=1,#arg do
- local argument=arg[index]
- if index>0 then
- local flag,value=match(argument,"^%-+(.-)=(.-)$")
- if flag then
- flag=gsub(flag,"^c:","")
- arguments[flag]=unquoted(value or "")
- else
- flag=match(argument,"^%-+(.+)")
- if flag then
- flag=gsub(flag,"^c:","")
- arguments[flag]=true
- else
- files[#files+1]=argument
- end
- end
- end
- end
- if not environment.ownname then
- if os.selfpath and os.selfname then
- environment.ownname=file.addsuffix(file.join(os.selfpath,os.selfname),"lua")
- end
- end
- environment.ownname=file.reslash(environment.ownname or arg[0] or 'unknown.lua')
-end
-function environment.setargument(name,value)
- environment.arguments[name]=value
-end
-function environment.getargument(name,partial)
- local arguments,sortedflags=environment.arguments,environment.sortedflags
- if arguments[name] then
- return arguments[name]
- elseif partial then
- if not sortedflags then
- sortedflags=allocate(table.sortedkeys(arguments))
- for k=1,#sortedflags do
- sortedflags[k]="^"..sortedflags[k]
- end
- environment.sortedflags=sortedflags
- end
- for k=1,#sortedflags do
- local v=sortedflags[k]
- if find(name,v) then
- return arguments[sub(v,2,#v)]
- end
- end
- end
- return nil
-end
-environment.argument=environment.getargument
-function environment.splitarguments(separator)
- local done,before,after=false,{},{}
- local originalarguments=environment.originalarguments
- for k=1,#originalarguments do
- local v=originalarguments[k]
- if not done and v==separator then
- done=true
- elseif done then
- after[#after+1]=v
- else
- before[#before+1]=v
- end
- end
- return before,after
-end
-function environment.reconstructcommandline(arg,noquote)
- local resolveprefix=resolvers.resolve
- arg=arg or environment.originalarguments
- if noquote and #arg==1 then
- return unquoted(resolveprefix and resolveprefix(arg[1]) or arg[1])
- elseif #arg>0 then
- local result={}
- for i=1,#arg do
- result[i]=optionalquoted(resolveprefix and resolveprefix(arg[i]) or resolveprefix)
- end
- return concat(result," ")
- else
- return ""
- end
-end
-function environment.relativepath(path,root)
- if not path then
- path=""
- end
- if not file.is_rootbased_path(path) then
- if not root then
- root=file.pathpart(environment.ownscript or environment.ownname or ".")
- end
- if root=="" then
- root="."
- end
- path=root.."/"..path
- end
- return file.collapsepath(path,true)
-end
-if arg then
- local newarg,instring={},false
- for index=1,#arg do
- local argument=arg[index]
- if find(argument,"^\"") then
- if find(argument,"\"$") then
- newarg[#newarg+1]=gsub(argument,"^\"(.-)\"$","%1")
- instring=false
- else
- newarg[#newarg+1]=gsub(argument,"^\"","")
- instring=true
- end
- elseif find(argument,"\"$") then
- if instring then
- newarg[#newarg]=newarg[#newarg].." "..gsub(argument,"\"$","")
- instring=false
- else
- newarg[#newarg+1]=argument
- end
- elseif instring then
- newarg[#newarg]=newarg[#newarg].." "..argument
- else
- newarg[#newarg+1]=argument
- end
- end
- for i=1,-5,-1 do
- newarg[i]=arg[i]
- end
- environment.initializearguments(newarg)
- environment.originalarguments=mark(newarg)
- environment.rawarguments=mark(arg)
- arg={}
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["luat-env"] = package.loaded["luat-env"] or true
-
--- original size: 6267, stripped down to: 4115
-
- if not modules then modules={} end modules ['luat-env']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local rawset,loadfile=rawset,loadfile
-local gsub=string.gsub
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_lua=logs.reporter("resolvers","lua")
-local luautilities=utilities.lua
-local luasuffixes=luautilities.suffixes
-local texgettoks=tex and tex.gettoks
-environment=environment or {}
-local environment=environment
-local mt={
- __index=function(_,k)
- if k=="version" then
- local version=texgettoks and texgettoks("contextversiontoks")
- if version and version~="" then
- rawset(environment,"version",version)
- return version
- else
- return "unknown"
- end
- elseif k=="jobname" or k=="formatname" then
- local name=tex and tex[k]
- if name or name=="" then
- rawset(environment,k,name)
- return name
- else
- return "unknown"
- end
- elseif k=="outputfilename" then
- local name=environment.jobname
- rawset(environment,k,name)
- return name
- end
- end
-}
-setmetatable(environment,mt)
-function environment.texfile(filename)
- return resolvers.findfile(filename,'tex')
-end
-function environment.luafile(filename)
- if CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and file.suffix(filename)=="lua" then
- local resolved=resolvers.findfile(file.replacesuffix(filename,"lmt")) or ""
- if resolved~="" then
- return resolved
- end
- end
- local resolved=resolvers.findfile(filename,'tex') or ""
- if resolved~="" then
- return resolved
- end
- resolved=resolvers.findfile(filename,'texmfscripts') or ""
- if resolved~="" then
- return resolved
- end
- return resolvers.findfile(filename,'luatexlibs') or ""
-end
-local stripindeed=false directives.register("system.compile.strip",function(v) stripindeed=v end)
-local function strippable(filename)
- if stripindeed then
- local modu=modules[file.nameonly(filename)]
- return modu and modu.dataonly
- else
- return false
- end
-end
-function environment.luafilechunk(filename,silent,macros)
- filename=file.replacesuffix(filename,"lua")
- local fullname=environment.luafile(filename)
- if fullname and fullname~="" then
- local data=luautilities.loadedluacode(fullname,strippable,filename,macros)
- if not silent then
- report_lua("loading file %a %s",fullname,not data and "failed" or "succeeded")
- end
- return data
- else
- if not silent then
- report_lua("unknown file %a",filename)
- end
- return nil
- end
-end
-function environment.loadluafile(filename,version)
- local lucname,luaname,chunk
- local basename=file.removesuffix(filename)
- if basename==filename then
- luaname=file.addsuffix(basename,luasuffixes.lua)
- lucname=file.addsuffix(basename,luasuffixes.luc)
- else
- luaname=filename
- lucname=nil
- end
- local fullname=(lucname and environment.luafile(lucname)) or ""
- if fullname~="" then
- if trace_locating then
- report_lua("loading %a",fullname)
- end
- chunk=loadfile(fullname)
- end
- if chunk then
- chunk()
- if version then
- local v=version
- if modules and modules[filename] then
- v=modules[filename].version
- elseif versions and versions[filename] then
- v=versions[filename]
- end
- if v==version then
- return true
- else
- if trace_locating then
- report_lua("version mismatch for %a, lua version %a, luc version %a",filename,v,version)
- end
- environment.loadluafile(filename)
- end
- else
- return true
- end
- end
- fullname=(luaname and environment.luafile(luaname)) or ""
- if fullname~="" then
- if trace_locating then
- report_lua("loading %a",fullname)
- end
- chunk=loadfile(fullname)
- if not chunk then
- if trace_locating then
- report_lua("unknown file %a",filename)
- end
- else
- chunk()
- return true
- end
- end
- return false
-end
-environment.filenames=setmetatable({},{
- __index=function(t,k)
- local v=environment.files[k]
- if v then
- return (gsub(v,"%.+$",""))
- end
- end,
- __newindex=function(t,k)
- end,
- __len=function(t)
- return #environment.files
- end,
-} )
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-zip"] = package.loaded["util-zip"] or true
-
--- original size: 19496, stripped down to: 10858
-
-if not modules then modules={} end modules ['util-zip']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,tostring,tonumber=type,tostring,tonumber
-local sort=table.sort
-local find,format,sub,gsub=string.find,string.format,string.sub,string.gsub
-local osdate,ostime,osclock=os.date,os.time,os.clock
-local ioopen=io.open
-local loaddata,savedata=io.loaddata,io.savedata
-local filejoin,isdir,dirname,mkdirs=file.join,lfs.isdir,file.dirname,dir.mkdirs
-local files=utilities.files
-local openfile=files.open
-local closefile=files.close
-local readstring=files.readstring
-local readcardinal2=files.readcardinal2le
-local readcardinal4=files.readcardinal4le
-local setposition=files.setposition
-local getposition=files.getposition
-local band=bit32.band
-local rshift=bit32.rshift
-local lshift=bit32.lshift
-local decompress,expandsize,calculatecrc
- local zlibdecompress=zlib.decompress
- local zlibexpandsize=zlib.expandsize
- local zlibchecksum=zlib.crc32
- decompress=function(source)
- return zlibdecompress(source,-15)
- end
- expandsize=zlibexpandsize and function(source,targetsize)
- return zlibexpandsize(source,targetsize,-15)
- end or decompress
- calculatecrc=function(buffer,initial)
- return zlibchecksum(initial or 0,buffer)
- end
-local zipfiles={}
-utilities.zipfiles=zipfiles
-local openzipfile,closezipfile,unzipfile,foundzipfile,getziphash,getziplist do
- function openzipfile(name)
- return {
- name=name,
- handle=openfile(name,0),
- }
- end
- local function collect(z)
- if not z.list then
- local list={}
- local hash={}
- local position=0
- local index=0
- local handle=z.handle
- while true do
- setposition(handle,position)
- local signature=readstring(handle,4)
- if signature=="PK\3\4" then
- local version=readcardinal2(handle)
- local flag=readcardinal2(handle)
- local method=readcardinal2(handle)
- local filetime=readcardinal2(handle)
- local filedate=readcardinal2(handle)
- local crc32=readcardinal4(handle)
- local compressed=readcardinal4(handle)
- local uncompressed=readcardinal4(handle)
- local namelength=readcardinal2(handle)
- local extralength=readcardinal2(handle)
- local filename=readstring(handle,namelength)
- local descriptor=band(flag,8)~=0
- local encrypted=band(flag,1)~=0
- local acceptable=method==0 or method==8
- local skipped=0
- local size=0
- if encrypted then
- size=readcardinal2(handle)
- skipbytes(size)
- skipped=skipped+size+2
- skipbytes(8)
- skipped=skipped+8
- size=readcardinal2(handle)
- skipbytes(size)
- skipped=skipped+size+2
- size=readcardinal4(handle)
- skipbytes(size)
- skipped=skipped+size+4
- size=readcardinal2(handle)
- skipbytes(size)
- skipped=skipped+size+2
- end
- position=position+30+namelength+extralength+skipped
- if descriptor then
- setposition(handle,position+compressed)
- crc32=readcardinal4(handle)
- compressed=readcardinal4(handle)
- uncompressed=readcardinal4(handle)
- end
- if acceptable then
- index=index+1
- local data={
- filename=filename,
- index=index,
- position=position,
- method=method,
- compressed=compressed,
- uncompressed=uncompressed,
- crc32=crc32,
- encrypted=encrypted,
- }
- hash[filename]=data
- list[index]=data
- else
- end
- position=position+compressed
- else
- break
- end
- z.list=list
- z.hash=hash
- end
- end
- end
- function getziplist(z)
- local list=z.list
- if not list then
- collect(z)
- end
- return z.list
- end
- function getziphash(z)
- local hash=z.hash
- if not hash then
- collect(z)
- end
- return z.hash
- end
- function foundzipfile(z,name)
- return getziphash(z)[name]
- end
- function closezipfile(z)
- local f=z.handle
- if f then
- closefile(f)
- z.handle=nil
- end
- end
- function unzipfile(z,filename,check)
- local hash=z.hash
- if not hash then
- hash=zipfiles.hash(z)
- end
- local data=hash[filename]
- if not data then
- end
- if data then
- local handle=z.handle
- local position=data.position
- local compressed=data.compressed
- if compressed>0 then
- setposition(handle,position)
- local result=readstring(handle,compressed)
- if data.method==8 then
- if expandsize then
- result=expandsize(result,data.uncompressed)
- else
- result=decompress(result)
- end
- end
- if check and data.crc32~=calculatecrc(result) then
- print("checksum mismatch")
- return ""
- end
- return result
- else
- return ""
- end
- end
- end
- zipfiles.open=openzipfile
- zipfiles.close=closezipfile
- zipfiles.unzip=unzipfile
- zipfiles.hash=getziphash
- zipfiles.list=getziplist
- zipfiles.found=foundzipfile
-end
-if xzip then
- local writecardinal1=files.writebyte
- local writecardinal2=files.writecardinal2le
- local writecardinal4=files.writecardinal4le
- local logwriter=logs.writer
- local globpattern=dir.globpattern
- local compress=xzip.compress
- local checksum=xzip.crc32
- local function fromdostime(dostime,dosdate)
- return ostime {
- year=rshift(dosdate,9)+1980,
- month=band(rshift(dosdate,5),0x0F),
- day=band((dosdate ),0x1F),
- hour=band(rshift(dostime,11) ),
- min=band(rshift(dostime,5),0x3F),
- sec=band((dostime ),0x1F),
- }
- end
- local function todostime(time)
- local t=osdate("*t",time)
- return
- lshift(t.year-1980,9)+lshift(t.month,5)+t.day,
- lshift(t.hour,11)+lshift(t.min,5)+rshift(t.sec,1)
- end
- local function openzip(filename,level,comment,verbose)
- local f=ioopen(filename,"wb")
- if f then
- return {
- filename=filename,
- handle=f,
- list={},
- level=tonumber(level) or 3,
- comment=tostring(comment),
- verbose=verbose,
- uncompressed=0,
- compressed=0,
- }
- end
- end
- local function writezip(z,name,data,level,time)
- local f=z.handle
- local list=z.list
- local level=tonumber(level) or z.level or 3
- local method=8
- local zipped=compress(data,level)
- local checksum=checksum(data)
- local verbose=z.verbose
- if not zipped then
- method=0
- zipped=data
- end
- local start=f:seek()
- local compressed=#zipped
- local uncompressed=#data
- z.compressed=z.compressed+compressed
- z.uncompressed=z.uncompressed+uncompressed
- if verbose then
- local pct=100*compressed/uncompressed
- if pct>=100 then
- logwriter(format("%10i %s",uncompressed,name))
- else
- logwriter(format("%10i %02.1f %s",uncompressed,pct,name))
- end
- end
- f:write("\x50\x4b\x03\x04")
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,method)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal4(f,checksum)
- writecardinal4(f,compressed)
- writecardinal4(f,uncompressed)
- writecardinal2(f,#name)
- writecardinal2(f,0)
- f:write(name)
- f:write(zipped)
- list[#list+1]={ #zipped,#data,name,checksum,start,time or 0 }
- end
- local function closezip(z)
- local f=z.handle
- local list=z.list
- local comment=z.comment
- local verbose=z.verbose
- local count=#list
- local start=f:seek()
- for i=1,count do
- local l=list[i]
- local compressed=l[1]
- local uncompressed=l[2]
- local name=l[3]
- local checksum=l[4]
- local start=l[5]
- local time=l[6]
- local date,time=todostime(time)
- f:write('\x50\x4b\x01\x02')
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,8)
- writecardinal2(f,time)
- writecardinal2(f,date)
- writecardinal4(f,checksum)
- writecardinal4(f,compressed)
- writecardinal4(f,uncompressed)
- writecardinal2(f,#name)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal4(f,0)
- writecardinal4(f,start)
- f:write(name)
- end
- local stop=f:seek()
- local size=stop-start
- f:write('\x50\x4b\x05\x06')
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,count)
- writecardinal2(f,count)
- writecardinal4(f,size)
- writecardinal4(f,start)
- if type(comment)=="string" and comment~="" then
- writecardinal2(f,#comment)
- f:write(comment)
- else
- writecardinal2(f,0)
- end
- if verbose then
- local compressed=z.compressed
- local uncompressed=z.uncompressed
- local filename=z.filename
- local pct=100*compressed/uncompressed
- logwriter("")
- if pct>=100 then
- logwriter(format("%10i %s",uncompressed,filename))
- else
- logwriter(format("%10i %02.1f %s",uncompressed,pct,filename))
- end
- end
- f:close()
- end
- local function zipdir(zipname,path,level,verbose)
- if type(zipname)=="table" then
- verbose=zipname.verbose
- level=zipname.level
- path=zipname.path
- zipname=zipname.zipname
- end
- if not zipname or zipname=="" then
- return
- end
- if not path or path=="" then
- path="."
- end
- if not isdir(path) then
- return
- end
- path=gsub(path,"\\+","/")
- path=gsub(path,"/+","/")
- local list={}
- local count=0
- globpattern(path,"",true,function(name,size,time)
- count=count+1
- list[count]={ name,time }
- end)
- sort(list,function(a,b)
- return a[1]<b[1]
- end)
- local zipf=openzip(zipname,level,comment,verbose)
- if zipf then
- local p=#path+2
- for i=1,count do
- local li=list[i]
- local name=li[1]
- local time=li[2]
- local data=loaddata(name)
- local name=sub(name,p,#name)
- writezip(zipf,name,data,level,time,verbose)
- end
- closezip(zipf)
- end
- end
- local function unzipdir(zipname,path,verbose)
- if type(zipname)=="table" then
- verbose=zipname.verbose
- path=zipname.path
- zipname=zipname.zipname
- end
- if not zipname or zipname=="" then
- return
- end
- if not path or path=="" then
- path="."
- end
- local z=openzipfile(zipname)
- if z then
- local list=getziplist(z)
- if list then
- local total=0
- local count=#list
- local step=number.idiv(count,10)
- local done=0
- local steps=verbose=="steps"
- local time=steps and osclock()
- for i=1,count do
- local l=list[i]
- local n=l.filename
- local d=unzipfile(z,n)
- if d then
- local p=filejoin(path,n)
- if mkdirs(dirname(p)) then
- if steps then
- total=total+#d
- done=done+1
- if done>=step then
- done=0
- logwriter(format("%4i files of %4i done, %10i bytes, %0.3f seconds",i,count,total,osclock()-time))
- end
- elseif verbose then
- logwriter(n)
- end
- savedata(p,d)
- end
- else
- logwriter(format("problem with file %s",n))
- end
- end
- if steps then
- logwriter(format("%4i files of %4i done, %10i bytes, %0.3f seconds",count,count,total,osclock()-time))
- end
- closezipfile(z)
- return true
- else
- closezipfile(z)
- end
- end
- end
- zipfiles.zipdir=zipdir
- zipfiles.unzipdir=unzipdir
-end
-zipfiles.gunzipfile=gzip.load
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-tab"] = package.loaded["lxml-tab"] or true
-
--- original size: 61808, stripped down to: 36227
-
-if not modules then modules={} end modules ['lxml-tab']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local trace_entities=false trackers.register("xml.entities",function(v) trace_entities=v end)
-local report_xml=logs and logs.reporter("xml","core") or function(...) print(string.format(...)) end
-if lpeg.setmaxstack then lpeg.setmaxstack(1000) end
-xml=xml or {}
-local xml=xml
-local concat,remove,insert=table.concat,table.remove,table.insert
-local type,next,setmetatable,getmetatable,tonumber,rawset,select=type,next,setmetatable,getmetatable,tonumber,rawset,select
-local lower,find,match,gsub=string.lower,string.find,string.match,string.gsub
-local sort=table.sort
-local utfchar=utf.char
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local P,S,R,C,V,C,Cs=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.V,lpeg.C,lpeg.Cs
-local formatters=string.formatters
-do
-xml.xmlns=xml.xmlns or {}
-local check=P(false)
-local parse=check
-function xml.registerns(namespace,pattern)
- check=check+C(P(lower(pattern)))/namespace
- parse=P { P(check)+1*V(1) }
-end
-function xml.checkns(namespace,url)
- local ns=lpegmatch(parse,lower(url))
- if ns and namespace~=ns then
- xml.xmlns[namespace]=ns
- end
-end
-function xml.resolvens(url)
- return lpegmatch(parse,lower(url)) or ""
-end
-end
-local nsremap,resolvens=xml.xmlns,xml.resolvens
-local stack,level,top,at,xmlnms,errorstr
-local entities,parameters
-local strip,utfize,resolve,cleanup,resolve_predefined,unify_predefined
-local dcache,hcache,acache
-local mt,dt,nt
-local currentfilename,currentline,linenumbers
-local grammar_parsed_text_one
-local grammar_parsed_text_two
-local grammar_unparsed_text
-local handle_hex_entity
-local handle_dec_entity
-local handle_any_entity_dtd
-local handle_any_entity_text
-local function preparexmlstate(settings)
- if settings then
- linenumbers=settings.linenumbers
- stack={}
- level=0
- top={}
- at={}
- mt={}
- dt={}
- nt=0
- xmlns={}
- errorstr=nil
- strip=settings.strip_cm_and_dt
- utfize=settings.utfize_entities
- resolve=settings.resolve_entities
- resolve_predefined=settings.resolve_predefined_entities
- unify_predefined=settings.unify_predefined_entities
- cleanup=settings.text_cleanup
- entities=settings.entities or {}
- currentfilename=settings.currentresource
- currentline=1
- parameters={}
- reported_at_errors={}
- dcache={}
- hcache={}
- acache={}
- if utfize==nil then
- settings.utfize_entities=true
- utfize=true
- end
- if resolve_predefined==nil then
- settings.resolve_predefined_entities=true
- resolve_predefined=true
- end
- else
- linenumbers=false
- stack=nil
- level=nil
- top=nil
- at=nil
- mt=nil
- dt=nil
- nt=nil
- xmlns=nil
- errorstr=nil
- strip=nil
- utfize=nil
- resolve=nil
- resolve_predefined=nil
- unify_predefined=nil
- cleanup=nil
- entities=nil
- parameters=nil
- reported_at_errors=nil
- dcache=nil
- hcache=nil
- acache=nil
- currentfilename=nil
- currentline=1
- end
-end
-local function initialize_mt(root)
- mt={ __index=root }
-end
-function xml.setproperty(root,k,v)
- getmetatable(root).__index[k]=v
-end
-function xml.checkerror(top,toclose)
- return ""
-end
-local checkns=xml.checkns
-local function add_attribute(namespace,tag,value)
- if cleanup and value~="" then
- value=cleanup(value)
- end
- if tag=="xmlns" then
- xmlns[#xmlns+1]=resolvens(value)
- at[tag]=value
- elseif namespace=="" then
- at[tag]=value
- elseif namespace=="xmlns" then
- checkns(tag,value)
- at["xmlns:"..tag]=value
- else
- at[namespace..":"..tag]=value
- end
-end
-local function add_empty(spacing,namespace,tag)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- local resolved=namespace=="" and xmlns[#xmlns] or nsremap[namespace] or namespace
- top=stack[level]
- dt=top.dt
- nt=#dt+1
- local t=linenumbers and {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt={},
- ni=nt,
- cf=currentfilename,
- cl=currentline,
- __p__=top,
- } or {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt={},
- ni=nt,
- __p__=top,
- }
- dt[nt]=t
- setmetatable(t,mt)
- if at.xmlns then
- remove(xmlns)
- end
- at={}
-end
-local function add_begin(spacing,namespace,tag)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- local resolved=namespace=="" and xmlns[#xmlns] or nsremap[namespace] or namespace
- dt={}
- top=linenumbers and {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt=dt,
- ni=nil,
- cf=currentfilename,
- cl=currentline,
- __p__=stack[level],
- } or {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt=dt,
- ni=nil,
- __p__=stack[level],
- }
- setmetatable(top,mt)
- nt=0
- level=level+1
- stack[level]=top
- at={}
-end
-local function add_end(spacing,namespace,tag)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- local toclose=stack[level]
- level=level-1
- top=stack[level]
- if level<1 then
- errorstr=formatters["unable to close %s %s"](tag,xml.checkerror(top,toclose) or "")
- report_xml(errorstr)
- elseif toclose.tg~=tag then
- errorstr=formatters["unable to close %s with %s %s"](toclose.tg,tag,xml.checkerror(top,toclose) or "")
- report_xml(errorstr)
- end
- dt=top.dt
- nt=#dt+1
- dt[nt]=toclose
- toclose.ni=nt
- if toclose.at.xmlns then
- remove(xmlns)
- end
-end
-local function add_text(text)
- if text=="" then
- return
- end
- if cleanup then
- if nt>0 then
- local s=dt[nt]
- if type(s)=="string" then
- dt[nt]=s..cleanup(text)
- else
- nt=nt+1
- dt[nt]=cleanup(text)
- end
- else
- nt=1
- dt[1]=cleanup(text)
- end
- else
- if nt>0 then
- local s=dt[nt]
- if type(s)=="string" then
- dt[nt]=s..text
- else
- nt=nt+1
- dt[nt]=text
- end
- else
- nt=1
- dt[1]=text
- end
- end
-end
-local function add_special(what,spacing,text)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- if strip and (what=="@cm@" or what=="@dt@") then
- else
- nt=nt+1
- dt[nt]=linenumbers and {
- special=true,
- ns="",
- tg=what,
- ni=nil,
- dt={ text },
- cf=currentfilename,
- cl=currentline,
- } or {
- special=true,
- ns="",
- tg=what,
- ni=nil,
- dt={ text },
- }
- end
-end
-local function set_message(txt)
- errorstr="garbage at the end of the file: "..gsub(txt,"([ \n\r\t]*)","")
-end
-local function attribute_value_error(str)
- if not reported_at_errors[str] then
- report_xml("invalid attribute value %a",str)
- reported_at_errors[str]=true
- at._error_=str
- end
- return str
-end
-local function attribute_specification_error(str)
- if not reported_at_errors[str] then
- report_xml("invalid attribute specification %a",str)
- reported_at_errors[str]=true
- at._error_=str
- end
- return str
-end
-do
- local badentity="&"
- xml.placeholders={
- unknown_dec_entity=function(str) return str=="" and badentity or formatters["&%s;"](str) end,
- unknown_hex_entity=function(str) return formatters["&#x%s;"](str) end,
- unknown_any_entity=function(str) return formatters["&#x%s;"](str) end,
- }
- local function fromhex(s)
- local n=tonumber(s,16)
- if n then
- return utfchar(n)
- else
- return formatters["h:%s"](s),true
- end
- end
- local function fromdec(s)
- local n=tonumber(s)
- if n then
- return utfchar(n)
- else
- return formatters["d:%s"](s),true
- end
- end
- local p_rest=(1-P(";"))^0
- local p_many=P(1)^0
- local parsedentity=P("&#")*(P("x")*(p_rest/fromhex)+(p_rest/fromdec))*P(";")*P(-1)+P ("#")*(P("x")*(p_many/fromhex)+(p_many/fromdec))
- xml.parsedentitylpeg=parsedentity
- local predefined_unified={
- [38]="&amp;",
- [42]="&quot;",
- [47]="&apos;",
- [74]="&lt;",
- [76]="&gt;",
- }
- local predefined_simplified={
- [38]="&",amp="&",
- [42]='"',quot='"',
- [47]="'",apos="'",
- [74]="<",lt="<",
- [76]=">",gt=">",
- }
- local nofprivates=0xF0000
- local privates_u={
- [ [[&]] ]="&amp;",
- [ [["]] ]="&quot;",
- [ [[']] ]="&apos;",
- [ [[<]] ]="&lt;",
- [ [[>]] ]="&gt;",
- }
- local privates_p={
- }
- local privates_s={
- [ [["]] ]="&U+22;",
- [ [[#]] ]="&U+23;",
- [ [[$]] ]="&U+24;",
- [ [[%]] ]="&U+25;",
- [ [[&]] ]="&U+26;",
- [ [[']] ]="&U+27;",
- [ [[<]] ]="&U+3C;",
- [ [[>]] ]="&U+3E;",
- [ [[\]] ]="&U+5C;",
- [ [[{]] ]="&U+7B;",
- [ [[|]] ]="&U+7C;",
- [ [[}]] ]="&U+7D;",
- [ [[~]] ]="&U+7E;",
- }
- local privates_x={
- [ [["]] ]="&U+22;",
- [ [[#]] ]="&U+23;",
- [ [[$]] ]="&U+24;",
- [ [[%]] ]="&U+25;",
- [ [[']] ]="&U+27;",
- [ [[\]] ]="&U+5C;",
- [ [[{]] ]="&U+7B;",
- [ [[|]] ]="&U+7C;",
- [ [[}]] ]="&U+7D;",
- [ [[~]] ]="&U+7E;",
- }
- local privates_n={
- }
- local escaped=utf.remapper(privates_u,"dynamic")
- local unprivatized=utf.remapper(privates_p,"dynamic")
- local unspecialized=utf.remapper(privates_s,"dynamic")
- local despecialized=utf.remapper(privates_x,"dynamic")
- xml.unprivatized=unprivatized
- xml.unspecialized=unspecialized
- xml.despecialized=despecialized
- xml.escaped=escaped
- local function unescaped(s)
- local p=privates_n[s]
- if not p then
- nofprivates=nofprivates+1
- p=utfchar(nofprivates)
- privates_n[s]=p
- s="&"..s..";"
- privates_u[p]=s
- privates_p[p]=s
- privates_s[p]=s
- end
- return p
- end
- xml.privatetoken=unescaped
- xml.privatecodes=privates_n
- xml.specialcodes=privates_s
- function xml.addspecialcode(key,value)
- privates_s[key]=value or "&"..s..";"
- end
- handle_hex_entity=function(str)
- local h=hcache[str]
- if not h then
- local n=tonumber(str,16)
- h=unify_predefined and predefined_unified[n]
- if h then
- if trace_entities then
- report_xml("utfize, converting hex entity &#x%s; into %a",str,h)
- end
- elseif utfize then
- h=(n and utfchar(n)) or xml.unknown_hex_entity(str) or ""
- if not n then
- report_xml("utfize, ignoring hex entity &#x%s;",str)
- elseif trace_entities then
- report_xml("utfize, converting hex entity &#x%s; into %a",str,h)
- end
- else
- if trace_entities then
- report_xml("found entity &#x%s;",str)
- end
- h="&#x"..str..";"
- end
- hcache[str]=h
- end
- return h
- end
- handle_dec_entity=function(str)
- local d=dcache[str]
- if not d then
- local n=tonumber(str)
- d=unify_predefined and predefined_unified[n]
- if d then
- if trace_entities then
- report_xml("utfize, converting dec entity &#%s; into %a",str,d)
- end
- elseif utfize then
- d=(n and utfchar(n)) or placeholders.unknown_dec_entity(str) or ""
- if not n then
- report_xml("utfize, ignoring dec entity &#%s;",str)
- elseif trace_entities then
- report_xml("utfize, converting dec entity &#%s; into %a",str,d)
- end
- else
- if trace_entities then
- report_xml("found entity &#%s;",str)
- end
- d="&#"..str..";"
- end
- dcache[str]=d
- end
- return d
- end
- handle_any_entity_dtd=function(str)
- if resolve then
- local a=resolve_predefined and predefined_simplified[str]
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to predefined %a",str,a)
- end
- else
- if type(resolve)=="function" then
- a=resolve(str,entities) or entities[str]
- else
- a=entities[str]
- end
- if a then
- if type(a)=="function" then
- if trace_entities then
- report_xml("expanding entity &%s; to function call",str)
- end
- a=a(str) or ""
- end
- a=lpegmatch(parsedentity,a) or a
- if trace_entities then
- report_xml("resolving entity &%s; to internal %a",str,a)
- end
- else
- local unknown_any_entity=placeholders.unknown_any_entity
- if unknown_any_entity then
- a=unknown_any_entity(str) or ""
- end
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to external %s",str,a)
- end
- else
- if trace_entities then
- report_xml("keeping entity &%s;",str)
- end
- if str=="" then
- a=badentity
- else
- a="&"..str..";"
- end
- end
- end
- end
- return a
- else
- local a=acache[str]
- if not a then
- a=resolve_predefined and predefined_simplified[str]
- if a then
- acache[str]=a
- if trace_entities then
- report_xml("entity &%s; becomes %a",str,a)
- end
- elseif str=="" then
- if trace_entities then
- report_xml("invalid entity &%s;",str)
- end
- a=badentity
- acache[str]=a
- else
- if trace_entities then
- report_xml("entity &%s; is made private",str)
- end
- a=unescaped(str)
- acache[str]=a
- end
- end
- return a
- end
- end
- handle_any_entity_text=function(str)
- if resolve then
- local a=resolve_predefined and predefined_simplified[str]
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to predefined %a",str,a)
- end
- else
- if type(resolve)=="function" then
- a=resolve(str,entities) or entities[str]
- else
- a=entities[str]
- end
- if a then
- if type(a)=="function" then
- if trace_entities then
- report_xml("expanding entity &%s; to function call",str)
- end
- a=a(str) or ""
- end
- a=lpegmatch(grammar_parsed_text_two,a) or a
- if type(a)=="number" then
- return ""
- else
- a=lpegmatch(parsedentity,a) or a
- if trace_entities then
- report_xml("resolving entity &%s; to internal %a",str,a)
- end
- end
- if trace_entities then
- report_xml("resolving entity &%s; to internal %a",str,a)
- end
- else
- local unknown_any_entity=placeholders.unknown_any_entity
- if unknown_any_entity then
- a=unknown_any_entity(str) or ""
- end
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to external %s",str,a)
- end
- else
- if trace_entities then
- report_xml("keeping entity &%s;",str)
- end
- if str=="" then
- a=badentity
- else
- a="&"..str..";"
- end
- end
- end
- end
- return a
- else
- local a=acache[str]
- if not a then
- a=resolve_predefined and predefined_simplified[str]
- if a then
- acache[str]=a
- if trace_entities then
- report_xml("entity &%s; becomes %a",str,a)
- end
- elseif str=="" then
- if trace_entities then
- report_xml("invalid entity &%s;",str)
- end
- a=badentity
- acache[str]=a
- else
- if trace_entities then
- report_xml("entity &%s; is made private",str)
- end
- a=unescaped(str)
- acache[str]=a
- end
- end
- return a
- end
- end
- local p_rest=(1-P(";"))^1
- local spec={
- [0x23]="\\Ux{23}",
- [0x24]="\\Ux{24}",
- [0x25]="\\Ux{25}",
- [0x5C]="\\Ux{5C}",
- [0x7B]="\\Ux{7B}",
- [0x7C]="\\Ux{7C}",
- [0x7D]="\\Ux{7D}",
- [0x7E]="\\Ux{7E}",
- }
- local hash=table.setmetatableindex(spec,function(t,k)
- local v=utfchar(k)
- t[k]=v
- return v
- end)
- local function fromuni(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["u:%s"](s),true
- end
- end
- local function fromhex(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["h:%s"](s),true
- end
- end
- local function fromdec(s)
- local n=tonumber(s)
- if n then
- return hash[n]
- else
- return formatters["d:%s"](s),true
- end
- end
- local reparsedentity=P("U+")*(p_rest/fromuni)+P("#")*(
- P("x")*(p_rest/fromhex)+p_rest/fromdec
- )
- local hash=table.setmetatableindex(function(t,k)
- local v=utfchar(k)
- t[k]=v
- return v
- end)
- local function fromuni(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["u:%s"](s),true
- end
- end
- local function fromhex(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["h:%s"](s),true
- end
- end
- local function fromdec(s)
- local n=tonumber(s)
- if n then
- return hash[n]
- else
- return formatters["d:%s"](s),true
- end
- end
- local unescapedentity=P("U+")*(p_rest/fromuni)+P("#")*(
- P("x")*(p_rest/fromhex)+p_rest/fromdec
- )
- xml.reparsedentitylpeg=reparsedentity
- xml.unescapedentitylpeg=unescapedentity
-end
-local escaped=xml.escaped
-local unescaped=xml.unescaped
-local placeholders=xml.placeholders
-local function handle_end_entity(str)
- report_xml("error in entity, %a found without ending %a",str,";")
- return str
-end
-local function handle_crap_error(chr)
- report_xml("error in parsing, unexpected %a found ",chr)
- add_text(chr)
- return chr
-end
-local function handlenewline()
- currentline=currentline+1
-end
-local spacetab=S(' \t')
-local space=S(' \r\n\t')
-local newline=lpegpatterns.newline/handlenewline
-local anything=P(1)
-local open=P('<')
-local close=P('>')
-local squote=S("'")
-local dquote=S('"')
-local equal=P('=')
-local slash=P('/')
-local colon=P(':')
-local semicolon=P(';')
-local ampersand=P('&')
-local valid_0=R("\128\255")
-local valid_1=R('az','AZ')+S('_')+valid_0
-local valid_2=valid_1+R('09')+S('-.')
-local valid=valid_1*valid_2^0
-local name_yes=C(valid^1)*colon*C(valid^1)
-local name_nop=C(P(true))*C(valid^1)
-local name=name_yes+name_nop
-local utfbom=lpegpatterns.utfbom
-local spacing=C(space^0)
-local space_nl=spacetab+newline
-local spacing_nl=Cs((space_nl)^0)
-local anything_nl=newline+P(1)
-local function weirdentity(k,v)
- if trace_entities then
- report_xml("registering %s entity %a as %a","weird",k,v)
- end
- parameters[k]=v
-end
-local function normalentity(k,v)
- if trace_entities then
- report_xml("registering %s entity %a as %a","normal",k,v)
- end
- entities[k]=v
-end
-local function systementity(k,v,n)
- if trace_entities then
- report_xml("registering %s entity %a as %a","system",k,v)
- end
- entities[k]=v
-end
-local function publicentity(k,v,n)
- if trace_entities then
- report_xml("registering %s entity %a as %a","public",k,v)
- end
- entities[k]=v
-end
-local function entityfile(pattern,k,v,n)
- if n then
- local okay,data
- local loadbinfile=resolvers and resolvers.loadbinfile
- if loadbinfile then
- okay,data=loadbinfile(n)
- else
- data=io.loaddata(n)
- okay=data and data~=""
- end
- if okay then
- if trace_entities then
- report_xml("loading public entities %a as %a from %a",k,v,n)
- end
- lpegmatch(pattern,data)
- return
- end
- end
- report_xml("ignoring public entities %a as %a from %a",k,v,n)
-end
-local function install(spacenewline,spacing,anything)
- local anyentitycontent=(1-open-semicolon-space-close-ampersand)^0
- local hexentitycontent=R("AF","af","09")^1
- local decentitycontent=R("09")^1
- local parsedentity=P("#")/""*(
- P("x")/""*(hexentitycontent/handle_hex_entity)+(decentitycontent/handle_dec_entity)
- )+(anyentitycontent/handle_any_entity_dtd)
- local parsedentity_text=P("#")/""*(
- P("x")/""*(hexentitycontent/handle_hex_entity)+(decentitycontent/handle_dec_entity)
- )+(anyentitycontent/handle_any_entity_text)
- local entity=(ampersand/"")*parsedentity*(semicolon/"")+ampersand*(anyentitycontent/handle_end_entity)
- local entity_text=(ampersand/"")*parsedentity_text*(semicolon/"")+ampersand*(anyentitycontent/handle_end_entity)
- local text_unparsed=Cs((anything-open)^1)
- local text_parsed=(Cs((anything-open-ampersand)^1)/add_text+Cs(entity_text)/add_text)^1
- local somespace=(spacenewline)^1
- local optionalspace=(spacenewline)^0
- local value=(squote*Cs((entity+(anything-squote))^0)*squote)+(dquote*Cs((entity+(anything-dquote))^0)*dquote)
- local endofattributes=slash*close+close
- local whatever=space*name*optionalspace*equal
- local wrongvalue=Cs(P(entity+(1-space-endofattributes))^1)/attribute_value_error
- local attributevalue=value+wrongvalue
- local attribute=(somespace*name*optionalspace*equal*optionalspace*attributevalue)/add_attribute
- local attributes=(attribute+somespace^-1*(((anything-endofattributes)^1)/attribute_specification_error))^0
- local parsedtext=text_parsed
- local unparsedtext=text_unparsed/add_text
- local balanced=P { "["*((anything-S"[]")+V(1))^0*"]" }
- local emptyelement=(spacing*open*name*attributes*optionalspace*slash*close)/add_empty
- local beginelement=(spacing*open*name*attributes*optionalspace*close)/add_begin
- local endelement=(spacing*open*slash*name*optionalspace*close)/add_end
- local begincomment=open*P("!--")
- local endcomment=P("--")*close
- local begininstruction=open*P("?")
- local endinstruction=P("?")*close
- local begincdata=open*P("![CDATA[")
- local endcdata=P("]]")*close
- local someinstruction=C((anything-endinstruction)^0)
- local somecomment=C((anything-endcomment )^0)
- local somecdata=C((anything-endcdata )^0)
- local begindoctype=open*P("!DOCTYPE")
- local enddoctype=close
- local beginset=P("[")
- local endset=P("]")
- local wrdtypename=C((anything-somespace-P(";"))^1)
- local doctypename=C((anything-somespace-close)^0)
- local elementdoctype=optionalspace*P("<!ELEMENT")*(anything-close)^0*close
- local basiccomment=begincomment*((anything-endcomment)^0)*endcomment
- local weirdentitytype=P("%")*(somespace*doctypename*somespace*value)/weirdentity
- local normalentitytype=(doctypename*somespace*value)/normalentity
- local publicentitytype=(doctypename*somespace*P("PUBLIC")*somespace*value)/publicentity
- local systementitytype=(doctypename*somespace*P("SYSTEM")*somespace*value*somespace*P("NDATA")*somespace*doctypename)/systementity
- local entitydoctype=optionalspace*P("<!ENTITY")*somespace*(systementitytype+publicentitytype+normalentitytype+weirdentitytype)*optionalspace*close
- local publicentityfile=(doctypename*somespace*P("PUBLIC")*somespace*value*(somespace*value)^0)/function(...)
- entityfile(entitydoctype,...)
- end
- local function weirdresolve(s)
- lpegmatch(entitydoctype,parameters[s])
- end
- local function normalresolve(s)
- lpegmatch(entitydoctype,entities[s])
- end
- local entityresolve=P("%")*(wrdtypename/weirdresolve )*P(";")+P("&")*(wrdtypename/normalresolve)*P(";")
- entitydoctype=entitydoctype+entityresolve
- local doctypeset=beginset*optionalspace*P(elementdoctype+entitydoctype+entityresolve+basiccomment+space)^0*optionalspace*endset
- local definitiondoctype=doctypename*somespace*doctypeset
- local publicdoctype=doctypename*somespace*P("PUBLIC")*somespace*value*somespace*value*somespace*doctypeset
- local systemdoctype=doctypename*somespace*P("SYSTEM")*somespace*value*somespace*doctypeset
- local simpledoctype=(anything-close)^1
- local somedoctype=C((somespace*(
-publicentityfile+publicdoctype+systemdoctype+definitiondoctype+simpledoctype)*optionalspace)^0)
- local instruction=(spacing*begininstruction*someinstruction*endinstruction)/function(...) add_special("@pi@",...) end
- local comment=(spacing*begincomment*somecomment*endcomment )/function(...) add_special("@cm@",...) end
- local cdata=(spacing*begincdata*somecdata*endcdata )/function(...) add_special("@cd@",...) end
- local doctype=(spacing*begindoctype*somedoctype*enddoctype )/function(...) add_special("@dt@",...) end
- local crap_parsed=anything-beginelement-endelement-emptyelement-begininstruction-begincomment-begincdata-ampersand
- local crap_unparsed=anything-beginelement-endelement-emptyelement-begininstruction-begincomment-begincdata
- local parsedcrap=Cs((crap_parsed^1+entity_text)^1)/handle_crap_error
- local parsedcrap=Cs((crap_parsed^1+entity_text)^1)/handle_crap_error
- local unparsedcrap=Cs((crap_unparsed )^1)/handle_crap_error
- local trailer=space^0*(text_unparsed/set_message)^0
- local grammar_parsed_text_one=P { "preamble",
- preamble=utfbom^0*instruction^0*(doctype+comment+instruction)^0,
- }
- local grammar_parsed_text_two=P { "followup",
- followup=V("parent")*trailer,
- parent=beginelement*V("children")^0*endelement,
- children=parsedtext+V("parent")+emptyelement+comment+cdata+instruction+parsedcrap,
- }
- local grammar_unparsed_text=P { "preamble",
- preamble=utfbom^0*instruction^0*(doctype+comment+instruction)^0*V("parent")*trailer,
- parent=beginelement*V("children")^0*endelement,
- children=unparsedtext+V("parent")+emptyelement+comment+cdata+instruction+unparsedcrap,
- }
- return grammar_parsed_text_one,grammar_parsed_text_two,grammar_unparsed_text
-end
-local
- grammar_parsed_text_one_nop,
- grammar_parsed_text_two_nop,
- grammar_unparsed_text_nop=install(space,spacing,anything)
-local
- grammar_parsed_text_one_yes,
- grammar_parsed_text_two_yes,
- grammar_unparsed_text_yes=install(space_nl,spacing_nl,anything_nl)
-local function _xmlconvert_(data,settings,detail)
- settings=settings or {}
- preparexmlstate(settings)
- if settings.linenumbers then
- grammar_parsed_text_one=grammar_parsed_text_one_yes
- grammar_parsed_text_two=grammar_parsed_text_two_yes
- grammar_unparsed_text=grammar_unparsed_text_yes
- else
- grammar_parsed_text_one=grammar_parsed_text_one_nop
- grammar_parsed_text_two=grammar_parsed_text_two_nop
- grammar_unparsed_text=grammar_unparsed_text_nop
- end
- local preprocessor=settings.preprocessor
- if data and data~="" and type(preprocessor)=="function" then
- data=preprocessor(data,settings) or data
- end
- if settings.parent_root then
- mt=getmetatable(settings.parent_root)
- else
- initialize_mt(top)
- end
- level=level+1
- stack[level]=top
- top.dt={}
- dt=top.dt
- nt=0
- if not data or data=="" then
- errorstr="empty xml file"
- elseif data==true then
- errorstr=detail or "problematic xml file"
- elseif utfize or resolve then
- local m=lpegmatch(grammar_parsed_text_one,data)
- if m then
- m=lpegmatch(grammar_parsed_text_two,data,m)
- end
- if m then
- else
- errorstr="invalid xml file - parsed text"
- end
- elseif type(data)=="string" then
- if lpegmatch(grammar_unparsed_text,data) then
- errorstr=""
- else
- errorstr="invalid xml file - unparsed text"
- end
- else
- errorstr="invalid xml file - no text at all"
- end
- local result
- if errorstr and errorstr~="" then
- result={ dt={ { ns="",tg="error",dt={ errorstr },at={},er=true } } }
- setmetatable(result,mt)
- setmetatable(result.dt[1],mt)
- setmetatable(stack,mt)
- local errorhandler=settings.error_handler
- if errorhandler==false then
- else
- errorhandler=errorhandler or xml.errorhandler
- if errorhandler then
- local currentresource=settings.currentresource
- if currentresource and currentresource~="" then
- xml.errorhandler(formatters["load error in [%s]: %s"](currentresource,errorstr),currentresource)
- else
- xml.errorhandler(formatters["load error: %s"](errorstr))
- end
- end
- end
- else
- result=stack[1]
- end
- if not settings.no_root then
- result={ special=true,ns="",tg='@rt@',dt=result.dt,at={},entities=entities,settings=settings }
- setmetatable(result,mt)
- local rdt=result.dt
- for k=1,#rdt do
- local v=rdt[k]
- if type(v)=="table" and not v.special then
- result.ri=k
- v.__p__=result
- break
- end
- end
- end
- if errorstr and errorstr~="" then
- result.error=true
- else
- errorstr=nil
- end
- result.statistics={
- errormessage=errorstr,
- entities={
- decimals=dcache,
- hexadecimals=hcache,
- names=acache,
- intermediates=parameters,
- }
- }
- preparexmlstate()
- return result
-end
-local function xmlconvert(data,settings)
- local ok,result=pcall(function() return _xmlconvert_(data,settings) end)
- if ok then
- return result
- elseif type(result)=="string" then
- return _xmlconvert_(true,settings,result)
- else
- return _xmlconvert_(true,settings)
- end
-end
-xml.convert=xmlconvert
-function xml.inheritedconvert(data,xmldata,cleanup)
- local settings=xmldata.settings
- if settings then
- settings.parent_root=xmldata
- end
- local xc=xmlconvert(data,settings)
- if cleanup then
- local x=xc.dt
- if x then
- x=x[1]
- if x and x.tg=="@pi@" then
- local dt=x.dt
- local pi=dt and dt[1]
- if type(pi)=="string" and find(pi,"^xml") then
- remove(dt,1)
- end
- end
- end
- end
- return xc
-end
-function xml.is_valid(root)
- return root and root.dt and root.dt[1] and type(root.dt[1])=="table" and not root.dt[1].er
-end
-function xml.package(tag,attributes,data)
- local ns,tg=match(tag,"^(.-):?([^:]+)$")
- local t={ ns=ns,tg=tg,dt=data or "",at=attributes or {} }
- setmetatable(t,mt)
- return t
-end
-function xml.is_valid(root)
- return root and not root.error
-end
-xml.errorhandler=report_xml
-function xml.load(filename,settings)
- local data=""
- if type(filename)=="string" then
- local f=io.open(filename,'r')
- if f then
- data=f:read("*all")
- f:close()
- end
- elseif filename then
- data=filename:read("*all")
- end
- if settings then
- settings.currentresource=filename
- local result=xmlconvert(data,settings)
- settings.currentresource=nil
- return result
- else
- return xmlconvert(data,{ currentresource=filename })
- end
-end
-local no_root={ no_root=true }
-function xml.toxml(data)
- if type(data)=="string" then
- local root={ xmlconvert(data,no_root) }
- return (#root>1 and root) or root[1]
- else
- return data
- end
-end
-local function copy(old,p)
- if old then
- local new={}
- for k,v in next,old do
- local t=type(v)=="table"
- if k=="at" then
- local t={}
- for k,v in next,v do
- t[k]=v
- end
- new[k]=t
- elseif k=="dt" then
- v.__p__=nil
- local t={}
- for i=1,#v do
- local vi=v[i]
- if type(vi)=="table" then
- t[i]=copy(vi,new)
- else
- t[i]=vi
- end
- end
- new[k]=t
- t.__p__=p
- else
- new[k]=v
- end
- end
- local mt=getmetatable(old)
- if mt then
- setmetatable(new,mt)
- end
- return new
- else
- return {}
- end
-end
-xml.copy=copy
-function xml.checkbom(root)
- if root.ri then
- local dt=root.dt
- for k=1,#dt do
- local v=dt[k]
- if type(v)=="table" and v.special and v.tg=="@pi@" and find(v.dt[1],"xml.*version=") then
- return
- end
- end
- insert(dt,1,{ special=true,ns="",tg="@pi@",dt={ "xml version='1.0' standalone='yes'" } } )
- insert(dt,2,"\n" )
- end
-end
-local f_attribute=formatters['%s=%q']
-local function verbose_element(e,handlers,escape)
- local handle=handlers.handle
- local serialize=handlers.serialize
- local ens,etg,eat,edt,ern=e.ns,e.tg,e.at,e.dt,e.rn
- local ats=eat and next(eat) and {}
- if ats then
- local n=0
- for k in next,eat do
- n=n+1
- ats[n]=k
- end
- if n==1 then
- local k=ats[1]
- ats=f_attribute(k,escaped(eat[k]))
- else
- sort(ats)
- for i=1,n do
- local k=ats[i]
- ats[i]=f_attribute(k,escaped(eat[k]))
- end
- ats=concat(ats," ")
- end
- end
- if ern and trace_entities and ern~=ens then
- ens=ern
- end
- local n=edt and #edt
- if ens~="" then
- if n and n>0 then
- if ats then
- handle("<",ens,":",etg," ",ats,">")
- else
- handle("<",ens,":",etg,">")
- end
- for i=1,n do
- local e=edt[i]
- if type(e)=="string" then
- handle(escaped(e))
- else
- serialize(e,handlers)
- end
- end
- handle("</",ens,":",etg,">")
- else
- if ats then
- handle("<",ens,":",etg," ",ats,"/>")
- else
- handle("<",ens,":",etg,"/>")
- end
- end
- else
- if n and n>0 then
- if ats then
- handle("<",etg," ",ats,">")
- else
- handle("<",etg,">")
- end
- for i=1,n do
- local e=edt[i]
- if type(e)=="string" then
- handle(escaped(e))
- else
- serialize(e,handlers)
- end
- end
- handle("</",etg,">")
- else
- if ats then
- handle("<",etg," ",ats,"/>")
- else
- handle("<",etg,"/>")
- end
- end
- end
-end
-local function verbose_pi(e,handlers)
- handlers.handle("<?",e.dt[1],"?>")
-end
-local function verbose_comment(e,handlers)
- handlers.handle("<!--",e.dt[1],"-->")
-end
-local function verbose_cdata(e,handlers)
- handlers.handle("<![CDATA[",e.dt[1],"]]>")
-end
-local function verbose_doctype(e,handlers)
- handlers.handle("<!DOCTYPE",e.dt[1],">")
-end
-local function verbose_root(e,handlers)
- handlers.serialize(e.dt,handlers)
-end
-local function verbose_text(e,handlers)
- handlers.handle(escaped(e))
-end
-local function verbose_document(e,handlers)
- local serialize=handlers.serialize
- local functions=handlers.functions
- for i=1,#e do
- local ei=e[i]
- if type(ei)=="string" then
- functions["@tx@"](ei,handlers)
- else
- serialize(ei,handlers)
- end
- end
-end
-local function serialize(e,handlers,...)
- if e then
- local initialize=handlers.initialize
- local finalize=handlers.finalize
- local functions=handlers.functions
- if initialize then
- local state=initialize(...)
- if not state==true then
- return state
- end
- end
- local etg=e.tg
- if etg then
- (functions[etg] or functions["@el@"])(e,handlers)
- else
- functions["@dc@"](e,handlers)
- end
- if finalize then
- return finalize()
- end
- end
-end
-local function xserialize(e,handlers)
- if e then
- local functions=handlers.functions
- local etg=e.tg
- if etg then
- (functions[etg] or functions["@el@"])(e,handlers)
- else
- functions["@dc@"](e,handlers)
- end
- end
-end
-local handlers={}
-local function newhandlers(settings)
- local t=table.copy(handlers[settings and settings.parent or "verbose"] or {})
- if settings then
- for k,v in next,settings do
- if type(v)=="table" then
- local tk=t[k] if not tk then tk={} t[k]=tk end
- for kk,vv in next,v do
- tk[kk]=vv
- end
- else
- t[k]=v
- end
- end
- if settings.name then
- handlers[settings.name]=t
- end
- end
- utilities.storage.mark(t)
- return t
-end
-local nofunction=function() end
-function xml.sethandlersfunction(handler,name,fnc)
- handler.functions[name]=fnc or nofunction
-end
-function xml.gethandlersfunction(handler,name)
- return handler.functions[name]
-end
-function xml.gethandlers(name)
- return handlers[name]
-end
-newhandlers {
- name="verbose",
- initialize=false,
- finalize=false,
- serialize=xserialize,
- handle=print,
- functions={
- ["@dc@"]=verbose_document,
- ["@dt@"]=verbose_doctype,
- ["@rt@"]=verbose_root,
- ["@el@"]=verbose_element,
- ["@pi@"]=verbose_pi,
- ["@cm@"]=verbose_comment,
- ["@cd@"]=verbose_cdata,
- ["@tx@"]=verbose_text,
- }
-}
-local result
-local xmlfilehandler=newhandlers {
- name="file",
- initialize=function(name)
- result=io.open(name,"wb")
- return result
- end,
- finalize=function()
- result:close()
- return true
- end,
- handle=function(...)
- result:write(...)
- end,
-}
-function xml.save(root,name)
- serialize(root,xmlfilehandler,name)
-end
-local result,r,threshold={},0,512
-local xmlstringhandler=newhandlers {
- name="string",
- initialize=function()
- r=0
- return result
- end,
- finalize=function()
- local done=concat(result,"",1,r)
- r=0
- if r>threshold then
- result={}
- end
- return done
- end,
- handle=function(...)
- for i=1,select("#",...) do
- r=r+1
- result[r]=select(i,...)
- end
- end,
-}
-local function xmltostring(root)
- if not root then
- return ""
- elseif type(root)=="string" then
- return root
- else
- return serialize(root,xmlstringhandler) or ""
- end
-end
-local function __tostring(root)
- return (root and xmltostring(root)) or ""
-end
-initialize_mt=function(root)
- mt={ __tostring=__tostring,__index=root }
-end
-xml.defaulthandlers=handlers
-xml.newhandlers=newhandlers
-xml.serialize=serialize
-xml.tostring=xmltostring
-local function xmlstring(e,handle)
- if not handle or (e.special and e.tg~="@rt@") then
- elseif e.tg then
- local edt=e.dt
- if edt then
- for i=1,#edt do
- xmlstring(edt[i],handle)
- end
- end
- else
- handle(e)
- end
-end
-xml.string=xmlstring
-function xml.settings(e)
- while e do
- local s=e.settings
- if s then
- return s
- else
- e=e.__p__
- end
- end
- return nil
-end
-function xml.root(e)
- local r=e
- while e do
- e=e.__p__
- if e then
- r=e
- end
- end
- return r
-end
-function xml.parent(root)
- return root.__p__
-end
-function xml.body(root)
- return root.ri and root.dt[root.ri] or root
-end
-function xml.name(root)
- if not root then
- return ""
- end
- local ns=root.ns
- local tg=root.tg
- if ns=="" then
- return tg
- else
- return ns..":"..tg
- end
-end
-function xml.erase(dt,k)
- if dt then
- if k then
- dt[k]=""
- else for k=1,#dt do
- dt[1]={ "" }
- end end
- end
-end
-function xml.assign(dt,k,root)
- if dt and k then
- dt[k]=type(root)=="table" and xml.body(root) or root
- return dt[k]
- else
- return xml.body(root)
- end
-end
-function xml.tocdata(e,wrapper)
- local whatever=type(e)=="table" and xmltostring(e.dt) or e or ""
- if wrapper then
- whatever=formatters["<%s>%s</%s>"](wrapper,whatever,wrapper)
- end
- local t={ special=true,ns="",tg="@cd@",at={},rn="",dt={ whatever },__p__=e }
- setmetatable(t,getmetatable(e))
- e.dt={ t }
-end
-function xml.makestandalone(root)
- if root.ri then
- local dt=root.dt
- for k=1,#dt do
- local v=dt[k]
- if type(v)=="table" and v.special and v.tg=="@pi@" then
- local txt=v.dt[1]
- if find(txt,"xml.*version=") then
- v.dt[1]=txt.." standalone='yes'"
- break
- end
- end
- end
- end
- return root
-end
-function xml.kind(e)
- local dt=e and e.dt
- if dt then
- local n=#dt
- if n==1 then
- local d=dt[1]
- if d.special then
- local tg=d.tg
- if tg=="@cd@" then
- return "cdata"
- elseif tg=="@cm" then
- return "comment"
- elseif tg=="@pi@" then
- return "instruction"
- elseif tg=="@dt@" then
- return "declaration"
- end
- elseif type(d)=="string" then
- return "text"
- end
- return "element"
- elseif n>0 then
- return "mixed"
- end
- end
- return "empty"
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-lpt"] = package.loaded["lxml-lpt"] or true
-
--- original size: 54667, stripped down to: 31258
-
-if not modules then modules={} end modules ['lxml-lpt']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local concat,remove,insert=table.concat,table.remove,table.insert
-local type,next,tonumber,tostring,setmetatable,load,select=type,next,tonumber,tostring,setmetatable,load,select
-local format,upper,lower,gmatch,gsub,find,rep=string.format,string.upper,string.lower,string.gmatch,string.gsub,string.find,string.rep
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local setmetatableindex=table.setmetatableindex
-local formatters=string.formatters
-local trace_lpath=false
-local trace_lparse=false
-local trace_lprofile=false
-local report_lpath=logs.reporter("xml","lpath")
-if trackers then
- trackers.register("xml.path",function(v)
- trace_lpath=v
- end)
- trackers.register("xml.parse",function(v)
- trace_lparse=v
- end)
- trackers.register("xml.profile",function(v)
- trace_lpath=v
- trace_lparse=v
- trace_lprofile=v
- end)
-end
-local xml=xml
-local lpathcalls=0 function xml.lpathcalls () return lpathcalls end
-local lpathcached=0 function xml.lpathcached() return lpathcached end
-xml.functions=xml.functions or {}
-local functions=xml.functions
-xml.expressions=xml.expressions or {}
-local expressions=xml.expressions
-xml.finalizers=xml.finalizers or {}
-local finalizers=xml.finalizers
-xml.specialhandler=xml.specialhandler or {}
-local specialhandler=xml.specialhandler
-lpegpatterns.xml=lpegpatterns.xml or {}
-local xmlpatterns=lpegpatterns.xml
-finalizers.xml=finalizers.xml or {}
-finalizers.tex=finalizers.tex or {}
-local function fallback (t,name)
- local fn=finalizers[name]
- if fn then
- t[name]=fn
- else
- report_lpath("unknown sub finalizer %a",name)
- fn=function() end
- end
- return fn
-end
-setmetatableindex(finalizers.xml,fallback)
-setmetatableindex(finalizers.tex,fallback)
-xml.defaultprotocol="xml"
-local apply_axis={}
-apply_axis['root']=function(list)
- local collected={}
- for l=1,#list do
- local ll=list[l]
- local rt=ll
- while ll do
- ll=ll.__p__
- if ll then
- rt=ll
- end
- end
- collected[l]=rt
- end
- return collected
-end
-apply_axis['self']=function(list)
- return list
-end
-apply_axis['child']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local dt=ll.dt
- if dt then
- local n=#dt
- if n==0 then
- ll.en=0
- elseif n==1 then
- local dk=dt[1]
- if dk.tg then
- c=c+1
- collected[c]=dk
- dk.ni=1
- dk.ei=1
- ll.en=1
- end
- else
- local en=0
- for k=1,#dt do
- local dk=dt[k]
- if dk.tg then
- c=c+1
- en=en+1
- collected[c]=dk
- dk.ni=k
- dk.ei=en
- end
- end
- ll.en=en
- end
- end
- end
- return collected
-end
-local function collect(list,collected,c)
- local dt=list.dt
- if dt then
- local n=#dt
- if n==0 then
- list.en=0
- elseif n==1 then
- local dk=dt[1]
- if dk.tg then
- c=c+1
- collected[c]=dk
- dk.ni=1
- dk.ei=1
- c=collect(dk,collected,c)
- list.en=1
- else
- list.en=0
- end
- else
- local en=0
- for k=1,n do
- local dk=dt[k]
- if dk.tg then
- c=c+1
- en=en+1
- collected[c]=dk
- dk.ni=k
- dk.ei=en
- c=collect(dk,collected,c)
- end
- end
- list.en=en
- end
- end
- return c
-end
-apply_axis['descendant']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- c=collect(list[l],collected,c)
- end
- return collected
-end
-local function collect(list,collected,c)
- local dt=list.dt
- if dt then
- local n=#dt
- if n==0 then
- list.en=0
- elseif n==1 then
- local dk=dt[1]
- if dk.tg then
- c=c+1
- collected[c]=dk
- dk.ni=1
- dk.ei=1
- c=collect(dk,collected,c)
- list.en=1
- end
- else
- local en=0
- for k=1,#dt do
- local dk=dt[k]
- if dk.tg then
- c=c+1
- en=en+1
- collected[c]=dk
- dk.ni=k
- dk.ei=en
- c=collect(dk,collected,c)
- end
- end
- list.en=en
- end
- end
- return c
-end
-apply_axis['descendant-or-self']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- if ll.special~=true then
- c=c+1
- collected[c]=ll
- end
- c=collect(ll,collected,c)
- end
- return collected
-end
-apply_axis['ancestor']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- while ll do
- ll=ll.__p__
- if ll then
- c=c+1
- collected[c]=ll
- end
- end
- end
- return collected
-end
-apply_axis['ancestor-or-self']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- c=c+1
- collected[c]=ll
- while ll do
- ll=ll.__p__
- if ll then
- c=c+1
- collected[c]=ll
- end
- end
- end
- return collected
-end
-apply_axis['parent']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local pl=list[l].__p__
- if pl then
- c=c+1
- collected[c]=pl
- end
- end
- return collected
-end
-apply_axis['attribute']=function(list)
- return {}
-end
-apply_axis['namespace']=function(list)
- return {}
-end
-apply_axis['following']=function(list)
- return {}
-end
-apply_axis['preceding']=function(list)
- return {}
-end
-apply_axis['following-sibling']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local p=ll.__p__
- local d=p.dt
- for i=ll.ni+1,#d do
- local di=d[i]
- if type(di)=="table" then
- c=c+1
- collected[c]=di
- end
- end
- end
- return collected
-end
-apply_axis['preceding-sibling']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local p=ll.__p__
- local d=p.dt
- for i=1,ll.ni-1 do
- local di=d[i]
- if type(di)=="table" then
- c=c+1
- collected[c]=di
- end
- end
- end
- return collected
-end
-apply_axis['reverse-sibling']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local p=ll.__p__
- local d=p.dt
- for i=ll.ni-1,1,-1 do
- local di=d[i]
- if type(di)=="table" then
- c=c+1
- collected[c]=di
- end
- end
- end
- return collected
-end
-apply_axis['auto-descendant-or-self']=apply_axis['descendant-or-self']
-apply_axis['auto-descendant']=apply_axis['descendant']
-apply_axis['auto-child']=apply_axis['child']
-apply_axis['auto-self']=apply_axis['self']
-apply_axis['initial-child']=apply_axis['child']
-local function apply_nodes(list,directive,nodes)
- local maxn=#nodes
- if maxn==3 then
- local nns=nodes[2]
- local ntg=nodes[3]
- if not nns and not ntg then
- if directive then
- return list
- else
- return {}
- end
- else
- local collected={}
- local c=0
- local m=0
- local p=nil
- if not nns then
- for l=1,#list do
- local ll=list[l]
- local ltg=ll.tg
- if ltg then
- if directive then
- if ntg==ltg then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif ntg~=ltg then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- elseif not ntg then
- for l=1,#list do
- local ll=list[l]
- local lns=ll.rn or ll.ns
- if lns then
- if directive then
- if lns==nns then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif lns~=nns then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- else
- for l=1,#list do
- local ll=list[l]
- local ltg=ll.tg
- if ltg then
- local lns=ll.rn or ll.ns
- local ok=ltg==ntg and lns==nns
- if directive then
- if ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif not ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- end
- return collected
- end
- else
- local collected={}
- local c=0
- local m=0
- local p=nil
- for l=1,#list do
- local ll=list[l]
- local ltg=ll.tg
- if ltg then
- local lns=ll.rn or ll.ns
- local ok=false
- for n=1,maxn,3 do
- local nns=nodes[n+1]
- local ntg=nodes[n+2]
- ok=(not ntg or ltg==ntg) and (not nns or lns==nns)
- if ok then
- break
- end
- end
- if directive then
- if ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif not ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- return collected
- end
-end
-local quit_expression=false
-local function apply_expression(list,expression,order)
- local collected={}
- local c=0
- quit_expression=false
- for l=1,#list do
- local ll=list[l]
- if expression(list,ll,l,order) then
- c=c+1
- collected[c]=ll
- end
- if quit_expression then
- break
- end
- end
- return collected
-end
-local function apply_selector(list,specification)
- if xml.applyselector then
- apply_selector=xml.applyselector
- return apply_selector(list,specification)
- else
- return list
- end
-end
-local P,V,C,Cs,Cc,Ct,R,S,Cg,Cb=lpeg.P,lpeg.V,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Ct,lpeg.R,lpeg.S,lpeg.Cg,lpeg.Cb
-local spaces=S(" \n\r\t\f")^0
-local lp_space=S(" \n\r\t\f")
-local lp_any=P(1)
-local lp_noequal=P("!=")/"~="+P("<=")+P(">=")+P("==")
-local lp_doequal=P("=")/"=="
-local lp_or=P("|")/" or "
-local lp_and=P("&")/" and "
-local builtin={
- text="(ll.dt[1] or '')",
- content="ll.dt",
- name="((ll.ns~='' and ll.ns..':'..ll.tg) or ll.tg)",
- tag="ll.tg",
- position="l",
- firstindex="1",
- firstelement="1",
- first="1",
- lastindex="(#ll.__p__.dt or 1)",
- lastelement="(ll.__p__.en or 1)",
- last="#list",
- list="list",
- self="ll",
- rootposition="order",
- order="order",
- element="(ll.ei or 1)",
- index="(ll.ni or 1)",
- match="(ll.mi or 1)",
- namespace="ll.ns",
- ns="ll.ns",
-}
-local lp_builtin=lpeg.utfchartabletopattern(builtin)/builtin*((spaces*P("(")*spaces*P(")"))/"")
-local lp_attribute=(P("@")+P("attribute::"))/""*Cc("(ll.at and ll.at['")*((R("az","AZ")+S("-_:"))^1)*Cc("'])")
-local lp_fastpos_p=P("+")^0*R("09")^1*P(-1)/"l==%0"
-local lp_fastpos_n=P("-")*R("09")^1*P(-1)/"(%0<0 and (#list+%0+1==l))"
-local lp_fastpos=lp_fastpos_n+lp_fastpos_p
-local lp_reserved=C("and")+C("or")+C("not")+C("div")+C("mod")+C("true")+C("false")
-local lp_lua_function=Cs((R("az","AZ","__")^1*(P(".")*R("az","AZ","__")^1)^1)*("("))/"%0"
-local lp_function=C(R("az","AZ","__")^1)*P("(")/function(t)
- if expressions[t] then
- return "expr."..t.."("
- else
- return "expr.error("
- end
-end
-local lparent=P("(")
-local rparent=P(")")
-local noparent=1-(lparent+rparent)
-local nested=P{lparent*(noparent+V(1))^0*rparent}
-local value=P(lparent*C((noparent+nested)^0)*rparent)
-local lp_child=Cc("expr.child(ll,'")*R("az","AZ")*R("az","AZ","--","__")^0*Cc("')")
-local lp_number=S("+-")*R("09")^1
-local lp_string=Cc("'")*R("az","AZ","--","__")^1*Cc("'")
-local lp_content=(P("'")*(1-P("'"))^0*P("'")+P('"')*(1-P('"'))^0*P('"'))
-local cleaner
-local lp_special=(C(P("name")+P("text")+P("tag")+P("count")+P("child")))*value/function(t,s)
- if expressions[t] then
- s=s and s~="" and lpegmatch(cleaner,s)
- if s and s~="" then
- return "expr."..t.."(ll,"..s..")"
- else
- return "expr."..t.."(ll)"
- end
- else
- return "expr.error("..t..")"
- end
-end
-local content=lp_builtin+lp_attribute+lp_special+lp_noequal+lp_doequal+lp_or+lp_and+lp_reserved+lp_lua_function+lp_function+lp_content+
- lp_child+lp_any
-local converter=Cs (
- lp_fastpos+(P { lparent*(V(1))^0*rparent+content } )^0
-)
-cleaner=Cs ((
- lp_reserved+lp_number+lp_string+1 )^1 )
-local template_e=[[
- local expr = xml.expressions
- return function(list,ll,l,order)
- return %s
- end
-]]
-local template_f_y=[[
- local finalizer = xml.finalizers['%s']['%s']
- return function(collection)
- return finalizer(collection,%s)
- end
-]]
-local template_f_n=[[
- return xml.finalizers['%s']['%s']
-]]
-local register_last_match={ kind="axis",axis="last-match" }
-local register_self={ kind="axis",axis="self" }
-local register_parent={ kind="axis",axis="parent" }
-local register_descendant={ kind="axis",axis="descendant" }
-local register_child={ kind="axis",axis="child" }
-local register_descendant_or_self={ kind="axis",axis="descendant-or-self" }
-local register_root={ kind="axis",axis="root" }
-local register_ancestor={ kind="axis",axis="ancestor" }
-local register_ancestor_or_self={ kind="axis",axis="ancestor-or-self" }
-local register_attribute={ kind="axis",axis="attribute" }
-local register_namespace={ kind="axis",axis="namespace" }
-local register_following={ kind="axis",axis="following" }
-local register_following_sibling={ kind="axis",axis="following-sibling" }
-local register_preceding={ kind="axis",axis="preceding" }
-local register_preceding_sibling={ kind="axis",axis="preceding-sibling" }
-local register_reverse_sibling={ kind="axis",axis="reverse-sibling" }
-local register_auto_descendant_or_self={ kind="axis",axis="auto-descendant-or-self" }
-local register_auto_descendant={ kind="axis",axis="auto-descendant" }
-local register_auto_self={ kind="axis",axis="auto-self" }
-local register_auto_child={ kind="axis",axis="auto-child" }
-local register_initial_child={ kind="axis",axis="initial-child" }
-local register_all_nodes={ kind="nodes",nodetest=true,nodes={ true,false,false } }
-local skip={}
-local function errorrunner_e(str,cnv)
- if not skip[str] then
- report_lpath("error in expression: %s => %s",str,cnv)
- skip[str]=cnv or str
- end
- return false
-end
-local function errorrunner_f(str,arg)
- report_lpath("error in finalizer: %s(%s)",str,arg or "")
- return false
-end
-local function register_nodes(nodetest,nodes)
- return { kind="nodes",nodetest=nodetest,nodes=nodes }
-end
-local function register_selector(specification)
- return { kind="selector",specification=specification }
-end
-local function register_expression(expression)
- local converted=lpegmatch(converter,expression)
- local wrapped=format(template_e,converted)
- local runner=load(wrapped)
- runner=(runner and runner()) or function() errorrunner_e(expression,converted) end
- return { kind="expression",expression=expression,converted=converted,evaluator=runner }
-end
-local function register_finalizer(protocol,name,arguments)
- local runner
- if arguments and arguments~="" then
- runner=load(format(template_f_y,protocol or xml.defaultprotocol,name,arguments))
- else
- runner=load(format(template_f_n,protocol or xml.defaultprotocol,name))
- end
- runner=(runner and runner()) or function() errorrunner_f(name,arguments) end
- return { kind="finalizer",name=name,arguments=arguments,finalizer=runner }
-end
-local expression=P { "ex",
- ex="["*C((V("sq")+V("dq")+(1-S("[]"))+V("ex"))^0)*"]",
- sq="'"*(1-S("'"))^0*"'",
- dq='"'*(1-S('"'))^0*'"',
-}
-local arguments=P { "ar",
- ar="("*Cs((V("sq")+V("dq")+V("nq")+P(1-P(")")))^0)*")",
- nq=((1-S("),'\""))^1)/function(s) return format("%q",s) end,
- sq=P("'")*(1-P("'"))^0*P("'"),
- dq=P('"')*(1-P('"'))^0*P('"'),
-}
-local function register_error(str)
- return { kind="error",error=format("unparsed: %s",str) }
-end
-local special_1=P("*")*Cc(register_auto_descendant)*Cc(register_all_nodes)
-local special_2=P("/")*Cc(register_auto_self)
-local special_3=P("")*Cc(register_auto_self)
-local no_nextcolon=P(-1)+#(1-P(":"))
-local no_nextlparent=P(-1)+#(1-P("("))
-local pathparser=Ct { "patterns",
- patterns=spaces*V("protocol")*spaces*(
- (V("special")*spaces*P(-1) )+(V("initial")*spaces*V("step")*spaces*(P("/")*spaces*V("step")*spaces)^0 )
- ),
- protocol=Cg(V("letters"),"protocol")*P("://")+Cg(Cc(nil),"protocol"),
- step=((V("shortcuts")+V("selector")+P("/")+V("axis"))*spaces*V("nodes")^0+V("error"))*spaces*V("expressions")^0*spaces*V("finalizer")^0,
- axis=V("last_match")+V("descendant")+V("child")+V("parent")+V("self")+V("root")+V("ancestor")+V("descendant_or_self")+V("following_sibling")+V("following")+V("reverse_sibling")+V("preceding_sibling")+V("preceding")+V("ancestor_or_self")+#(1-P(-1))*Cc(register_auto_child),
- special=special_1+special_2+special_3,
- initial=(P("/")*spaces*Cc(register_initial_child))^-1,
- error=(P(1)^1)/register_error,
- shortcuts_a=V("s_descendant_or_self")+V("s_descendant")+V("s_child")+V("s_parent")+V("s_self")+V("s_root")+V("s_ancestor")+V("s_lastmatch"),
- shortcuts=V("shortcuts_a")*(spaces*"/"*spaces*V("shortcuts_a"))^0,
- s_descendant_or_self=(P("***/")+P("/"))*Cc(register_descendant_or_self),
- s_descendant=P("**")*Cc(register_descendant),
- s_child=P("*")*no_nextcolon*Cc(register_child),
- s_parent=P("..")*Cc(register_parent),
- s_self=P("." )*Cc(register_self),
- s_root=P("^^")*Cc(register_root),
- s_ancestor=P("^")*Cc(register_ancestor),
- s_lastmatch=P("=")*Cc(register_last_match),
- descendant=P("descendant::")*Cc(register_descendant),
- child=P("child::")*Cc(register_child),
- parent=P("parent::")*Cc(register_parent),
- self=P("self::")*Cc(register_self),
- root=P('root::')*Cc(register_root),
- ancestor=P('ancestor::')*Cc(register_ancestor),
- descendant_or_self=P('descendant-or-self::')*Cc(register_descendant_or_self),
- ancestor_or_self=P('ancestor-or-self::')*Cc(register_ancestor_or_self),
- following=P('following::')*Cc(register_following),
- following_sibling=P('following-sibling::')*Cc(register_following_sibling),
- preceding=P('preceding::')*Cc(register_preceding),
- preceding_sibling=P('preceding-sibling::')*Cc(register_preceding_sibling),
- reverse_sibling=P('reverse-sibling::')*Cc(register_reverse_sibling),
- last_match=P('last-match::')*Cc(register_last_match),
- selector=P("{")*C((1-P("}"))^1)*P("}")/register_selector,
- nodes=(V("nodefunction")*spaces*P("(")*V("nodeset")*P(")")+V("nodetest")*V("nodeset"))/register_nodes,
- expressions=expression/register_expression,
- letters=R("az")^1,
- name=(1-S("/[]()|:*!"))^1,
- negate=P("!")*Cc(false),
- nodefunction=V("negate")+P("not")*Cc(false)+Cc(true),
- nodetest=V("negate")+Cc(true),
- nodename=(V("negate")+Cc(true))*spaces*((V("wildnodename")*P(":")*V("wildnodename"))+(Cc(false)*V("wildnodename"))),
- wildnodename=(C(V("name"))+P("*")*Cc(false))*no_nextlparent,
- nodeset=spaces*Ct(V("nodename")*(spaces*P("|")*spaces*V("nodename"))^0)*spaces,
- finalizer=(Cb("protocol")*P("/")^-1*C(V("name"))*arguments*P(-1))/register_finalizer,
-}
-xmlpatterns.pathparser=pathparser
-local cache={}
-local function nodesettostring(set,nodetest)
- local t={}
- for i=1,#set,3 do
- local directive,ns,tg=set[i],set[i+1],set[i+2]
- if not ns or ns=="" then ns="*" end
- if not tg or tg=="" then tg="*" end
- tg=(tg=="@rt@" and "[root]") or format("%s:%s",ns,tg)
- t[#t+1]=(directive and tg) or format("not(%s)",tg)
- end
- if nodetest==false then
- return format("not(%s)",concat(t,"|"))
- else
- return concat(t,"|")
- end
-end
-local function tagstostring(list)
- if #list==0 then
- return "no elements"
- else
- local t={}
- for i=1,#list do
- local li=list[i]
- local ns=li.ns
- local tg=li.tg
- if not ns or ns=="" then ns="*" end
- if not tg or tg=="" then tg="*" end
- t[i]=(tg=="@rt@" and "[root]") or format("%s:%s",ns,tg)
- end
- return concat(t," ")
- end
-end
-xml.nodesettostring=nodesettostring
-local lpath
-local function lshow(parsed)
- if type(parsed)=="string" then
- parsed=lpath(parsed)
- end
- report_lpath("%s://%s => %s",parsed.protocol or xml.defaultprotocol,parsed.pattern,
- table.serialize(parsed,false))
-end
-xml.lshow=lshow
-local function add_comment(p,str)
- local pc=p.comment
- if not pc then
- p.comment={ str }
- else
- pc[#pc+1]=str
- end
-end
-lpath=function (pattern)
- lpathcalls=lpathcalls+1
- if type(pattern)=="table" then
- return pattern
- else
- local parsed=cache[pattern]
- if parsed then
- lpathcached=lpathcached+1
- else
- parsed=lpegmatch(pathparser,pattern)
- if parsed then
- parsed.pattern=pattern
- local np=#parsed
- if np==0 then
- parsed={ pattern=pattern,register_self,state="parsing error" }
- report_lpath("parsing error in pattern: %s",pattern)
- lshow(parsed)
- else
- local pi=parsed[1]
- if pi.axis=="auto-child" then
- if false then
- add_comment(parsed,"auto-child replaced by auto-descendant-or-self")
- parsed[1]=register_auto_descendant_or_self
- else
- add_comment(parsed,"auto-child replaced by auto-descendant")
- parsed[1]=register_auto_descendant
- end
- elseif pi.axis=="initial-child" and np>1 and parsed[2].axis then
- add_comment(parsed,"initial-child removed")
- remove(parsed,1)
- end
- local np=#parsed
- if np>1 then
- local pnp=parsed[np]
- if pnp.kind=="nodes" and pnp.nodetest==true then
- local nodes=pnp.nodes
- if nodes[1]==true and nodes[2]==false and nodes[3]==false then
- add_comment(parsed,"redundant final wildcard filter removed")
- remove(parsed,np)
- end
- end
- end
- end
- else
- parsed={ pattern=pattern }
- end
- cache[pattern]=parsed
- if trace_lparse and not trace_lprofile then
- lshow(parsed)
- end
- end
- return parsed
- end
-end
-xml.lpath=lpath
-do
- local profiled={}
- xml.profiled=profiled
- local lastmatch=nil
- local keepmatch=nil
- if directives then
- directives.register("xml.path.keeplastmatch",function(v)
- keepmatch=v
- lastmatch=nil
- end)
- end
- apply_axis["last-match"]=function()
- return lastmatch or {}
- end
- local function profiled_apply(list,parsed,nofparsed,order)
- local p=profiled[parsed.pattern]
- if p then
- p.tested=p.tested+1
- else
- p={ tested=1,matched=0,finalized=0 }
- profiled[parsed.pattern]=p
- end
- local collected=list
- for i=1,nofparsed do
- local pi=parsed[i]
- local kind=pi.kind
- if kind=="axis" then
- collected=apply_axis[pi.axis](collected)
- elseif kind=="nodes" then
- collected=apply_nodes(collected,pi.nodetest,pi.nodes)
- elseif kind=="expression" then
- collected=apply_expression(collected,pi.evaluator,order)
- elseif kind=="selector" then
- collected=apply_selector(collected,pi.specification)
- elseif kind=="finalizer" then
- collected=pi.finalizer(collected)
- p.matched=p.matched+1
- p.finalized=p.finalized+1
- return collected
- end
- if not collected or #collected==0 then
- local pn=i<nofparsed and parsed[nofparsed]
- if pn and pn.kind=="finalizer" then
- collected=pn.finalizer(collected)
- p.finalized=p.finalized+1
- return collected
- end
- return nil
- end
- end
- if collected then
- p.matched=p.matched+1
- end
- return collected
- end
- local function traced_apply(list,parsed,nofparsed,order)
- if trace_lparse then
- lshow(parsed)
- end
- report_lpath("collecting: %s",parsed.pattern)
- report_lpath("root tags : %s",tagstostring(list))
- report_lpath("order : %s",order or "unset")
- local collected=list
- for i=1,nofparsed do
- local pi=parsed[i]
- local kind=pi.kind
- if kind=="axis" then
- collected=apply_axis[pi.axis](collected)
- report_lpath("% 10i : ax : %s",(collected and #collected) or 0,pi.axis)
- elseif kind=="nodes" then
- collected=apply_nodes(collected,pi.nodetest,pi.nodes)
- report_lpath("% 10i : ns : %s",(collected and #collected) or 0,nodesettostring(pi.nodes,pi.nodetest))
- elseif kind=="expression" then
- collected=apply_expression(collected,pi.evaluator,order)
- report_lpath("% 10i : ex : %s -> %s",(collected and #collected) or 0,pi.expression,pi.converted)
- elseif kind=="selector" then
- collected=apply_selector(collected,pi.specification)
- report_lpath("% 10i : se : %s ",(collected and #collected) or 0,pi.specification)
- elseif kind=="finalizer" then
- collected=pi.finalizer(collected)
- report_lpath("% 10i : fi : %s : %s(%s)",(type(collected)=="table" and #collected) or 0,parsed.protocol or xml.defaultprotocol,pi.name,pi.arguments or "")
- return collected
- end
- if not collected or #collected==0 then
- local pn=i<nofparsed and parsed[nofparsed]
- if pn and pn.kind=="finalizer" then
- collected=pn.finalizer(collected)
- report_lpath("% 10i : fi : %s : %s(%s)",(type(collected)=="table" and #collected) or 0,parsed.protocol or xml.defaultprotocol,pn.name,pn.arguments or "")
- return collected
- end
- return nil
- end
- end
- return collected
- end
- local function normal_apply(list,parsed,nofparsed,order)
- local collected=list
- for i=1,nofparsed do
- local pi=parsed[i]
- local kind=pi.kind
- if kind=="axis" then
- local axis=pi.axis
- if axis~="self" then
- collected=apply_axis[axis](collected)
- end
- elseif kind=="nodes" then
- collected=apply_nodes(collected,pi.nodetest,pi.nodes)
- elseif kind=="expression" then
- collected=apply_expression(collected,pi.evaluator,order)
- elseif kind=="selector" then
- collected=apply_selector(collected,pi.specification)
- elseif kind=="finalizer" then
- return pi.finalizer(collected)
- end
- if not collected or #collected==0 then
- local pf=i<nofparsed and parsed[nofparsed].finalizer
- if pf then
- return pf(collected)
- end
- return nil
- end
- end
- return collected
- end
- local apply=normal_apply
- if trackers then
- trackers.register("xml.path,xml.parse,xml.profile",function()
- if trace_lprofile then
- apply=profiled_apply
- elseif trace_lpath then
- apply=traced_apply
- else
- apply=normal_apply
- end
- end)
- end
- function xml.applylpath(list,pattern)
- if not list then
- lastmatch=nil
- return
- end
- local parsed=cache[pattern]
- if parsed then
- lpathcalls=lpathcalls+1
- lpathcached=lpathcached+1
- elseif type(pattern)=="table" then
- lpathcalls=lpathcalls+1
- parsed=pattern
- else
- parsed=lpath(pattern) or pattern
- end
- if not parsed then
- lastmatch=nil
- return
- end
- local nofparsed=#parsed
- if nofparsed==0 then
- lastmatch=nil
- return
- end
- local collected=apply({ list },parsed,nofparsed,list.mi)
- lastmatch=keepmatch and collected or nil
- return collected
- end
- function xml.lastmatch()
- return lastmatch
- end
- local stack={}
- function xml.pushmatch()
- insert(stack,lastmatch)
- end
- function xml.popmatch()
- lastmatch=remove(stack)
- end
-end
-local applylpath=xml.applylpath
-function xml.filter(root,pattern)
- return applylpath(root,pattern)
-end
-expressions.child=function(e,pattern)
- return applylpath(e,pattern)
-end
-expressions.count=function(e,pattern)
- local collected=applylpath(e,pattern)
- return pattern and (collected and #collected) or 0
-end
-expressions.attribute=function(e,name,value)
- if type(e)=="table" and name then
- local a=e.at
- if a then
- local v=a[name]
- if value then
- return v==value
- else
- return v
- end
- end
- end
- return nil
-end
-expressions.oneof=function(s,...)
- for i=1,select("#",...) do
- if s==select(i,...) then
- return true
- end
- end
- return false
-end
-expressions.error=function(str)
- xml.errorhandler(format("unknown function in lpath expression: %s",tostring(str or "?")))
- return false
-end
-expressions.undefined=function(s)
- return s==nil
-end
-expressions.quit=function(s)
- if s or s==nil then
- quit_expression=true
- end
- return true
-end
-expressions.print=function(...)
- print(...)
- return true
-end
-expressions.find=find
-expressions.upper=upper
-expressions.lower=lower
-expressions.number=tonumber
-expressions.boolean=toboolean
-function expressions.contains(str,pattern)
- local t=type(str)
- if t=="string" then
- if find(str,pattern) then
- return true
- end
- elseif t=="table" then
- for i=1,#str do
- local d=str[i]
- if type(d)=="string" and find(d,pattern) then
- return true
- end
- end
- end
- return false
-end
-function expressions.idstring(str)
- return type(str)=="string" and gsub(str,"^#","") or ""
-end
-local function traverse(root,pattern,handle)
- local collected=applylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local r=e.__p__
- handle(r,r.dt,e.ni)
- end
- end
-end
-local function selection(root,pattern,handle)
- local collected=applylpath(root,pattern)
- if collected then
- if handle then
- for c=1,#collected do
- handle(collected[c])
- end
- else
- return collected
- end
- end
-end
-xml.traverse=traverse
-xml.selection=selection
-local function dofunction(collected,fnc,...)
- if collected then
- local f=functions[fnc]
- if f then
- for c=1,#collected do
- f(collected[c],...)
- end
- else
- report_lpath("unknown function %a",fnc)
- end
- end
-end
-finalizers.xml["function"]=dofunction
-finalizers.tex["function"]=dofunction
-expressions.text=function(e,n)
- local rdt=e.__p__.dt
- return rdt and rdt[n] or ""
-end
-expressions.name=function(e,n)
- local found=false
- n=tonumber(n) or 0
- if n==0 then
- found=type(e)=="table" and e
- elseif n<0 then
- local d=e.__p__.dt
- local k=e.ni
- for i=k-1,1,-1 do
- local di=d[i]
- if type(di)=="table" then
- if n==-1 then
- found=di
- break
- else
- n=n+1
- end
- end
- end
- else
- local d=e.__p__.dt
- local k=e.ni
- for i=k+1,#d,1 do
- local di=d[i]
- if type(di)=="table" then
- if n==1 then
- found=di
- break
- else
- n=n-1
- end
- end
- end
- end
- if found then
- local ns=found.rn or found.ns or ""
- local tg=found.tg
- if ns~="" then
- return ns..":"..tg
- else
- return tg
- end
- else
- return ""
- end
-end
-expressions.tag=function(e,n)
- if not e then
- return ""
- else
- local found=false
- n=tonumber(n) or 0
- if n==0 then
- found=(type(e)=="table") and e
- elseif n<0 then
- local d=e.__p__.dt
- local k=e.ni
- for i=k-1,1,-1 do
- local di=d[i]
- if type(di)=="table" then
- if n==-1 then
- found=di
- break
- else
- n=n+1
- end
- end
- end
- else
- local d=e.__p__.dt
- local k=e.ni
- for i=k+1,#d,1 do
- local di=d[i]
- if type(di)=="table" then
- if n==1 then
- found=di
- break
- else
- n=n-1
- end
- end
- end
- end
- return (found and found.tg) or ""
- end
-end
-local dummy=function() end
-function xml.elements(root,pattern,reverse)
- local collected=applylpath(root,pattern)
- if not collected then
- return dummy
- end
- local n=#collected
- if n==0 then
- return dummy
- end
- if reverse then
- local c=n+1
- return function()
- if c>1 then
- c=c-1
- local e=collected[c]
- local r=e.__p__
- return r,r.dt,e.ni
- end
- end
- else
- local c=0
- return function()
- if c<n then
- c=c+1
- local e=collected[c]
- local r=e.__p__
- return r,r.dt,e.ni
- end
- end
- end
-end
-function xml.collected(root,pattern,reverse)
- local collected=applylpath(root,pattern)
- if not collected then
- return dummy
- end
- local n=#collected
- if n==0 then
- return dummy
- end
- if reverse then
- local c=n+1
- return function()
- if c>1 then
- c=c-1
- return collected[c]
- end
- end
- else
- local c=0
- return function()
- if c<n then
- c=c+1
- return collected[c]
- end
- end
- end
-end
-function xml.inspect(collection,pattern)
- pattern=pattern or "."
- for e in xml.collected(collection,pattern or ".") do
- report_lpath("pattern: %s\n\n%s\n",pattern,xml.tostring(e))
- end
-end
-local function split(e)
- local dt=e.dt
- if dt then
- for i=1,#dt do
- local dti=dt[i]
- if type(dti)=="string" then
- dti=gsub(dti,"^[\n\r]*(.-)[\n\r]*","%1")
- dti=gsub(dti,"[\n\r]+","\n\n")
- dt[i]=dti
- else
- split(dti)
- end
- end
- end
- return e
-end
-function xml.finalizers.paragraphs(c)
- for i=1,#c do
- split(c[i])
- end
- return c
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-mis"] = package.loaded["lxml-mis"] or true
-
--- original size: 3574, stripped down to: 1808
-
-if not modules then modules={} end modules ['lxml-mis']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local xml,lpeg,string=xml,lpeg,string
-local type=type
-local concat=table.concat
-local format,gsub,match=string.format,string.gsub,string.match
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local P,S,R,C,V,Cc,Cs=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.V,lpeg.Cc,lpeg.Cs
-lpegpatterns.xml=lpegpatterns.xml or {}
-local xmlpatterns=lpegpatterns.xml
-local function xmlgsub(t,old,new)
- local dt=t.dt
- if dt then
- for k=1,#dt do
- local v=dt[k]
- if type(v)=="string" then
- dt[k]=gsub(v,old,new)
- else
- xmlgsub(v,old,new)
- end
- end
- end
-end
-function xml.stripleadingspaces(dk,d,k)
- if d and k then
- local dkm=d[k-1]
- if dkm and type(dkm)=="string" then
- local s=match(dkm,"\n(%s+)")
- xmlgsub(dk,"\n"..rep(" ",#s),"\n")
- end
- end
-end
-local normal=(1-S("<&>"))^0
-local special=P("<")/"&lt;"+P(">")/"&gt;"+P("&")/"&amp;"
-local escaped=Cs(normal*(special*normal)^0)
-local normal=(1-S"&")^0
-local special=P("&lt;")/"<"+P("&gt;")/">"+P("&amp;")/"&"
-local unescaped=Cs(normal*(special*normal)^0)
-local cleansed=Cs(((P("<")*(1-P(">"))^0*P(">"))/""+1)^0)
-xmlpatterns.escaped=escaped
-xmlpatterns.unescaped=unescaped
-xmlpatterns.cleansed=cleansed
-function xml.escaped (str) return lpegmatch(escaped,str) end
-function xml.unescaped(str) return lpegmatch(unescaped,str) end
-function xml.cleansed (str) return lpegmatch(cleansed,str) end
-function xml.fillin(root,pattern,str,check)
- local e=xml.first(root,pattern)
- if e then
- local n=#e.dt
- if not check or n==0 or (n==1 and e.dt[1]=="") then
- e.dt={ str }
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-aux"] = package.loaded["lxml-aux"] or true
-
--- original size: 33708, stripped down to: 20953
-
-if not modules then modules={} end modules ['lxml-aux']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local trace_manipulations=false trackers.register("lxml.manipulations",function(v) trace_manipulations=v end)
-local trace_inclusions=false trackers.register("lxml.inclusions",function(v) trace_inclusions=v end)
-local report_xml=logs.reporter("xml")
-local xml=xml
-local xmlcopy,xmlname=xml.copy,xml.name
-local xmlinheritedconvert=xml.inheritedconvert
-local xmlapplylpath=xml.applylpath
-local type,next,setmetatable,getmetatable=type,next,setmetatable,getmetatable
-local insert,remove,fastcopy,concat=table.insert,table.remove,table.fastcopy,table.concat
-local gmatch,gsub,format,find,strip,match=string.gmatch,string.gsub,string.format,string.find,string.strip,string.match
-local utfbyte=utf.byte
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local striplinepatterns=utilities.strings.striplinepatterns
-local function report(what,pattern,c,e)
- report_xml("%s element %a, root %a, position %a, index %a, pattern %a",what,xmlname(e),xmlname(e.__p__),c,e.ni,pattern)
-end
-local function withelements(e,handle,depth)
- if e and handle then
- local edt=e.dt
- if edt then
- depth=depth or 0
- for i=1,#edt do
- local e=edt[i]
- if type(e)=="table" then
- handle(e,depth)
- withelements(e,handle,depth+1)
- end
- end
- end
- end
-end
-xml.withelements=withelements
-function xml.withelement(e,n,handle)
- if e and n~=0 and handle then
- local edt=e.dt
- if edt then
- if n>0 then
- for i=1,#edt do
- local ei=edt[i]
- if type(ei)=="table" then
- if n==1 then
- handle(ei)
- return
- else
- n=n-1
- end
- end
- end
- elseif n<0 then
- for i=#edt,1,-1 do
- local ei=edt[i]
- if type(ei)=="table" then
- if n==-1 then
- handle(ei)
- return
- else
- n=n+1
- end
- end
- end
- end
- end
- end
-end
-function xml.each(root,pattern,handle,reverse)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- if handle then
- if reverse then
- for c=#collected,1,-1 do
- handle(collected[c])
- end
- else
- for c=1,#collected do
- handle(collected[c])
- end
- end
- end
- return collected
- end
-end
-function xml.processattributes(root,pattern,handle)
- local collected=xmlapplylpath(root,pattern)
- if collected and handle then
- for c=1,#collected do
- handle(collected[c].at)
- end
- end
- return collected
-end
-function xml.collect(root,pattern)
- return xmlapplylpath(root,pattern)
-end
-function xml.collecttexts(root,pattern,flatten)
- local collected=xmlapplylpath(root,pattern)
- if collected and flatten then
- local xmltostring=xml.tostring
- for c=1,#collected do
- collected[c]=xmltostring(collected[c].dt)
- end
- end
- return collected or {}
-end
-function xml.collect_tags(root,pattern,nonamespace)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- local t={}
- local n=0
- for c=1,#collected do
- local e=collected[c]
- local ns=e.ns
- local tg=e.tg
- n=n+1
- if nonamespace then
- t[n]=tg
- elseif ns=="" then
- t[n]=tg
- else
- t[n]=ns..":"..tg
- end
- end
- return t
- end
-end
-local no_root={ no_root=true }
-local function redo_ni(d)
- for k=1,#d do
- local dk=d[k]
- if type(dk)=="table" then
- dk.ni=k
- end
- end
-end
-xml.reindex=redo_ni
-local function xmltoelement(whatever,root)
- if not whatever then
- return nil
- end
- local element
- if type(whatever)=="string" then
- element=xmlinheritedconvert(whatever,root,true)
- else
- element=whatever
- end
- if element.error then
- return whatever
- end
- if element then
- end
- return element
-end
-xml.toelement=xmltoelement
-local function copiedelement(element,newparent)
- if type(element)~="string" then
- element=xmlcopy(element).dt
- if newparent and type(element)=="table" then
- for i=1,#element do
- local e=element[i]
- if type(e)=="table" then
- e.__p__=newparent
- end
- end
- end
- end
- return element
-end
-function xml.delete(root,pattern)
- if not pattern or pattern=="" then
- local p=root.__p__
- if p then
- if trace_manipulations then
- report('deleting',"--",c,root)
- end
- local d=p.dt
- remove(d,root.ni)
- redo_ni(d)
- end
- else
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local p=e.__p__
- if p then
- if trace_manipulations then
- report('deleting',pattern,c,e)
- end
- local d=p.dt
- local ni=e.ni
- if ni<=#d then
- if false then
- p.dt[ni]=""
- else
- remove(d,ni)
- redo_ni(d)
- end
- else
- end
- end
- end
- end
- end
-end
-function xml.wipe(root,pattern)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local p=e.__p__
- if p then
- local d=p.dt
- local ni=e.ni
- if ni<=#d then
- local dt=e.dt
- if #dt==1 then
- local d1=dt[1]
- if type(d1)=="string" and match(d1,"^%s*$") then
- if trace_manipulations then
- report('wiping',pattern,c,e)
- end
- remove(d,ni)
- redo_ni(d)
- end
- end
- end
- end
- end
- end
-end
-function xml.replace(root,pattern,whatever)
- local element=root and xmltoelement(whatever,root)
- local collected=element and xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local p=e.__p__
- if p then
- if trace_manipulations then
- report('replacing',pattern,c,e)
- end
- local d=p.dt
- local n=e.ni
- local t=copiedelement(element,p)
- if type(t)=="table" then
- d[n]=t[1]
- for i=2,#t do
- n=n+1
- insert(d,n,t[i])
- end
- else
- d[n]=t
- end
- redo_ni(d)
- end
- end
- end
-end
-local function wrap(e,wrapper)
- local t={
- rn=e.rn,
- tg=e.tg,
- ns=e.ns,
- at=e.at,
- dt=e.dt,
- __p__=e,
- }
- setmetatable(t,getmetatable(e))
- e.rn=wrapper.rn or e.rn or ""
- e.tg=wrapper.tg or e.tg or ""
- e.ns=wrapper.ns or e.ns or ""
- e.at=fastcopy(wrapper.at)
- e.dt={ t }
-end
-function xml.wrap(root,pattern,whatever)
- if whatever then
- local wrapper=xmltoelement(whatever,root)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- if trace_manipulations then
- report('wrapping',pattern,c,e)
- end
- wrap(e,wrapper)
- end
- end
- else
- wrap(root,xmltoelement(pattern))
- end
-end
-local function inject_element(root,pattern,whatever,prepend)
- local element=root and xmltoelement(whatever,root)
- local collected=element and xmlapplylpath(root,pattern)
- local function inject_e(e)
- local r=e.__p__
- local d=r.dt
- local k=e.ni
- local rri=r.ri
- local edt=(rri and d[rri].dt) or (d and d[k] and d[k].dt)
- if edt then
- local be,af
- local cp=copiedelement(element,e)
- if prepend then
- be,af=cp,edt
- else
- be,af=edt,cp
- end
- local bn=#be
- for i=1,#af do
- bn=bn+1
- be[bn]=af[i]
- end
- if rri then
- r.dt[rri].dt=be
- else
- d[k].dt=be
- end
- redo_ni(d)
- end
- end
- if not collected then
- elseif collected.tg then
- inject_e(collected)
- else
- for c=1,#collected do
- inject_e(collected[c])
- end
- end
-end
-local function insert_element(root,pattern,whatever,before)
- local element=root and xmltoelement(whatever,root)
- local collected=element and xmlapplylpath(root,pattern)
- local function insert_e(e)
- local r=e.__p__
- local d=r.dt
- local k=e.ni
- if not before then
- k=k+1
- end
- insert(d,k,copiedelement(element,r))
- redo_ni(d)
- end
- if not collected then
- elseif collected.tg then
- insert_e(collected)
- else
- for c=1,#collected do
- insert_e(collected[c])
- end
- end
-end
-xml.insert_element=insert_element
-xml.insertafter=insert_element
-xml.insertbefore=function(r,p,e) insert_element(r,p,e,true) end
-xml.injectafter=inject_element
-xml.injectbefore=function(r,p,e) inject_element(r,p,e,true) end
-local function include(xmldata,pattern,attribute,recursive,loaddata,level)
- pattern=pattern or 'include'
- loaddata=loaddata or io.loaddata
- local collected=xmlapplylpath(xmldata,pattern)
- if collected then
- if not level then
- level=1
- end
- for c=1,#collected do
- local ek=collected[c]
- local name=nil
- local ekdt=ek.dt
- if ekdt then
- local ekat=ek.at
- local ekrt=ek.__p__
- if ekrt then
- local epdt=ekrt.dt
- if not attribute or attribute=="" then
- name=(type(ekdt)=="table" and ekdt[1]) or ekdt
- end
- if not name then
- for a in gmatch(attribute or "href","([^|]+)") do
- name=ekat[a]
- if name then
- break
- end
- end
- end
- local data=nil
- if name and name~="" then
- local d,n=loaddata(name)
- data=d or ""
- name=n or name
- if trace_inclusions then
- report_xml("including %s bytes from %a at level %s by pattern %a and attribute %a (%srecursing)",#data,name,level,pattern,attribute or "",recursive and "" or "not ")
- end
- end
- if not data or data=="" then
- epdt[ek.ni]=""
- elseif ekat["parse"]=="text" then
- epdt[ek.ni]=xml.escaped(data)
- else
- local settings=xmldata.settings
- local savedresource=settings.currentresource
- settings.currentresource=name
- local xi=xmlinheritedconvert(data,xmldata,true)
- if not xi then
- epdt[ek.ni]=""
- else
- if recursive then
- include(xi,pattern,attribute,recursive,loaddata,level+1)
- end
- local child=xml.body(xi)
- child.__p__=ekrt
- child.__f__=name
- child.cf=name
- epdt[ek.ni]=child
- local settings=xmldata.settings
- local inclusions=settings and settings.inclusions
- if inclusions then
- inclusions[#inclusions+1]=name
- elseif settings then
- settings.inclusions={ name }
- else
- settings={ inclusions={ name } }
- xmldata.settings=settings
- end
- if child.er then
- local badinclusions=settings.badinclusions
- if badinclusions then
- badinclusions[#badinclusions+1]=name
- else
- settings.badinclusions={ name }
- end
- end
- end
-settings.currentresource=savedresource
- end
- end
- end
- end
- end
-end
-xml.include=include
-function xml.inclusion(e,default)
- while e do
- local f=e.__f__
- if f then
- return f
- else
- e=e.__p__
- end
- end
- return default
-end
-local function getinclusions(key,e,sorted)
- while e do
- local settings=e.settings
- if settings then
- local inclusions=settings[key]
- if inclusions then
- inclusions=table.unique(inclusions)
- if sorted then
- table.sort(inclusions)
- end
- return inclusions
- else
- e=e.__p__
- end
- else
- e=e.__p__
- end
- end
-end
-function xml.inclusions(e,sorted)
- return getinclusions("inclusions",e,sorted)
-end
-function xml.badinclusions(e,sorted)
- return getinclusions("badinclusions",e,sorted)
-end
-local b_collapser=lpegpatterns.b_collapser
-local m_collapser=lpegpatterns.m_collapser
-local e_collapser=lpegpatterns.e_collapser
-local x_collapser=lpegpatterns.x_collapser
-local b_stripper=lpegpatterns.b_stripper
-local m_stripper=lpegpatterns.m_stripper
-local e_stripper=lpegpatterns.e_stripper
-local x_stripper=lpegpatterns.x_stripper
-local function stripelement(e,nolines,anywhere,everything)
- local edt=e.dt
- if edt then
- local n=#edt
- if n==0 then
- return e
- elseif everything then
- local t={}
- local m=0
- for i=1,n do
- local str=edt[i]
- if type(str)~="string" then
- m=m+1
- t[m]=str
- elseif str~="" then
- str=lpegmatch(x_collapser,str)
- if str~="" then
- m=m+1
- t[m]=str
- end
- end
- end
- e.dt=t
- elseif anywhere then
- local t={}
- local m=0
- for i=1,n do
- local str=edt[i]
- if type(str)~="string" then
- m=m+1
- t[m]=str
- elseif str~="" then
- if nolines then
- str=lpegmatch((i==1 and b_collapser) or (i==m and e_collapser) or m_collapser,str)
- else
- str=lpegmatch((i==1 and b_stripper) or (i==m and e_stripper) or m_stripper,str)
- end
- if str~="" then
- m=m+1
- t[m]=str
- end
- end
- end
- e.dt=t
- else
- local str=edt[1]
- if type(str)=="string" then
- if str~="" then
- str=lpegmatch(nolines and b_collapser or b_stripper,str)
- end
- if str=="" then
- remove(edt,1)
- n=n-1
- else
- edt[1]=str
- end
- end
- if n>0 then
- str=edt[n]
- if type(str)=="string" then
- if str=="" then
- remove(edt)
- else
- str=lpegmatch(nolines and e_collapser or e_stripper,str)
- if str=="" then
- remove(edt)
- else
- edt[n]=str
- end
- end
- end
- end
- end
- end
- return e
-end
-xml.stripelement=stripelement
-function xml.strip(root,pattern,nolines,anywhere,everything)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for i=1,#collected do
- stripelement(collected[i],nolines,anywhere,everything)
- end
- end
-end
-local function compactelement(e)
- local edt=e.dt
- if edt then
- for e=1,#edt do
- local str=edt[e]
- if type(str)=="string" and not find(str,"%S") then
- edt[e]=""
- end
- end
- end
- return e
-end
-xml.compactelement=compactelement
-local function renamespace(root,oldspace,newspace)
- local ndt=#root.dt
- for i=1,ndt or 0 do
- local e=root[i]
- if type(e)=="table" then
- if e.ns==oldspace then
- e.ns=newspace
- if e.rn then
- e.rn=newspace
- end
- end
- local edt=e.dt
- if edt then
- renamespace(edt,oldspace,newspace)
- end
- end
- end
-end
-xml.renamespace=renamespace
-function xml.remaptag(root,pattern,newtg)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- collected[c].tg=newtg
- end
- end
-end
-function xml.remapnamespace(root,pattern,newns)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- collected[c].ns=newns
- end
- end
-end
-function xml.checknamespace(root,pattern,newns)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- if (not e.rn or e.rn=="") and e.ns=="" then
- e.rn=newns
- end
- end
- end
-end
-function xml.remapname(root,pattern,newtg,newns,newrn)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- e.tg,e.ns,e.rn=newtg,newns,newrn
- end
- end
-end
-function xml.cdatatotext(e)
- local dt=e.dt
- if #dt==1 then
- local first=dt[1]
- if first.tg=="@cd@" then
- e.dt=first.dt
- end
- else
- end
-end
-function xml.texttocdata(e)
- local dt=e.dt
- local s=xml.tostring(dt)
- e.tg="@cd@"
- e.special=true
- e.ns=""
- e.rn=""
- e.dt={ s }
- e.at=nil
-end
-function xml.elementtocdata(e)
- local dt=e.dt
- local s=xml.tostring(e)
- e.tg="@cd@"
- e.special=true
- e.ns=""
- e.rn=""
- e.dt={ s }
- e.at=nil
-end
-xml.builtinentities=table.tohash { "amp","quot","apos","lt","gt" }
-local entities=characters and characters.entities or nil
-local builtinentities=xml.builtinentities
-function xml.addentitiesdoctype(root,option)
- if not entities then
- require("char-ent")
- entities=characters.entities
- end
- if entities and root and root.tg=="@rt@" and root.statistics then
- local list={}
- local hexify=option=="hexadecimal"
- for k,v in table.sortedhash(root.statistics.entities.names) do
- if not builtinentities[k] then
- local e=entities[k]
- if not e then
- e=format("[%s]",k)
- elseif hexify then
- e=format("&#%05X;",utfbyte(k))
- end
- list[#list+1]=format(" <!ENTITY %s %q >",k,e)
- end
- end
- local dt=root.dt
- local n=dt[1].tg=="@pi@" and 2 or 1
- if #list>0 then
- insert(dt,n,{ "\n" })
- insert(dt,n,{
- tg="@dt@",
- dt={ format("Something [\n%s\n] ",concat(list)) },
- ns="",
- special=true,
- })
- insert(dt,n,{ "\n\n" })
- else
- end
- end
-end
-xml.all=xml.each
-xml.insert=xml.insertafter
-xml.inject=xml.injectafter
-xml.after=xml.insertafter
-xml.before=xml.insertbefore
-xml.process=xml.each
-xml.obsolete=xml.obsolete or {}
-local obsolete=xml.obsolete
-xml.strip_whitespace=xml.strip obsolete.strip_whitespace=xml.strip
-xml.collect_elements=xml.collect obsolete.collect_elements=xml.collect
-xml.delete_element=xml.delete obsolete.delete_element=xml.delete
-xml.replace_element=xml.replace obsolete.replace_element=xml.replace
-xml.each_element=xml.each obsolete.each_element=xml.each
-xml.process_elements=xml.process obsolete.process_elements=xml.process
-xml.insert_element_after=xml.insertafter obsolete.insert_element_after=xml.insertafter
-xml.insert_element_before=xml.insertbefore obsolete.insert_element_before=xml.insertbefore
-xml.inject_element_after=xml.injectafter obsolete.inject_element_after=xml.injectafter
-xml.inject_element_before=xml.injectbefore obsolete.inject_element_before=xml.injectbefore
-xml.process_attributes=xml.processattributes obsolete.process_attributes=xml.processattributes
-xml.collect_texts=xml.collecttexts obsolete.collect_texts=xml.collecttexts
-xml.inject_element=xml.inject obsolete.inject_element=xml.inject
-xml.remap_tag=xml.remaptag obsolete.remap_tag=xml.remaptag
-xml.remap_name=xml.remapname obsolete.remap_name=xml.remapname
-xml.remap_namespace=xml.remapnamespace obsolete.remap_namespace=xml.remapnamespace
-function xml.cdata(e)
- if e then
- local dt=e.dt
- if dt and #dt==1 then
- local first=dt[1]
- return first.tg=="@cd@" and first.dt[1] or ""
- end
- end
- return ""
-end
-function xml.finalizers.xml.cdata(collected)
- if collected then
- local e=collected[1]
- if e then
- local dt=e.dt
- if dt and #dt==1 then
- local first=dt[1]
- return first.tg=="@cd@" and first.dt[1] or ""
- end
- end
- end
- return ""
-end
-function xml.insertcomment(e,str,n)
- insert(e.dt,n or 1,{
- tg="@cm@",
- ns="",
- special=true,
- at={},
- dt={ str },
- })
-end
-function xml.insertcdata(e,str,n)
- insert(e.dt,n or 1,{
- tg="@cd@",
- ns="",
- special=true,
- at={},
- dt={ str },
- })
-end
-function xml.setcomment(e,str,n)
- e.dt={ {
- tg="@cm@",
- ns="",
- special=true,
- at={},
- dt={ str },
- } }
-end
-function xml.setcdata(e,str)
- e.dt={ {
- tg="@cd@",
- ns="",
- special=true,
- at={},
- dt={ str },
- } }
-end
-function xml.separate(x,pattern)
- local collected=xmlapplylpath(x,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local d=e.dt
- if d==x then
- report_xml("warning: xml.separate changes root")
- x=d
- end
- local t={ "\n" }
- local n=1
- local i=1
- local nd=#d
- while i<=nd do
- while i<=nd do
- local di=d[i]
- if type(di)=="string" then
- if di=="\n" or find(di,"^%s+$") then
- i=i+1
- else
- d[i]=strip(di)
- break
- end
- else
- break
- end
- end
- if i>nd then
- break
- end
- t[n+1]="\n"
- t[n+2]=d[i]
- t[n+3]="\n"
- n=n+3
- i=i+1
- end
- t[n+1]="\n"
- setmetatable(t,getmetatable(d))
- e.dt=t
- end
- end
- return x
-end
-local helpers=xml.helpers or {}
-xml.helpers=helpers
-local function normal(e,action)
- local edt=e.dt
- if edt then
- for i=1,#edt do
- local str=edt[i]
- if type(str)=="string" and str~="" then
- edt[i]=action(str)
- end
- end
- end
-end
-local function recurse(e,action)
- local edt=e.dt
- if edt then
- for i=1,#edt do
- local str=edt[i]
- if type(str)~="string" then
- recurse(str,action)
- elseif str~="" then
- edt[i]=action(str)
- end
- end
- end
-end
-function helpers.recursetext(collected,action,recursive)
- if recursive then
- for i=1,#collected do
- recurse(collected[i],action)
- end
- else
- for i=1,#collected do
- normal(collected[i],action)
- end
- end
-end
-local specials={
- ["@rt@"]="root",
- ["@pi@"]="instruction",
- ["@cm@"]="comment",
- ["@dt@"]="declaration",
- ["@cd@"]="cdata",
-}
-local function convert(x,strip,flat)
- local ns=x.ns
- local tg=x.tg
- local at=x.at
- local dt=x.dt
- local node=flat and {
- [0]=(not x.special and (ns~="" and ns..":"..tg or tg)) or nil,
- } or {
- _namespace=ns~="" and ns or nil,
- _tag=not x.special and tg or nil,
- _type=specials[tg] or "_element",
- }
- if at then
- for k,v in next,at do
- node[k]=v
- end
- end
- local n=0
- for i=1,#dt do
- local di=dt[i]
- if type(di)=="table" then
- if flat and di.special then
- else
- di=convert(di,strip,flat)
- if di then
- n=n+1
- node[n]=di
- end
- end
- elseif strip then
- di=lpegmatch(strip,di)
- if di~="" then
- n=n+1
- node[n]=di
- end
- else
- n=n+1
- node[n]=di
- end
- end
- if next(node) then
- return node
- end
-end
-function xml.totable(x,strip,flat)
- if type(x)=="table" then
- if strip then
- strip=striplinepatterns[strip]
- end
- return convert(x,strip,flat)
- end
-end
-function xml.rename(e,namespace,name,attributes)
- if type(e)~="table" or not e.tg then
- return
- end
- if type(name)=="table" then
- attributes=name
- name=namespace
- namespace=""
- elseif type(name)~="string" then
- attributes={}
- name=namespace
- namespace=""
- end
- if type(attributes)~="table" then
- attributes={}
- end
- e.ns=namespace
- e.rn=namespace
- e.tg=name
- e.at=attributes
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-xml"] = package.loaded["lxml-xml"] or true
-
--- original size: 11096, stripped down to: 7702
-
-if not modules then modules={} end modules ['lxml-xml']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local tonumber,next=tonumber,next
-local concat=table.concat
-local find,lower,upper=string.find,string.lower,string.upper
-local xml=xml
-local finalizers=xml.finalizers.xml
-local xmlfilter=xml.filter
-local xmltostring=xml.tostring
-local xmlserialize=xml.serialize
-local xmlcollected=xml.collected
-local xmlnewhandlers=xml.newhandlers
-local reparsedentity=xml.reparsedentitylpeg
-local unescapedentity=xml.unescapedentitylpeg
-local parsedentity=reparsedentity
-local function first(collected)
- return collected and collected[1]
-end
-local function last(collected)
- return collected and collected[#collected]
-end
-local function all(collected)
- return collected
-end
-local reverse=table.reversed
-local function attribute(collected,name)
- if collected and #collected>0 then
- local at=collected[1].at
- return at and at[name]
- end
-end
-local function att(id,name)
- local at=id.at
- return at and at[name]
-end
-local function count(collected)
- return collected and #collected or 0
-end
-local function position(collected,n)
- if not collected then
- return 0
- end
- local nc=#collected
- if nc==0 then
- return 0
- end
- n=tonumber(n) or 0
- if n<0 then
- return collected[nc+n+1]
- elseif n>0 then
- return collected[n]
- else
- return collected[1].mi or 0
- end
-end
-local function match(collected)
- return collected and #collected>0 and collected[1].mi or 0
-end
-local function index(collected)
- return collected and #collected>0 and collected[1].ni or 0
-end
-local function attributes(collected,arguments)
- if collected and #collected>0 then
- local at=collected[1].at
- if arguments then
- return at[arguments]
- elseif next(at) then
- return at
- end
- end
-end
-local function chainattribute(collected,arguments)
- if collected and #collected>0 then
- local e=collected[1]
- while e do
- local at=e.at
- if at then
- local a=at[arguments]
- if a then
- return a
- end
- else
- break
- end
- e=e.__p__
- end
- end
- return ""
-end
-local function raw(collected)
- if collected and #collected>0 then
- local e=collected[1] or collected
- return e and xmltostring(e) or ""
- else
- return ""
- end
-end
-local xmltexthandler=xmlnewhandlers {
- name="string",
- initialize=function()
- result={}
- return result
- end,
- finalize=function()
- return concat(result)
- end,
- handle=function(...)
- result[#result+1]=concat {... }
- end,
- escape=false,
-}
-local function xmltotext(root)
- local dt=root.dt
- if not dt then
- return ""
- end
- local nt=#dt
- if nt==0 then
- return ""
- elseif nt==1 and type(dt[1])=="string" then
- return dt[1]
- else
- return xmlserialize(root,xmltexthandler) or ""
- end
-end
-function xml.serializetotext(root)
- return root and xmlserialize(root,xmltexthandler) or ""
-end
-local function text(collected)
- if collected then
- local e=collected[1] or collected
- return e and xmltotext(e) or ""
- else
- return ""
- end
-end
-local function texts(collected)
- if not collected then
- return {}
- end
- local nc=#collected
- if nc==0 then
- return {}
- end
- local t,n={},0
- for c=1,nc do
- local e=collected[c]
- if e and e.dt then
- n=n+1
- t[n]=e.dt
- end
- end
- return t
-end
-local function tag(collected,n)
- if not collected then
- return
- end
- local nc=#collected
- if nc==0 then
- return
- end
- local c
- if n==0 or not n then
- c=collected[1]
- elseif n>1 then
- c=collected[n]
- else
- c=collected[nc-n+1]
- end
- return c and c.tg
-end
-local function name(collected,n)
- if not collected then
- return
- end
- local nc=#collected
- if nc==0 then
- return
- end
- local c
- if n==0 or not n then
- c=collected[1]
- elseif n>1 then
- c=collected[n]
- else
- c=collected[nc-n+1]
- end
- if not c then
- elseif c.ns=="" then
- return c.tg
- else
- return c.ns..":"..c.tg
- end
-end
-local function tags(collected,nonamespace)
- if not collected then
- return
- end
- local nc=#collected
- if nc==0 then
- return
- end
- local t,n={},0
- for c=1,nc do
- local e=collected[c]
- local ns,tg=e.ns,e.tg
- n=n+1
- if nonamespace or ns=="" then
- t[n]=tg
- else
- t[n]=ns..":"..tg
- end
- end
- return t
-end
-local function empty(collected,spacesonly)
- if not collected then
- return true
- end
- local nc=#collected
- if nc==0 then
- return true
- end
- for c=1,nc do
- local e=collected[c]
- if e then
- local edt=e.dt
- if edt then
- local n=#edt
- if n==1 then
- local edk=edt[1]
- local typ=type(edk)
- if typ=="table" then
- return false
- elseif edk~="" then
- return false
- elseif spacesonly and not find(edk,"%S") then
- return false
- end
- elseif n>1 then
- return false
- end
- end
- end
- end
- return true
-end
-finalizers.first=first
-finalizers.last=last
-finalizers.all=all
-finalizers.reverse=reverse
-finalizers.elements=all
-finalizers.default=all
-finalizers.attribute=attribute
-finalizers.att=att
-finalizers.count=count
-finalizers.position=position
-finalizers.match=match
-finalizers.index=index
-finalizers.attributes=attributes
-finalizers.chainattribute=chainattribute
-finalizers.text=text
-finalizers.texts=texts
-finalizers.tag=tag
-finalizers.name=name
-finalizers.tags=tags
-finalizers.empty=empty
-function xml.first(id,pattern)
- return first(xmlfilter(id,pattern))
-end
-function xml.last(id,pattern)
- return last(xmlfilter(id,pattern))
-end
-function xml.count(id,pattern)
- return count(xmlfilter(id,pattern))
-end
-function xml.attribute(id,pattern,a,default)
- return attribute(xmlfilter(id,pattern),a,default)
-end
-function xml.raw(id,pattern)
- if pattern then
- return raw(xmlfilter(id,pattern))
- else
- return raw(id)
- end
-end
-function xml.text(id,pattern)
- if pattern then
- local collected=xmlfilter(id,pattern)
- return collected and #collected>0 and xmltotext(collected[1]) or ""
- elseif id then
- return xmltotext(id) or ""
- else
- return ""
- end
-end
-function xml.pure(id,pattern)
- if pattern then
- local collected=xmlfilter(id,pattern)
- if collected and #collected>0 then
- parsedentity=unescapedentity
- local s=collected and #collected>0 and xmltotext(collected[1]) or ""
- parsedentity=reparsedentity
- return s
- else
- return ""
- end
- else
- parsedentity=unescapedentity
- local s=xmltotext(id) or ""
- parsedentity=reparsedentity
- return s
- end
-end
-xml.content=text
-function xml.position(id,pattern,n)
- return position(xmlfilter(id,pattern),n)
-end
-function xml.match(id,pattern)
- return match(xmlfilter(id,pattern))
-end
-function xml.empty(id,pattern,spacesonly)
- return empty(xmlfilter(id,pattern),spacesonly)
-end
-xml.all=xml.filter
-xml.index=xml.position
-xml.found=xml.filter
-local function totable(x)
- local t={}
- for e in xmlcollected(x[1] or x,"/*") do
- t[e.tg]=xmltostring(e.dt) or ""
- end
- return next(t) and t or nil
-end
-xml.table=totable
-finalizers.table=totable
-local function textonly(e,t)
- if e then
- local edt=e.dt
- if edt then
- for i=1,#edt do
- local e=edt[i]
- if type(e)=="table" then
- textonly(e,t)
- else
- t[#t+1]=e
- end
- end
- end
- end
- return t
-end
-function xml.textonly(e)
- return concat(textonly(e,{}))
-end
-function finalizers.lowerall(collected)
- for c=1,#collected do
- local e=collected[c]
- if not e.special then
- e.tg=lower(e.tg)
- local eat=e.at
- if eat then
- local t={}
- for k,v in next,eat do
- t[lower(k)]=v
- end
- e.at=t
- end
- end
- end
-end
-function finalizers.upperall(collected)
- for c=1,#collected do
- local e=collected[c]
- if not e.special then
- e.tg=upper(e.tg)
- local eat=e.at
- if eat then
- local t={}
- for k,v in next,eat do
- t[upper(k)]=v
- end
- e.at=t
- end
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-xml"] = package.loaded["trac-xml"] or true
-
--- original size: 6407, stripped down to: 4640
-
-if not modules then modules={} end modules ['trac-xml']={
- version=1.001,
- comment="companion to trac-log.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local formatters=string.formatters
-local reporters=logs.reporters
-local xmlserialize=xml.serialize
-local xmlcollected=xml.collected
-local xmltext=xml.text
-local xmlfirst=xml.first
-local function showhelp(specification,...)
- local root=xml.convert(specification.helpinfo or "")
- if not root then
- return
- end
- local xs=xml.gethandlers("string")
- xml.sethandlersfunction(xs,"short",function(e,handler) xmlserialize(e.dt,handler) end)
- xml.sethandlersfunction(xs,"ref",function(e,handler) handler.handle("--"..e.at.name) end)
- local wantedcategories=select("#",...)==0 and true or table.tohash {... }
- local nofcategories=xml.count(root,"/application/flags/category")
- local report=specification.report
- for category in xmlcollected(root,"/application/flags/category") do
- local categoryname=category.at.name or ""
- if wantedcategories==true or wantedcategories[categoryname] then
- if nofcategories>1 then
- report("%s options:",categoryname)
- report()
- end
- for subcategory in xmlcollected(category,"/subcategory") do
- for flag in xmlcollected(subcategory,"/flag") do
- local name=flag.at.name
- local value=flag.at.value
- local short=xmltext(xmlfirst(flag,"/short"))
- if value then
- report("--%-20s %s",formatters["%s=%s"](name,value),short)
- else
- report("--%-20s %s",name,short)
- end
- end
- report()
- end
- end
- end
- for category in xmlcollected(root,"/application/examples/category") do
- local title=xmltext(xmlfirst(category,"/title"))
- if title and title~="" then
- report()
- report(title)
- report()
- end
- for subcategory in xmlcollected(category,"/subcategory") do
- for example in xmlcollected(subcategory,"/example") do
- local command=xmltext(xmlfirst(example,"/command"))
- local comment=xmltext(xmlfirst(example,"/comment"))
- report(command)
- end
- report()
- end
- end
- for comment in xmlcollected(root,"/application/comments/comment") do
- local comment=xmltext(comment)
- report()
- report(comment)
- report()
- end
-end
-local reporthelp=reporters.help
-local exporthelp=reporters.export
-local function xmlfound(t)
- local helpinfo=t.helpinfo
- if type(helpinfo)=="table" then
- return false
- end
- if type(helpinfo)~="string" then
- helpinfo="Warning: no helpinfo found."
- t.helpinfo=helpinfo
- return false
- end
- if string.find(helpinfo,".xml$") then
- local ownscript=environment.ownscript
- local helpdata=false
- if ownscript then
- local helpfile=file.join(file.pathpart(ownscript),helpinfo)
- helpdata=io.loaddata(helpfile)
- if helpdata=="" then
- helpdata=false
- end
- end
- if not helpdata then
- local helpfile=resolvers.findfile(helpinfo,"tex")
- helpdata=helpfile and io.loaddata(helpfile)
- end
- if helpdata and helpdata~="" then
- helpinfo=helpdata
- else
- helpinfo=formatters["Warning: help file %a is not found."](helpinfo)
- end
- end
- t.helpinfo=helpinfo
- return string.find(t.helpinfo,"^<%?xml") and true or false
-end
-function reporters.help(t,...)
- if xmlfound(t) then
- showhelp(t,...)
- else
- reporthelp(t,...)
- end
-end
-function reporters.export(t,methods,filename)
- if not xmlfound(t) then
- return exporthelp(t)
- end
- if not methods or methods=="" then
- methods=environment.arguments["exporthelp"]
- end
- if not filename or filename=="" then
- filename=environment.files[1]
- end
- dofile(resolvers.findfile("trac-exp.lua","tex"))
- local exporters=logs.exporters
- if not exporters or not methods then
- return exporthelp(t)
- end
- if methods=="all" then
- methods=table.keys(exporters)
- elseif type(methods)=="string" then
- methods=utilities.parsers.settings_to_array(methods)
- else
- return exporthelp(t)
- end
- if type(filename)~="string" or filename=="" then
- filename=false
- elseif file.pathpart(filename)=="" then
- t.report("export file %a will not be saved on the current path (safeguard)",filename)
- return
- end
- for i=1,#methods do
- local method=methods[i]
- local exporter=exporters[method]
- if exporter then
- local result=exporter(t,method)
- if result and result~="" then
- if filename then
- local fullname=file.replacesuffix(filename,method)
- t.report("saving export in %a",fullname)
- dir.mkdirs(file.pathpart(fullname))
- io.savedata(fullname,result)
- else
- reporters.lines(t,result)
- end
- else
- t.report("no output from exporter %a",method)
- end
- else
- t.report("unknown exporter %a",method)
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-ini"] = package.loaded["data-ini"] or true
-
--- original size: 10947, stripped down to: 7176
-
-if not modules then modules={} end modules ['data-ini']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local next,type,getmetatable,rawset=next,type,getmetatable,rawset
-local gsub,find,gmatch,char=string.gsub,string.find,string.gmatch,string.char
-local filedirname,filebasename,filejoin=file.dirname,file.basename,file.join
-local ostype,osname,osuname,ossetenv,osgetenv=os.type,os.name,os.uname,os.setenv,os.getenv
-local sortedpairs=table.sortedpairs
-local P,S,R,C,Cs,Cc,lpegmatch=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.match
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local trace_expansions=false trackers.register("resolvers.expansions",function(v) trace_expansions=v end)
-local report_initialization=logs.reporter("resolvers","initialization")
-resolvers=resolvers or {}
-local resolvers=resolvers
-texconfig.kpse_init=false
-texconfig.shell_escape='t'
-if not (environment and environment.default_texmfcnf) and kpse and kpse.default_texmfcnf then
- local default_texmfcnf=kpse.default_texmfcnf()
- default_texmfcnf=gsub(default_texmfcnf,"$SELFAUTOLOC","selfautoloc:")
- default_texmfcnf=gsub(default_texmfcnf,"$SELFAUTODIR","selfautodir:")
- default_texmfcnf=gsub(default_texmfcnf,"$SELFAUTOPARENT","selfautoparent:")
- default_texmfcnf=gsub(default_texmfcnf,"$HOME","home:")
- environment.default_texmfcnf=default_texmfcnf
-end
-kpse={ original=kpse }
-setmetatable(kpse,{
- __index=function(kp,name)
- report_initialization("fatal error: kpse library is accessed (key: %s)",name)
- os.exit()
- end
-} )
-do
- local osfontdir=osgetenv("OSFONTDIR")
- if osfontdir and osfontdir~="" then
- elseif osname=="windows" then
- ossetenv("OSFONTDIR","c:/windows/fonts//")
- elseif osname=="macosx" then
- ossetenv("OSFONTDIR","$HOME/Library/Fonts//;/Library/Fonts//;/System/Library/Fonts//")
- end
-end
-if not environment.homedir then
- local oldhome=osgetenv('HOME')
- local homedir=osgetenv(ostype=="windows" and 'USERPROFILE' or 'HOME') or ''
- if not homedir or homedir=="" then
- homedir=char(127)
- end
- homedir=file.collapsepath(homedir)
- ossetenv("HOME",homedir)
- ossetenv("USERPROFILE",homedir)
- environment.oldhome=oldhome
- environment.homedir=homedir
-end
-do
- local args=environment.originalarguments or arg
- if not environment.ownmain then
- environment.ownmain=status and string.match(string.lower(status.banner),"this is ([%a]+)") or "luatex"
- end
- local ownbin=environment.ownbin or args[-2] or arg[-2] or args[-1] or arg[-1] or arg[0] or "luatex"
- local ownpath=environment.ownpath or os.selfdir
- ownbin=file.collapsepath(ownbin)
- ownpath=file.collapsepath(ownpath)
- if not ownpath or ownpath=="" or ownpath=="unset" then
- ownpath=args[-1] or arg[-1]
- ownpath=ownpath and filedirname(gsub(ownpath,"\\","/"))
- if not ownpath or ownpath=="" then
- ownpath=args[-0] or arg[-0]
- ownpath=ownpath and filedirname(gsub(ownpath,"\\","/"))
- end
- local binary=ownbin
- if not ownpath or ownpath=="" then
- ownpath=ownpath and filedirname(binary)
- end
- if not ownpath or ownpath=="" then
- if os.binsuffix~="" then
- binary=file.replacesuffix(binary,os.binsuffix)
- end
- local path=osgetenv("PATH")
- if path then
- for p in gmatch(path,"[^"..io.pathseparator.."]+") do
- local b=filejoin(p,binary)
- if lfs.isfile(b) then
- local olddir=lfs.currentdir()
- if lfs.chdir(p) then
- local pp=lfs.currentdir()
- if trace_locating and p~=pp then
- report_initialization("following symlink %a to %a",p,pp)
- end
- ownpath=pp
- lfs.chdir(olddir)
- else
- if trace_locating then
- report_initialization("unable to check path %a",p)
- end
- ownpath=p
- end
- break
- end
- end
- end
- end
- if not ownpath or ownpath=="" then
- ownpath="."
- report_initialization("forcing fallback to ownpath %a",ownpath)
- elseif trace_locating then
- report_initialization("using ownpath %a",ownpath)
- end
- end
- environment.ownbin=ownbin
- environment.ownpath=ownpath
-end
-resolvers.ownpath=environment.ownpath
-function resolvers.getownpath()
- return environment.ownpath
-end
-do
- local ownpath=environment.ownpath or dir.current()
- if ownpath then
- ossetenv('SELFAUTOLOC',file.collapsepath(ownpath))
- ossetenv('SELFAUTODIR',file.collapsepath(ownpath.."/.."))
- ossetenv('SELFAUTOPARENT',file.collapsepath(ownpath.."/../.."))
- else
- report_initialization("error: unable to locate ownpath")
- os.exit()
- end
-end
-local texos=environment.texos or osgetenv("TEXOS")
-local texmfos=environment.texmfos or osgetenv('SELFAUTODIR')
-if not texos or texos=="" then
- texos=file.basename(texmfos)
-end
-ossetenv('TEXMFOS',texmfos)
-ossetenv('TEXOS',texos)
-ossetenv('SELFAUTOSYSTEM',os.platform)
-environment.texos=texos
-environment.texmfos=texmfos
-local texroot=environment.texroot or osgetenv("TEXROOT")
-if not texroot or texroot=="" then
- texroot=osgetenv('SELFAUTOPARENT')
- ossetenv('TEXROOT',texroot)
-end
-environment.texroot=file.collapsepath(texroot)
-local prefixes=utilities.storage.allocate()
-resolvers.prefixes=prefixes
-local resolved={}
-local abstract={}
-local dynamic={}
-function resolvers.resetresolve(str)
- resolved,abstract={},{}
-end
-function resolvers.allprefixes(separator)
- local all=table.sortedkeys(prefixes)
- if separator then
- for i=1,#all do
- all[i]=all[i]..":"
- end
- end
- return all
-end
-local function _resolve_(method,target)
- local action=prefixes[method]
- if action then
- return action(target)
- else
- return method..":"..target
- end
-end
-function resolvers.unresolve(str)
- return abstract[str] or str
-end
-function resolvers.setdynamic(str)
- dynamic[str]=true
-end
-local pattern=Cs((C(R("az")^2)*P(":")*C((1-S(" \"\';,"))^1)/_resolve_+P(1))^0)
-local prefix=C(R("az")^2)*P(":")
-local target=C((1-S(" \"\';,"))^1)
-local notarget=(#S(";,")+P(-1))*Cc("")
-local p_resolve=Cs(((prefix*(target+notarget))/_resolve_+P(1))^0)
-local p_simple=prefix*P(-1)
-local function resolve(str)
- if type(str)=="table" then
- local res={}
- for i=1,#str do
- res[i]=resolve(str[i])
- end
- return res
- end
- local res=resolved[str]
- if res then
- return res
- end
- local simple=lpegmatch(p_simple,str)
- local action=prefixes[simple]
- if action then
- local res=action(res)
- if not dynamic[simple] then
- resolved[simple]=res
- abstract[res]=simple
- end
- return res
- end
- res=lpegmatch(p_resolve,str)
- resolved[str]=res
- abstract[res]=str
- return res
-end
-resolvers.resolve=resolve
-if type(osuname)=="function" then
- for k,v in next,osuname() do
- if not prefixes[k] then
- prefixes[k]=function() return v end
- end
- end
-end
-if ostype=="unix" then
- local pattern
- local function makepattern(t,k,v)
- if t then
- rawset(t,k,v)
- end
- local colon=P(":")
- for k,v in sortedpairs(prefixes) do
- if p then
- p=P(k)+p
- else
- p=P(k)
- end
- end
- pattern=Cs((p*colon+colon/";"+P(1))^0)
- end
- makepattern()
- table.setmetatablenewindex(prefixes,makepattern)
- function resolvers.repath(str)
- return lpegmatch(pattern,str)
- end
-else
- function resolvers.repath(str)
- return str
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-exp"] = package.loaded["data-exp"] or true
-
--- original size: 18179, stripped down to: 10432
-
-if not modules then modules={} end modules ['data-exp']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local format,find,gmatch,lower,char,sub=string.format,string.find,string.gmatch,string.lower,string.char,string.sub
-local concat,sort=table.concat,table.sort
-local sortedkeys=table.sortedkeys
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local Ct,Cs,Cc,Carg,P,C,S=lpeg.Ct,lpeg.Cs,lpeg.Cc,lpeg.Carg,lpeg.P,lpeg.C,lpeg.S
-local type,next=type,next
-local isdir=lfs.isdir
-local collapsepath,joinpath,basename=file.collapsepath,file.join,file.basename
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local trace_expansions=false trackers.register("resolvers.expansions",function(v) trace_expansions=v end)
-local trace_globbing=true trackers.register("resolvers.globbing",function(v) trace_globbing=v end)
-local report_expansions=logs.reporter("resolvers","expansions")
-local report_globbing=logs.reporter("resolvers","globbing")
-local resolvers=resolvers
-local resolveprefix=resolvers.resolve
-local function f_both(a,b)
- local t,n={},0
- for sb in gmatch(b,"[^,]+") do
- for sa in gmatch(a,"[^,]+") do
- n=n+1;t[n]=sa..sb
- end
- end
- return concat(t,",")
-end
-local comma=P(",")
-local nocomma=(1-comma)^1
-local docomma=comma^1/","
-local before=Cs((nocomma*Carg(1)+docomma)^0)
-local after=Cs((Carg(1)*nocomma+docomma)^0)
-local both=Cs(((C(nocomma)*Carg(1))/function(a,b) return lpegmatch(before,b,1,a) end+docomma)^0)
-local function f_first (a,b) return lpegmatch(after,b,1,a) end
-local function f_second(a,b) return lpegmatch(before,a,1,b) end
-local function f_both (a,b) return lpegmatch(both,b,1,a) end
-local left=P("{")
-local right=P("}")
-local var=P((1-S("{}" ))^0)
-local set=P((1-S("{},"))^0)
-local other=P(1)
-local l_first=Cs((Cc("{")*(C(set)*left*C(var)*right/f_first)*Cc("}")+other )^0 )
-local l_second=Cs((Cc("{")*(left*C(var)*right*C(set)/f_second)*Cc("}")+other )^0 )
-local l_both=Cs((Cc("{")*(left*C(var)*right*left*C(var)*right/f_both)*Cc("}")+other )^0 )
-local l_rest=Cs((left*var*(left/"")*var*(right/"")*var*right+other )^0 )
-local stripper_1=lpeg.stripper ("{}@")
-local replacer_1=lpeg.replacer { { ",}",",@}" },{ "{,","{@," },}
-local function splitpathexpr(str,newlist,validate)
- if trace_expansions then
- report_expansions("expanding variable %a",str)
- end
- local t,ok,done=newlist or {},false,false
- local n=#t
- str=lpegmatch(replacer_1,str)
- repeat
- local old=str
- repeat
- local old=str
- str=lpegmatch(l_first,str)
- until old==str
- repeat
- local old=str
- str=lpegmatch(l_second,str)
- until old==str
- repeat
- local old=str
- str=lpegmatch(l_both,str)
- until old==str
- repeat
- local old=str
- str=lpegmatch(l_rest,str)
- until old==str
- until old==str
- str=lpegmatch(stripper_1,str)
- if validate then
- for s in gmatch(str,"[^,]+") do
- s=validate(s)
- if s then
- n=n+1
- t[n]=s
- end
- end
- else
- for s in gmatch(str,"[^,]+") do
- n=n+1
- t[n]=s
- end
- end
- if trace_expansions then
- for k=1,#t do
- report_expansions("% 4i: %s",k,t[k])
- end
- end
- return t
-end
-local function validate(s)
- s=collapsepath(s)
- return s~="" and not find(s,"^!*unset/*$") and s
-end
-resolvers.validatedpath=validate
-function resolvers.expandedpathfromlist(pathlist)
- local newlist={}
- for k=1,#pathlist do
- splitpathexpr(pathlist[k],newlist,validate)
- end
- return newlist
-end
-local usedhomedir=nil
-local donegation=(P("!")/"" )^0
-local doslashes=(P("\\")/"/"+1)^0
-local function expandedhome()
- if not usedhomedir then
- usedhomedir=lpegmatch(Cs(donegation*doslashes),environment.homedir or "")
- if usedhomedir=="~" or usedhomedir=="" or not isdir(usedhomedir) then
- if trace_expansions then
- report_expansions("no home dir set, ignoring dependent path using current path")
- end
- usedhomedir="."
- end
- end
- return usedhomedir
-end
-local dohome=((P("~")+P("$HOME")+P("%HOME%"))/expandedhome)^0
-local cleanup=Cs(donegation*dohome*doslashes)
-resolvers.cleanpath=function(str)
- return str and lpegmatch(cleanup,str) or ""
-end
-local expandhome=P("~")/"$HOME"
-local dodouble=P('"')/""*(expandhome+(1-P('"')))^0*P('"')/""
-local dosingle=P("'")/""*(expandhome+(1-P("'")))^0*P("'")/""
-local dostring=(expandhome+1 )^0
-local stripper=Cs(
- lpegpatterns.unspacer*(dosingle+dodouble+dostring)*lpegpatterns.unspacer
-)
-function resolvers.checkedvariable(str)
- return type(str)=="string" and lpegmatch(stripper,str) or str
-end
-local cache={}
-local splitter=lpeg.tsplitat(";")
-local backslashswapper=lpeg.replacer("\\","/")
-local function splitconfigurationpath(str)
- if str then
- local found=cache[str]
- if not found then
- if str=="" then
- found={}
- else
- local split=lpegmatch(splitter,lpegmatch(backslashswapper,str))
- found={}
- local noffound=0
- for i=1,#split do
- local s=split[i]
- if not find(s,"^{*unset}*") then
- noffound=noffound+1
- found[noffound]=s
- end
- end
- if trace_expansions then
- report_expansions("splitting path specification %a",str)
- for k=1,noffound do
- report_expansions("% 4i: %s",k,found[k])
- end
- end
- cache[str]=found
- end
- end
- return found
- end
-end
-resolvers.splitconfigurationpath=splitconfigurationpath
-function resolvers.splitpath(str)
- if type(str)=='table' then
- return str
- else
- return splitconfigurationpath(str)
- end
-end
-function resolvers.joinpath(str)
- if type(str)=='table' then
- return joinpath(str)
- else
- return str
- end
-end
-local attributes,directory=lfs.attributes,lfs.dir
-local weird=P(".")^1+lpeg.anywhere(S("~`!#$%^&*()={}[]:;\"\'||<>,?\n\r\t"))
-local lessweird=P(".")^1+lpeg.anywhere(S("~`#$%^&*:;\"\'||<>,?\n\r\t"))
-local timer={}
-local scanned={}
-local nofscans=0
-local scancache={}
-local fullcache={}
-local nofsharedscans=0
-local addcasecraptoo=true
-local function scan(files,remap,spec,path,n,m,r,onlyone,tolerant)
- local full=path=="" and spec or (spec..path..'/')
- local dirlist={}
- local nofdirs=0
- local pattern=tolerant and lessweird or weird
- local filelist={}
- local noffiles=0
- for name,mode in directory(full) do
- if not lpegmatch(pattern,name) then
- if not mode then
- mode=attributes(full..name,"mode")
- end
- if mode=="file" then
- n=n+1
- noffiles=noffiles+1
- filelist[noffiles]=name
- elseif mode=="directory" then
- m=m+1
- nofdirs=nofdirs+1
- if path~="" then
- dirlist[nofdirs]=path.."/"..name
- else
- dirlist[nofdirs]=name
- end
- end
- end
- end
- if noffiles>0 then
- sort(filelist)
- for i=1,noffiles do
- local name=filelist[i]
- local lower=lower(name)
- local paths=files[lower]
- if paths then
- if onlyone then
- else
- if name~=lower then
- local rl=remap[lower]
- if not rl then
- remap[lower]=name
- r=r+1
- elseif trace_globbing and rl~=name then
- report_globbing("confusing filename, name: %a, lower: %a, already: %a",name,lower,rl)
- end
- if addcasecraptoo then
- local paths=files[name]
- if not paths then
- files[name]=path
- elseif type(paths)=="string" then
- files[name]={ paths,path }
- else
- paths[#paths+1]=path
- end
- end
- end
- if type(paths)=="string" then
- files[lower]={ paths,path }
- else
- paths[#paths+1]=path
- end
- end
- else
- files[lower]=path
- if name~=lower then
- local rl=remap[lower]
- if not rl then
- remap[lower]=name
- r=r+1
- elseif trace_globbing and rl~=name then
- report_globbing("confusing filename, name: %a, lower: %a, already: %a",name,lower,rl)
- end
- end
- end
- end
- end
- if nofdirs>0 then
- sort(dirlist)
- for i=1,nofdirs do
- files,remap,n,m,r=scan(files,remap,spec,dirlist[i],n,m,r,onlyonce,tolerant)
- end
- end
- scancache[sub(full,1,-2)]=files
- return files,remap,n,m,r
-end
-local function scanfiles(path,branch,usecache,onlyonce,tolerant)
- local realpath=resolveprefix(path)
- if usecache then
- local content=fullcache[realpath]
- if content then
- if trace_locating then
- report_expansions("using cached scan of path %a, branch %a",path,branch or path)
- end
- nofsharedscans=nofsharedscans+1
- return content
- end
- end
- statistics.starttiming(timer)
- if trace_locating then
- report_expansions("scanning path %a, branch %a",path,branch or path)
- end
- local content
- if isdir(realpath) then
- local files,remap,n,m,r=scan({},{},realpath..'/',"",0,0,0,onlyonce,tolerant)
- content={
- metadata={
- path=path,
- files=n,
- directories=m,
- remappings=r,
- },
- files=files,
- remap=remap,
- }
- if trace_locating then
- report_expansions("%s files found on %s directories with %s uppercase remappings",n,m,r)
- end
- else
- content={
- metadata={
- path=path,
- files=0,
- directories=0,
- remappings=0,
- },
- files={},
- remap={},
- }
- if trace_locating then
- report_expansions("invalid path %a",realpath)
- end
- end
- if usecache then
- scanned[#scanned+1]=realpath
- fullcache[realpath]=content
- end
- nofscans=nofscans+1
- statistics.stoptiming(timer)
- return content
-end
-resolvers.scanfiles=scanfiles
-function resolvers.simplescanfiles(path,branch,usecache)
- return scanfiles(path,branch,usecache,true,true)
-end
-function resolvers.scandata()
- table.sort(scanned)
- return {
- n=nofscans,
- shared=nofsharedscans,
- time=statistics.elapsedtime(timer),
- paths=scanned,
- }
-end
-function resolvers.get_from_content(content,path,name)
- if not content then
- return
- end
- local files=content.files
- if not files then
- return
- end
- local remap=content.remap
- if not remap then
- return
- end
- if name then
- local used=lower(name)
- return path,remap[used] or used
- else
- local name=path
- local used=lower(name)
- local path=files[used]
- if path then
- return path,remap[used] or used
- end
- end
-end
-local nothing=function() end
-function resolvers.filtered_from_content(content,pattern)
- if content and type(pattern)=="string" then
- local pattern=lower(pattern)
- local files=content.files
- local remap=content.remap
- if files and remap then
- local f=sortedkeys(files)
- local n=#f
- local i=0
- local function iterator()
- while i<n do
- i=i+1
- local k=f[i]
- if find(k,pattern) then
- return files[k],remap and remap[k] or k
- end
- end
- end
- return iterator
- end
- end
- return nothing
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-env"] = package.loaded["data-env"] or true
-
--- original size: 9501, stripped down to: 6411
-
-if not modules then modules={} end modules ['data-env']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local lower,gsub=string.lower,string.gsub
-local next,rawget=next,rawget
-local resolvers=resolvers
-local allocate=utilities.storage.allocate
-local setmetatableindex=table.setmetatableindex
-local suffixonly=file.suffixonly
-local formats=allocate()
-local suffixes=allocate()
-local dangerous=allocate()
-local suffixmap=allocate()
-local usertypes=allocate()
-resolvers.formats=formats
-resolvers.suffixes=suffixes
-resolvers.dangerous=dangerous
-resolvers.suffixmap=suffixmap
-resolvers.usertypes=usertypes
-local luasuffixes=utilities.lua.suffixes
-local relations=allocate {
- core={
- ofm={
- names={ "ofm","omega font metric","omega font metrics" },
- variable='OFMFONTS',
- suffixes={ 'ofm','tfm' },
- },
- ovf={
- names={ "ovf","omega virtual font","omega virtual fonts" },
- variable='OVFFONTS',
- suffixes={ 'ovf','vf' },
- },
- tfm={
- names={ "tfm","tex font metric","tex font metrics" },
- variable='TFMFONTS',
- suffixes={ 'tfm' },
- },
- vf={
- names={ "vf","virtual font","virtual fonts" },
- variable='VFFONTS',
- suffixes={ 'vf' },
- },
- otf={
- names={ "otf","opentype","opentype font","opentype fonts"},
- variable='OPENTYPEFONTS',
- suffixes={ 'otf' },
- },
- ttf={
- names={ "ttf","truetype","truetype font","truetype fonts","truetype collection","truetype collections","truetype dictionary","truetype dictionaries" },
- variable='TTFONTS',
- suffixes={ 'ttf','ttc','dfont' },
- },
- afm={
- names={ "afm","adobe font metric","adobe font metrics" },
- variable="AFMFONTS",
- suffixes={ "afm" },
- },
- pfb={
- names={ "pfb","type1","type 1","type1 font","type 1 font","type1 fonts","type 1 fonts" },
- variable='T1FONTS',
- suffixes={ 'pfb','pfa' },
- },
- fea={
- names={ "fea","font feature","font features","font feature file","font feature files" },
- variable='FONTFEATURES',
- suffixes={ 'fea' },
- },
- cid={
- names={ "cid","cid map","cid maps","cid file","cid files" },
- variable='FONTCIDMAPS',
- suffixes={ 'cid','cidmap' },
- },
- fmt={
- names={ "fmt","format","tex format" },
- variable='TEXFORMATS',
- suffixes={ 'fmt' },
- },
- mem={
- names={ 'mem',"metapost format" },
- variable='MPMEMS',
- suffixes={ 'mem' },
- },
- mp={
- names={ "mp" },
- variable='MPINPUTS',
- suffixes=CONTEXTLMTXMODE>0
- and { 'mp','mpxl','mpvi','mpiv','mpii' }
- or { 'mp','mpvi','mpiv','mpii' },
- usertype=true,
- },
- tex={
- names={ "tex" },
- variable='TEXINPUTS',
- suffixes={ "tex","mkiv","mkvi","mkxl","mklx","mkii","cld","lfg","xml" },
- usertype=true,
- },
- icc={
- names={ "icc","icc profile","icc profiles" },
- variable='ICCPROFILES',
- suffixes={ 'icc' },
- },
- texmfscripts={
- names={ "texmfscript","texmfscripts","script","scripts" },
- variable='TEXMFSCRIPTS',
- suffixes={ 'lua','rb','pl','py' },
- },
- lua={
- names={ "lua" },
- variable='LUAINPUTS',
- suffixes={ luasuffixes.lua,luasuffixes.luc,luasuffixes.tma,luasuffixes.tmc },
- usertype=true,
- },
- lib={
- names={ "lib" },
- variable='CLUAINPUTS',
- suffixes=os.libsuffix and { os.libsuffix } or { 'dll','so' },
- },
- bib={
- names={ 'bib' },
- variable='BIBINPUTS',
- suffixes={ 'bib' },
- usertype=true,
- },
- bst={
- names={ 'bst' },
- variable='BSTINPUTS',
- suffixes={ 'bst' },
- usertype=true,
- },
- fontconfig={
- names={ 'fontconfig','fontconfig file','fontconfig files' },
- variable='FONTCONFIG_PATH',
- },
- pk={
- names={ "pk" },
- variable='PKFONTS',
- suffixes={ 'pk' },
- },
- },
- obsolete={
- enc={
- names={ "enc","enc files","enc file","encoding files","encoding file" },
- variable='ENCFONTS',
- suffixes={ 'enc' },
- },
- map={
- names={ "map","map files","map file" },
- variable='TEXFONTMAPS',
- suffixes={ 'map' },
- },
- lig={
- names={ "lig files","lig file","ligature file","ligature files" },
- variable='LIGFONTS',
- suffixes={ 'lig' },
- },
- opl={
- names={ "opl" },
- variable='OPLFONTS',
- suffixes={ 'opl' },
- },
- ovp={
- names={ "ovp" },
- variable='OVPFONTS',
- suffixes={ 'ovp' },
- },
- },
- kpse={
- base={
- names={ 'base',"metafont format" },
- variable='MFBASES',
- suffixes={ 'base','bas' },
- },
- cmap={
- names={ 'cmap','cmap files','cmap file' },
- variable='CMAPFONTS',
- suffixes={ 'cmap' },
- },
- cnf={
- names={ 'cnf' },
- suffixes={ 'cnf' },
- },
- web={
- names={ 'web' },
- suffixes={ 'web','ch' }
- },
- cweb={
- names={ 'cweb' },
- suffixes={ 'w','web','ch' },
- },
- gf={
- names={ 'gf' },
- suffixes={ '<resolution>gf' },
- },
- mf={
- names={ 'mf' },
- variable='MFINPUTS',
- suffixes={ 'mf' },
- },
- mft={
- names={ 'mft' },
- suffixes={ 'mft' },
- },
- pk={
- names={ 'pk' },
- suffixes={ '<resolution>pk' },
- },
- },
-}
-resolvers.relations=relations
-function resolvers.updaterelations()
- for category,categories in next,relations do
- for name,relation in next,categories do
- local rn=relation.names
- local rv=relation.variable
- if rn and rv then
- local rs=relation.suffixes
- local ru=relation.usertype
- for i=1,#rn do
- local rni=lower(gsub(rn[i]," ",""))
- formats[rni]=rv
- if rs then
- suffixes[rni]=rs
- for i=1,#rs do
- local rsi=rs[i]
- suffixmap[rsi]=rni
- end
- end
- end
- if ru then
- usertypes[name]=true
- end
- end
- end
- end
-end
-resolvers.updaterelations()
-local function simplified(t,k)
- return k and rawget(t,lower(gsub(k," ",""))) or nil
-end
-setmetatableindex(formats,simplified)
-setmetatableindex(suffixes,simplified)
-setmetatableindex(suffixmap,simplified)
-function resolvers.suffixofformat(str)
- local s=suffixes[str]
- return s and s[1] or ""
-end
-function resolvers.suffixofformat(str)
- return suffixes[str] or {}
-end
-for name,format in next,formats do
- dangerous[name]=true
-end
-dangerous.tex=nil
-function resolvers.formatofvariable(str)
- return formats[str] or ''
-end
-function resolvers.formatofsuffix(str)
- return suffixmap[suffixonly(str)] or 'tex'
-end
-function resolvers.variableofformat(str)
- return formats[str] or ''
-end
-function resolvers.variableofformatorsuffix(str)
- local v=formats[str]
- if v then
- return v
- end
- v=suffixmap[suffixonly(str)]
- if v then
- return formats[v]
- end
- return ''
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-tmp"] = package.loaded["data-tmp"] or true
-
--- original size: 16409, stripped down to: 11591
-
-if not modules then modules={} end modules ['data-tmp']={
- version=1.100,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local next,type=next,type
-local pcall,loadfile,collectgarbage=pcall,loadfile,collectgarbage
-local format,lower,gsub=string.format,string.lower,string.gsub
-local concat,serialize,fastserialize,serializetofile=table.concat,table.serialize,table.fastserialize,table.tofile
-local mkdirs,expanddirname,isdir,isfile=dir.mkdirs,dir.expandname,lfs.isdir,lfs.isfile
-local is_writable,is_readable=file.is_writable,file.is_readable
-local collapsepath,joinfile,addsuffix,dirname=file.collapsepath,file.join,file.addsuffix,file.dirname
-local savedata=file.savedata
-local formatters=string.formatters
-local osexit,osdate,osuuid=os.exit,os.date,os.uuid
-local removefile=os.remove
-local md5hex=md5.hex
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local trace_cache=false trackers.register("resolvers.cache",function(v) trace_cache=v end)
-local report_caches=logs.reporter("resolvers","caches")
-local report_resolvers=logs.reporter("resolvers","caching")
-local resolvers=resolvers
-local cleanpath=resolvers.cleanpath
-local resolvepath=resolvers.resolve
-local luautilities=utilities.lua
-do
- local directive_cleanup=false directives.register("system.compile.cleanup",function(v) directive_cleanup=v end)
- local directive_strip=false directives.register("system.compile.strip",function(v) directive_strip=v end)
- local compilelua=luautilities.compile
- function luautilities.compile(luafile,lucfile,cleanup,strip)
- if cleanup==nil then cleanup=directive_cleanup end
- if strip==nil then strip=directive_strip end
- return compilelua(luafile,lucfile,cleanup,strip)
- end
-end
-caches=caches or {}
-local caches=caches
-local writable=nil
-local readables={}
-local usedreadables={}
-local compilelua=luautilities.compile
-local luasuffixes=luautilities.suffixes
-caches.base=caches.base or "luatex-cache"
-caches.more=caches.more or "context"
-caches.defaults={ "TMPDIR","TEMPDIR","TMP","TEMP","HOME","HOMEPATH" }
-local direct_cache=false
-local fast_cache=false
-local cache_tree=false
-directives.register("system.caches.direct",function(v) direct_cache=true end)
-directives.register("system.caches.fast",function(v) fast_cache=true end)
-local function configfiles()
- return concat(resolvers.configurationfiles(),";")
-end
-local function hashed(tree)
- tree=gsub(tree,"[\\/]+$","")
- tree=lower(tree)
- local hash=md5hex(tree)
- if trace_cache or trace_locating then
- report_caches("hashing tree %a, hash %a",tree,hash)
- end
- return hash
-end
-local function treehash()
- local tree=configfiles()
- if not tree or tree=="" then
- return false
- else
- return hashed(tree)
- end
-end
-caches.hashed=hashed
-caches.treehash=treehash
-caches.configfiles=configfiles
-local function identify()
- local texmfcaches=resolvers.cleanpathlist("TEXMFCACHE")
- if texmfcaches then
- for k=1,#texmfcaches do
- local cachepath=texmfcaches[k]
- if cachepath~="" then
- cachepath=resolvepath(cachepath)
- cachepath=cleanpath(cachepath)
- cachepath=collapsepath(cachepath)
- local valid=isdir(cachepath)
- if valid then
- if is_readable(cachepath) then
- readables[#readables+1]=cachepath
- if not writable and is_writable(cachepath) then
- writable=cachepath
- end
- end
- elseif not writable then
- local cacheparent=dirname(cachepath)
- if is_writable(cacheparent) then
- mkdirs(cachepath)
- if isdir(cachepath) and is_writable(cachepath) then
- report_caches("path %a created",cachepath)
- writable=cachepath
- readables[#readables+1]=cachepath
- end
- end
- end
- end
- end
- end
- local texmfcaches=caches.defaults
- if texmfcaches then
- for k=1,#texmfcaches do
- local cachepath=texmfcaches[k]
- cachepath=resolvers.expansion(cachepath)
- if cachepath~="" then
- cachepath=resolvepath(cachepath)
- cachepath=cleanpath(cachepath)
- local valid=isdir(cachepath)
- if valid and is_readable(cachepath) then
- if not writable and is_writable(cachepath) then
- readables[#readables+1]=cachepath
- writable=cachepath
- break
- end
- end
- end
- end
- end
- if not writable then
- report_caches("fatal error: there is no valid writable cache path defined")
- osexit()
- elseif #readables==0 then
- report_caches("fatal error: there is no valid readable cache path defined")
- osexit()
- end
- writable=expanddirname(cleanpath(writable))
- local base=caches.base
- local more=caches.more
- local tree=cache_tree or treehash()
- if tree then
- cache_tree=tree
- writable=mkdirs(writable,base,more,tree)
- for i=1,#readables do
- readables[i]=joinfile(readables[i],base,more,tree)
- end
- else
- writable=mkdirs(writable,base,more)
- for i=1,#readables do
- readables[i]=joinfile(readables[i],base,more)
- end
- end
- if trace_cache then
- for i=1,#readables do
- report_caches("using readable path %a (order %s)",readables[i],i)
- end
- report_caches("using writable path %a",writable)
- end
- identify=function()
- return writable,readables
- end
- return writable,readables
-end
-function caches.usedpaths(separator)
- local writable,readables=identify()
- if #readables>1 then
- local result={}
- local done={}
- for i=1,#readables do
- local readable=readables[i]
- if readable==writable then
- done[readable]=true
- result[#result+1]=formatters["readable+writable: %a"](readable)
- elseif usedreadables[i] then
- done[readable]=true
- result[#result+1]=formatters["readable: %a"](readable)
- end
- end
- if not done[writable] then
- result[#result+1]=formatters["writable: %a"](writable)
- end
- return concat(result,separator or " | ")
- else
- return writable or "?"
- end
-end
-local r_cache={}
-local w_cache={}
-local function getreadablepaths(...)
- local tags={... }
- local hash=concat(tags,"/")
- local done=r_cache[hash]
- if not done then
- local writable,readables=identify()
- if #tags>0 then
- done={}
- for i=1,#readables do
- done[i]=joinfile(readables[i],...)
- end
- else
- done=readables
- end
- r_cache[hash]=done
- end
- return done
-end
-local function getwritablepath(...)
- local tags={... }
- local hash=concat(tags,"/")
- local done=w_cache[hash]
- if not done then
- local writable,readables=identify()
- if #tags>0 then
- done=mkdirs(writable,...)
- else
- done=writable
- end
- w_cache[hash]=done
- end
- return done
-end
-local function setfirstwritablefile(filename,...)
- local wr=getwritablepath(...)
- local fullname=joinfile(wr,filename)
- return fullname,wr
-end
-local function setluanames(path,name)
- return
- format("%s/%s.%s",path,name,luasuffixes.tma),
- format("%s/%s.%s",path,name,luasuffixes.tmc)
-end
-local function getfirstreadablefile(filename,...)
- local fullname,path=setfirstwritablefile(filename,...)
- if is_readable(fullname) then
- return fullname,path
- end
- local rd=getreadablepaths(...)
- for i=1,#rd do
- local path=rd[i]
- local fullname=joinfile(path,filename)
- if is_readable(fullname) then
- usedreadables[i]=true
- return fullname,path
- end
- end
- return fullname,path
-end
-caches.getreadablepaths=getreadablepaths
-caches.getwritablepath=getwritablepath
-caches.setfirstwritablefile=setfirstwritablefile
-caches.getfirstreadablefile=getfirstreadablefile
-caches.setluanames=setluanames
-local checkmemory=utilities and utilities.lua and utilities.lua.checkmemory
-local threshold=100
-function caches.loaddata(readables,name,writable)
- local used=checkmemory and checkmemory()
- if type(readables)=="string" then
- readables={ readables }
- end
- for i=1,#readables do
- local path=readables[i]
- local loader=false
- local state=false
- local tmaname,tmcname=setluanames(path,name)
- if isfile(tmcname) then
- state,loader=pcall(loadfile,tmcname)
- end
- if not loader and isfile(tmaname) then
- local tmacrap,tmcname=setluanames(writable,name)
- if isfile(tmcname) then
- state,loader=pcall(loadfile,tmcname)
- end
- compilelua(tmaname,tmcname)
- if isfile(tmcname) then
- state,loader=pcall(loadfile,tmcname)
- end
- if not loader then
- state,loader=pcall(loadfile,tmaname)
- end
- end
- if loader then
- loader=loader()
- if checkmemory then
- checkmemory(used,threshold)
- else
- collectgarbage("step")
- end
- return loader
- end
- end
- return false
-end
-function caches.is_writable(filepath,filename)
- local tmaname,tmcname=setluanames(filepath,filename)
- return is_writable(tmaname)
-end
-local saveoptions={ compact=true,accurate=not JITSUPPORTED }
-function caches.savedata(filepath,filename,data,fast)
- local tmaname,tmcname=setluanames(filepath,filename)
- data.cache_uuid=osuuid()
- if fast or fast_cache then
- savedata(tmaname,fastserialize(data,true))
- elseif direct_cache then
- savedata(tmaname,serialize(data,true,saveoptions))
- else
- serializetofile(tmaname,data,true,saveoptions)
- end
- compilelua(tmaname,tmcname)
-end
-local content_state={}
-function caches.contentstate()
- return content_state or {}
-end
-function caches.loadcontent(cachename,dataname,filename)
- if not filename then
- local name=hashed(cachename)
- local full,path=getfirstreadablefile(addsuffix(name,luasuffixes.lua),"trees")
- filename=joinfile(path,name)
- end
- local state,blob=pcall(loadfile,addsuffix(filename,luasuffixes.luc))
- if not blob then
- state,blob=pcall(loadfile,addsuffix(filename,luasuffixes.lua))
- end
- if blob then
- local data=blob()
- if data and data.content then
- if data.type==dataname then
- if data.version==resolvers.cacheversion then
- content_state[#content_state+1]=data.uuid
- if trace_locating then
- report_resolvers("loading %a for %a from %a",dataname,cachename,filename)
- end
- return data.content
- else
- report_resolvers("skipping %a for %a from %a (version mismatch)",dataname,cachename,filename)
- end
- else
- report_resolvers("skipping %a for %a from %a (datatype mismatch)",dataname,cachename,filename)
- end
- elseif trace_locating then
- report_resolvers("skipping %a for %a from %a (no content)",dataname,cachename,filename)
- end
- elseif trace_locating then
- report_resolvers("skipping %a for %a from %a (invalid file)",dataname,cachename,filename)
- end
-end
-function caches.collapsecontent(content)
- for k,v in next,content do
- if type(v)=="table" and #v==1 then
- content[k]=v[1]
- end
- end
-end
-function caches.savecontent(cachename,dataname,content,filename)
- if not filename then
- local name=hashed(cachename)
- local full,path=setfirstwritablefile(addsuffix(name,luasuffixes.lua),"trees")
- filename=joinfile(path,name)
- end
- local luaname=addsuffix(filename,luasuffixes.lua)
- local lucname=addsuffix(filename,luasuffixes.luc)
- if trace_locating then
- report_resolvers("preparing %a for %a",dataname,cachename)
- end
- local data={
- type=dataname,
- root=cachename,
- version=resolvers.cacheversion,
- date=osdate("%Y-%m-%d"),
- time=osdate("%H:%M:%S"),
- content=content,
- uuid=osuuid(),
- }
- local ok=savedata(luaname,serialize(data,true))
- if ok then
- if trace_locating then
- report_resolvers("category %a, cachename %a saved in %a",dataname,cachename,luaname)
- end
- if compilelua(luaname,lucname) then
- if trace_locating then
- report_resolvers("%a compiled to %a",dataname,lucname)
- end
- return true
- else
- if trace_locating then
- report_resolvers("compiling failed for %a, deleting file %a",dataname,lucname)
- end
- removefile(lucname)
- end
- elseif trace_locating then
- report_resolvers("unable to save %a in %a (access error)",dataname,luaname)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-met"] = package.loaded["data-met"] or true
-
--- original size: 5518, stripped down to: 3854
-
-if not modules then modules={} end modules ['data-met']={
- version=1.100,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type=type
-local find=string.find
-local addurlscheme,urlhashed=url.addscheme,url.hashed
-local collapsepath,joinfile=file.collapsepath,file.join
-local report_methods=logs.reporter("resolvers","methods")
-local trace_locating=false
-local trace_methods=false
-trackers.register("resolvers.locating",function(v) trace_methods=v end)
-trackers.register("resolvers.methods",function(v) trace_methods=v end)
-local allocate=utilities.storage.allocate
-local resolvers=resolvers
-local registered={}
-local function splitmethod(filename)
- if not filename then
- return {
- scheme="unknown",
- original=filename,
- }
- end
- if type(filename)=="table" then
- return filename
- end
- filename=collapsepath(filename,".")
- if not find(filename,"://",1,true) then
- return {
- scheme="file",
- path=filename,
- original=filename,
- filename=filename,
- }
- end
- local specification=urlhashed(filename)
- if not specification.scheme or specification.scheme=="" then
- return {
- scheme="file",
- path=filename,
- original=filename,
- filename=filename,
- }
- else
- return specification
- end
-end
-resolvers.splitmethod=splitmethod
-local function methodhandler(what,first,...)
- local method=registered[what]
- if method then
- local how=method.how
- local namespace=method.namespace
- if how=="uri" or how=="url" then
- local specification=splitmethod(first)
- local scheme=specification.scheme
- local resolver=namespace and namespace[scheme]
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, handler %a, argument %a",what,how,scheme,first)
- end
- return resolver(specification,...)
- else
- resolver=namespace.default or namespace.file
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, handler %a, argument %a",what,how,"default",first)
- end
- return resolver(specification,...)
- elseif trace_methods then
- report_methods("resolving, method %a, how %a, handler %a, argument %a",what,how,"unset")
- end
- end
- elseif how=="tag" then
- local resolver=namespace and namespace[first]
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, tag %a",what,how,first)
- end
- return resolver(...)
- else
- resolver=namespace.default or namespace.file
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, tag %a",what,how,"default")
- end
- return resolver(...)
- elseif trace_methods then
- report_methods("resolving, method %a, how %a, tag %a",what,how,"unset")
- end
- end
- end
- else
- report_methods("resolving, invalid method %a")
- end
-end
-resolvers.methodhandler=methodhandler
-function resolvers.registermethod(name,namespace,how)
- registered[name]={
- how=how or "tag",
- namespace=namespace
- }
- namespace["byscheme"]=function(scheme,filename,...)
- if scheme=="file" then
- return methodhandler(name,filename,...)
- else
- return methodhandler(name,addurlscheme(filename,scheme),...)
- end
- end
-end
-local concatinators=allocate { notfound=joinfile }
-local locators=allocate { notfound=function() end }
-local hashers=allocate { notfound=function() end }
-local generators=allocate { notfound=function() end }
-resolvers.concatinators=concatinators
-resolvers.locators=locators
-resolvers.hashers=hashers
-resolvers.generators=generators
-local registermethod=resolvers.registermethod
-registermethod("concatinators",concatinators,"tag")
-registermethod("locators",locators,"uri")
-registermethod("hashers",hashers,"uri")
-registermethod("generators",generators,"uri")
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-res"] = package.loaded["data-res"] or true
-
--- original size: 69576, stripped down to: 44470
-
-if not modules then modules={} end modules ['data-res']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local gsub,find,lower,upper,match,gmatch=string.gsub,string.find,string.lower,string.upper,string.match,string.gmatch
-local concat,insert,remove=table.concat,table.insert,table.remove
-local next,type,rawget,loadfile=next,type,rawget,loadfile
-local mergedtable=table.merged
-local os=os
-local P,S,R,C,Cc,Cs,Ct,Carg=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.Cc,lpeg.Cs,lpeg.Ct,lpeg.Carg
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local formatters=string.formatters
-local filedirname=file.dirname
-local filebasename=file.basename
-local suffixonly=file.suffixonly
-local addsuffix=file.addsuffix
-local removesuffix=file.removesuffix
-local filejoin=file.join
-local collapsepath=file.collapsepath
-local joinpath=file.joinpath
-local is_qualified_path=file.is_qualified_path
-local allocate=utilities.storage.allocate
-local settings_to_array=utilities.parsers.settings_to_array
-local urlhasscheme=url.hasscheme
-local getcurrentdir=lfs.currentdir
-local isfile=lfs.isfile
-local isdir=lfs.isdir
-local setmetatableindex=table.setmetatableindex
-local luasuffixes=utilities.lua.suffixes
-local trace_locating=false trackers .register("resolvers.locating",function(v) trace_locating=v end)
-local trace_details=false trackers .register("resolvers.details",function(v) trace_details=v end)
-local trace_expansions=false trackers .register("resolvers.expansions",function(v) trace_expansions=v end)
-local trace_paths=false trackers .register("resolvers.paths",function(v) trace_paths=v end)
-local resolve_otherwise=true directives.register("resolvers.otherwise",function(v) resolve_otherwise=v end)
-local report_resolving=logs.reporter("resolvers","resolving")
-local resolvers=resolvers
-local expandedpathfromlist=resolvers.expandedpathfromlist
-local checkedvariable=resolvers.checkedvariable
-local splitconfigurationpath=resolvers.splitconfigurationpath
-local methodhandler=resolvers.methodhandler
-local filtered=resolvers.filtered_from_content
-local lookup=resolvers.get_from_content
-local cleanpath=resolvers.cleanpath
-local resolveprefix=resolvers.resolve
-local initializesetter=utilities.setters.initialize
-local ostype,osname,osenv,ossetenv,osgetenv=os.type,os.name,os.env,os.setenv,os.getenv
-resolvers.cacheversion="1.100"
-resolvers.configbanner=""
-resolvers.homedir=environment.homedir
-resolvers.luacnfname="texmfcnf.lua"
-resolvers.luacnffallback="contextcnf.lua"
-resolvers.luacnfstate="unknown"
-local criticalvars={
- "SELFAUTOLOC",
- "SELFAUTODIR",
- "SELFAUTOPARENT",
- "TEXMFCNF",
- "TEXMF",
- "TEXOS",
-}
-if environment.default_texmfcnf then
- resolvers.luacnfspec="home:texmf/web2c;"..environment.default_texmfcnf
-else
- resolvers.luacnfspec=concat ({
- "home:texmf/web2c",
- "selfautoparent:/texmf-local/web2c",
- "selfautoparent:/texmf-context/web2c",
- "selfautoparent:/texmf-dist/web2c",
- "selfautoparent:/texmf/web2c",
- },";")
-end
-local unset_variable="unset"
-local formats=resolvers.formats
-local suffixes=resolvers.suffixes
-local usertypes=resolvers.usertypes
-local dangerous=resolvers.dangerous
-local suffixmap=resolvers.suffixmap
-resolvers.defaultsuffixes={ "tex" }
-local instance=nil
-local variable
-local expansion
-local setenv
-local getenv
-local formatofsuffix=resolvers.formatofsuffix
-local splitpath=resolvers.splitpath
-local splitmethod=resolvers.splitmethod
-setenv=function(key,value,raw)
- if instance then
- instance.environment[key]=value
- ossetenv(key,raw and value or resolveprefix(value))
- end
-end
-getenv=function(key)
- local value=rawget(instance.environment,key)
- if value and value~="" then
- return value
- else
- local e=osgetenv(key)
- return e~=nil and e~="" and checkedvariable(e) or ""
- end
-end
-resolvers.getenv=getenv
-resolvers.setenv=setenv
-local dollarstripper=lpeg.stripper("$")
-local inhibitstripper=P("!")^0*Cs(P(1)^0)
-local expandedvariable,resolvedvariable do
- local function resolveinstancevariable(k)
- return instance.expansions[k]
- end
- local p_variable=P("$")/""
- local p_key=C(R("az","AZ","09","__","--")^1)
- local p_whatever=P(";")*((1-S("!{}/\\"))^1*P(";")/"")+P(";")*(P(";")/"")+P(1)
- local variableexpander=Cs((p_variable*(p_key/resolveinstancevariable)+p_whatever)^1 )
- local p_cleaner=P("\\")/"/"+P(";")*S("!{}/\\")^0*P(";")^1/";"
- local variablecleaner=Cs((p_cleaner+P(1))^0)
- local p_variable=R("az","AZ","09","__","--")^1/resolveinstancevariable
- local p_variable=(P("$")/"")*(p_variable+(P("{")/"")*p_variable*(P("}")/""))
- local variableresolver=Cs((p_variable+P(1))^0)
- expandedvariable=function(var)
- return lpegmatch(variableexpander,var) or var
- end
- function resolvers.reset()
- if trace_locating then
- report_resolving("creating instance")
- end
- local environment={}
- local variables={}
- local expansions={}
- local order={}
- instance={
- environment=environment,
- variables=variables,
- expansions=expansions,
- order=order,
- files={},
- setups={},
- found={},
- foundintrees={},
- hashes={},
- hashed={},
- pathlists=false,
- specification={},
- lists={},
- data={},
- fakepaths={},
- remember=true,
- diskcache=true,
- renewcache=false,
- renewtree=false,
- loaderror=false,
- savelists=true,
- pattern=nil,
- force_suffixes=true,
- pathstack={},
- }
- setmetatableindex(variables,function(t,k)
- local v
- for i=1,#order do
- v=order[i][k]
- if v~=nil then
- t[k]=v
- return v
- end
- end
- if v==nil then
- v=""
- end
- t[k]=v
- return v
- end)
- local repath=resolvers.repath
- setmetatableindex(environment,function(t,k)
- local v=osgetenv(k)
- if v==nil then
- v=variables[k]
- end
- if v~=nil then
- v=checkedvariable(v) or ""
- end
- v=repath(v)
- t[k]=v
- return v
- end)
- setmetatableindex(expansions,function(t,k)
- local v=environment[k]
- if type(v)=="string" then
- v=lpegmatch(variableresolver,v)
- v=lpegmatch(variablecleaner,v)
- end
- t[k]=v
- return v
- end)
- end
-end
-function resolvers.initialized()
- return instance~=nil
-end
-local function reset_hashes()
- instance.lists={}
- instance.pathlists=false
- instance.found={}
-end
-local function reset_caches()
- instance.lists={}
- instance.pathlists=false
-end
-local makepathexpression do
- local slash=P("/")
- local pathexpressionpattern=Cs (
- Cc("^")*(
- Cc("%")*S(".-")+slash^2*P(-1)/"/.*"
-+slash^2/"/"+(1-slash)*P(-1)*Cc("/")+P(1)
- )^1*Cc("$")
- )
- local cache={}
- makepathexpression=function(str)
- if str=="." then
- return "^%./$"
- else
- local c=cache[str]
- if not c then
- c=lpegmatch(pathexpressionpattern,str)
- cache[str]=c
- end
- return c
- end
- end
-end
-local function reportcriticalvariables(cnfspec)
- if trace_locating then
- for i=1,#criticalvars do
- local k=criticalvars[i]
- local v=getenv(k) or "unknown"
- report_resolving("variable %a set to %a",k,v)
- end
- report_resolving()
- if cnfspec then
- report_resolving("using configuration specification %a",type(cnfspec)=="table" and concat(cnfspec,",") or cnfspec)
- end
- report_resolving()
- end
- reportcriticalvariables=function() end
-end
-local function identify_configuration_files()
- local specification=instance.specification
- if #specification==0 then
- local cnfspec=getenv("TEXMFCNF")
- if cnfspec=="" then
- cnfspec=resolvers.luacnfspec
- resolvers.luacnfstate="default"
- else
- resolvers.luacnfstate="environment"
- end
- reportcriticalvariables(cnfspec)
- local cnfpaths=expandedpathfromlist(splitpath(cnfspec))
- local function locatecnf(luacnfname,kind)
- for i=1,#cnfpaths do
- local filepath=cnfpaths[i]
- local filename=collapsepath(filejoin(filepath,luacnfname))
- local realname=resolveprefix(filename)
- if trace_locating then
- local fullpath=gsub(resolveprefix(collapsepath(filepath)),"//","/")
- local weirdpath=find(fullpath,"/texmf.+/texmf") or not find(fullpath,"/web2c",1,true)
- report_resolving("looking for %s %a on %s path %a from specification %a",
- kind,luacnfname,weirdpath and "weird" or "given",fullpath,filepath)
- end
- if isfile(realname) then
- specification[#specification+1]=filename
- if trace_locating then
- report_resolving("found %s configuration file %a",kind,realname)
- end
- end
- end
- end
- locatecnf(resolvers.luacnfname,"regular")
- if #specification==0 then
- locatecnf(resolvers.luacnffallback,"fallback")
- end
- if trace_locating then
- report_resolving()
- end
- elseif trace_locating then
- report_resolving("configuration files already identified")
- end
-end
-local function load_configuration_files()
- local specification=instance.specification
- local setups=instance.setups
- local order=instance.order
- if #specification>0 then
- local luacnfname=resolvers.luacnfname
- for i=1,#specification do
- local filename=specification[i]
- local pathname=filedirname(filename)
- local filename=filejoin(pathname,luacnfname)
- local realname=resolveprefix(filename)
- local blob=loadfile(realname)
- if blob then
- local data=blob()
- local parent=data and data.parent
- if parent then
- local filename=filejoin(pathname,parent)
- local realname=resolveprefix(filename)
- local blob=loadfile(realname)
- if blob then
- local parentdata=blob()
- if parentdata then
- report_resolving("loading configuration file %a",filename)
- data=mergedtable(parentdata,data)
- end
- end
- end
- data=data and data.content
- if data then
- if trace_locating then
- report_resolving("loading configuration file %a",filename)
- report_resolving()
- end
- local variables=data.variables or {}
- local warning=false
- for k,v in next,data do
- local variant=type(v)
- if variant=="table" then
- initializesetter(filename,k,v)
- elseif variables[k]==nil then
- if trace_locating and not warning then
- report_resolving("variables like %a in configuration file %a should move to the 'variables' subtable",
- k,resolveprefix(filename))
- warning=true
- end
- variables[k]=v
- end
- end
- setups[pathname]=variables
- if resolvers.luacnfstate=="default" then
- local cnfspec=variables["TEXMFCNF"]
- if cnfspec then
- if trace_locating then
- report_resolving("reloading configuration due to TEXMF redefinition")
- end
- setenv("TEXMFCNF",cnfspec)
- instance.specification={}
- identify_configuration_files()
- load_configuration_files()
- resolvers.luacnfstate="configuration"
- break
- end
- end
- else
- if trace_locating then
- report_resolving("skipping configuration file %a (no content)",filename)
- end
- setups[pathname]={}
- instance.loaderror=true
- end
- elseif trace_locating then
- report_resolving("skipping configuration file %a (no valid format)",filename)
- end
- order[#order+1]=setups[pathname]
- if instance.loaderror then
- break
- end
- end
- elseif trace_locating then
- report_resolving("warning: no lua configuration files found")
- end
-end
-local expandedpathlist
-local unexpandedpathlist
-function resolvers.configurationfiles()
- return instance.specification or {}
-end
-local function load_file_databases()
- instance.loaderror=false
- instance.files={}
- if not instance.renewcache then
- local hashes=instance.hashes
- for k=1,#hashes do
- local hash=hashes[k]
- resolvers.hashers.byscheme(hash.type,hash.name)
- if instance.loaderror then break end
- end
- end
-end
-local function locate_file_databases()
- local texmfpaths=expandedpathlist("TEXMF")
- if #texmfpaths>0 then
- for i=1,#texmfpaths do
- local path=collapsepath(texmfpaths[i])
- path=gsub(path,"/+$","")
- local stripped=lpegmatch(inhibitstripper,path)
- if stripped~="" then
- local runtime=stripped==path
- path=cleanpath(path)
- local spec=splitmethod(stripped)
- if runtime and (spec.noscheme or spec.scheme=="file") then
- stripped="tree:///"..stripped
- elseif spec.scheme=="cache" or spec.scheme=="file" then
- stripped=spec.path
- end
- if trace_locating then
- if runtime then
- report_resolving("locating list of %a (runtime) (%s)",path,stripped)
- else
- report_resolving("locating list of %a (cached)",path)
- end
- end
- methodhandler('locators',stripped)
- end
- end
- if trace_locating then
- report_resolving()
- end
- elseif trace_locating then
- report_resolving("no texmf paths are defined (using TEXMF)")
- end
-end
-local function generate_file_databases()
- local hashes=instance.hashes
- for k=1,#hashes do
- local hash=hashes[k]
- methodhandler('generators',hash.name)
- end
- if trace_locating then
- report_resolving()
- end
-end
-local function save_file_databases()
- local hashes=instance.hashes
- local files=instance.files
- for i=1,#hashes do
- local hash=hashes[i]
- local cachename=hash.name
- if hash.cache then
- local content=files[cachename]
- caches.collapsecontent(content)
- if trace_locating then
- report_resolving("saving tree %a",cachename)
- end
- caches.savecontent(cachename,"files",content)
- elseif trace_locating then
- report_resolving("not saving runtime tree %a",cachename)
- end
- end
-end
-function resolvers.renew(hashname)
- local files=instance.files
- if hashname and hashname~="" then
- local expanded=expansion(hashname) or ""
- if expanded~="" then
- if trace_locating then
- report_resolving("identifying tree %a from %a",expanded,hashname)
- end
- hashname=expanded
- else
- if trace_locating then
- report_resolving("identifying tree %a",hashname)
- end
- end
- local realpath=resolveprefix(hashname)
- if isdir(realpath) then
- if trace_locating then
- report_resolving("using path %a",realpath)
- end
- methodhandler('generators',hashname)
- local content=files[hashname]
- caches.collapsecontent(content)
- if trace_locating then
- report_resolving("saving tree %a",hashname)
- end
- caches.savecontent(hashname,"files",content)
- else
- report_resolving("invalid path %a",realpath)
- end
- end
-end
-local function load_databases()
- locate_file_databases()
- if instance.diskcache and not instance.renewcache then
- load_file_databases()
- if instance.loaderror then
- generate_file_databases()
- save_file_databases()
- end
- else
- generate_file_databases()
- if instance.renewcache then
- save_file_databases()
- end
- end
-end
-function resolvers.appendhash(type,name,cache)
- local hashed=instance.hashed
- local hashes=instance.hashes
- if hashed[name] then
- else
- if trace_locating then
- report_resolving("hash %a appended",name)
- end
- insert(hashes,{ type=type,name=name,cache=cache } )
- hashed[name]=cache
- end
-end
-function resolvers.prependhash(type,name,cache)
- local hashed=instance.hashed
- local hashes=instance.hashes
- if hashed[name] then
- else
- if trace_locating then
- report_resolving("hash %a prepended",name)
- end
- insert(hashes,1,{ type=type,name=name,cache=cache } )
- hashed[name]=cache
- end
-end
-function resolvers.extendtexmfvariable(specification)
- local environment=instance.environment
- local variables=instance.variables
- local texmftrees=splitpath(getenv("TEXMF"))
- insert(texmftrees,1,specification)
- texmftrees=concat(texmftrees,",")
- if environment["TEXMF"] then
- environment["TEXMF"]=texmftrees
- elseif variables["TEXMF"] then
- variables["TEXMF"]=texmftrees
- else
- end
- reset_hashes()
-end
-function resolvers.splitexpansions()
- local expansions=instance.expansions
- for k,v in next,expansions do
- local t,tn,h,p={},0,{},splitconfigurationpath(v)
- for kk=1,#p do
- local vv=p[kk]
- if vv~="" and not h[vv] then
- tn=tn+1
- t[tn]=vv
- h[vv]=true
- end
- end
- if tn>1 then
- expansions[k]=t
- else
- expansions[k]=t[1]
- end
- end
-end
-function resolvers.datastate()
- return caches.contentstate()
-end
-variable=function(name)
- local variables=instance.variables
- local name=name and lpegmatch(dollarstripper,name)
- local result=name and variables[name]
- return result~=nil and result or ""
-end
-expansion=function(name)
- local expansions=instance.expansions
- local name=name and lpegmatch(dollarstripper,name)
- local result=name and expansions[name]
- return result~=nil and result or ""
-end
-resolvers.variable=variable
-resolvers.expansion=expansion
-unexpandedpathlist=function(str)
- local pth=variable(str)
- local lst=splitpath(pth)
- return expandedpathfromlist(lst)
-end
-function resolvers.unexpandedpath(str)
- return joinpath(unexpandedpathlist(str))
-end
-function resolvers.pushpath(name)
- local pathstack=instance.pathstack
- local lastpath=pathstack[#pathstack]
- local pluspath=filedirname(name)
- if lastpath then
- lastpath=collapsepath(filejoin(lastpath,pluspath))
- else
- lastpath=collapsepath(pluspath)
- end
- insert(pathstack,lastpath)
- if trace_paths then
- report_resolving("pushing path %a",lastpath)
- end
-end
-function resolvers.poppath()
- local pathstack=instance.pathstack
- if trace_paths and #pathstack>0 then
- report_resolving("popping path %a",pathstack[#pathstack])
- end
- remove(pathstack)
-end
-function resolvers.stackpath()
- local pathstack=instance.pathstack
- local currentpath=pathstack[#pathstack]
- return currentpath~="" and currentpath or nil
-end
-local done={}
-function resolvers.resetextrapaths()
- local extra_paths=instance.extra_paths
- if not extra_paths then
- done={}
- instance.extra_paths={}
- elseif #ep>0 then
- done={}
- reset_caches()
- end
-end
-function resolvers.getextrapaths()
- return instance.extra_paths or {}
-end
-function resolvers.registerextrapath(paths,subpaths)
- if not subpaths or subpaths=="" then
- if not paths or path=="" then
- return
- elseif done[paths] then
- return
- end
- end
- local paths=settings_to_array(paths)
- local subpaths=settings_to_array(subpaths)
- local extra_paths=instance.extra_paths or {}
- local oldn=#extra_paths
- local newn=oldn
- local nofpaths=#paths
- local nofsubpaths=#subpaths
- if nofpaths>0 then
- if nofsubpaths>0 then
- for i=1,nofpaths do
- local p=paths[i]
- for j=1,nofsubpaths do
- local s=subpaths[j]
- local ps=p.."/"..s
- if not done[ps] then
- newn=newn+1
- extra_paths[newn]=cleanpath(ps)
- done[ps]=true
- end
- end
- end
- else
- for i=1,nofpaths do
- local p=paths[i]
- if not done[p] then
- newn=newn+1
- extra_paths[newn]=cleanpath(p)
- done[p]=true
- end
- end
- end
- elseif nofsubpaths>0 then
- for i=1,oldn do
- for j=1,nofsubpaths do
- local s=subpaths[j]
- local ps=extra_paths[i].."/"..s
- if not done[ps] then
- newn=newn+1
- extra_paths[newn]=cleanpath(ps)
- done[ps]=true
- end
- end
- end
- end
- if newn>0 then
- instance.extra_paths=extra_paths
- end
- if newn~=oldn then
- reset_caches()
- end
-end
-function resolvers.pushextrapath(path)
- local paths=settings_to_array(path)
- local extra_stack=instance.extra_stack
- if extra_stack then
- insert(extra_stack,1,paths)
- else
- instance.extra_stack={ paths }
- end
- reset_caches()
-end
-function resolvers.popextrapath()
- local extra_stack=instance.extra_stack
- if extra_stack then
- reset_caches()
- return remove(extra_stack,1)
- end
-end
-local function made_list(instance,list,extra_too)
- local done={}
- local new={}
- local newn=0
- local function add(p)
- for k=1,#p do
- local v=p[k]
- if not done[v] then
- done[v]=true
- newn=newn+1
- new[newn]=v
- end
- end
- end
- for k=1,#list do
- local v=list[k]
- if done[v] then
- elseif find(v,"^[%.%/]$") then
- done[v]=true
- newn=newn+1
- new[newn]=v
- else
- break
- end
- end
- if extra_too then
- local extra_stack=instance.extra_stack
- local extra_paths=instance.extra_paths
- if extra_stack and #extra_stack>0 then
- for k=1,#extra_stack do
- add(extra_stack[k])
- end
- end
- if extra_paths and #extra_paths>0 then
- add(extra_paths)
- end
- end
- add(list)
- return new
-end
-expandedpathlist=function(str,extra_too)
- if not str then
- return {}
- elseif instance.savelists then
- str=lpegmatch(dollarstripper,str)
- local lists=instance.lists
- local lst=lists[str]
- if not lst then
- local l=made_list(instance,splitpath(expansion(str)),extra_too)
- lst=expandedpathfromlist(l)
- lists[str]=lst
- end
- return lst
- else
- local lst=splitpath(expansion(str))
- return made_list(instance,expandedpathfromlist(lst),extra_too)
- end
-end
-resolvers.expandedpathlist=expandedpathlist
-resolvers.unexpandedpathlist=unexpandedpathlist
-function resolvers.cleanpathlist(str)
- local t=expandedpathlist(str)
- if t then
- for i=1,#t do
- t[i]=collapsepath(cleanpath(t[i]))
- end
- end
- return t
-end
-function resolvers.expandpath(str)
- return joinpath(expandedpathlist(str))
-end
-local function expandedpathlistfromvariable(str)
- str=lpegmatch(dollarstripper,str)
- local tmp=resolvers.variableofformatorsuffix(str)
- return expandedpathlist(tmp~="" and tmp or str)
-end
-function resolvers.expandpathfromvariable(str)
- return joinpath(expandedpathlistfromvariable(str))
-end
-resolvers.expandedpathlistfromvariable=expandedpathlistfromvariable
-function resolvers.cleanedpathlist(v)
- local t=expandedpathlist(v)
- for i=1,#t do
- t[i]=resolveprefix(cleanpath(t[i]))
- end
- return t
-end
-function resolvers.expandbraces(str)
- local pth=expandedpathfromlist(splitpath(str))
- return joinpath(pth)
-end
-function resolvers.registerfilehash(name,content,someerror)
- local files=instance.files
- if content then
- files[name]=content
- else
- files[name]={}
- if somerror==true then
- instance.loaderror=someerror
- end
- end
-end
-function resolvers.getfilehashes()
- return instance and instance.files or {}
-end
-function resolvers.gethashes()
- return instance and instance.hashes or {}
-end
-function resolvers.renewcache()
- if instance then
- instance.renewcache=true
- end
-end
-local function isreadable(name)
- local readable=isfile(name)
- if trace_details then
- if readable then
- report_resolving("file %a is readable",name)
- else
- report_resolving("file %a is not readable",name)
- end
- end
- return readable
-end
-local function collect_files(names)
- local filelist={}
- local noffiles=0
- local function check(hash,root,pathname,path,basename,name)
- if not pathname or find(path,pathname) then
- local variant=hash.type
- local search=filejoin(root,path,name)
- local result=methodhandler('concatinators',variant,root,path,name)
- if trace_details then
- report_resolving("match: variant %a, search %a, result %a",variant,search,result)
- end
- noffiles=noffiles+1
- filelist[noffiles]={ variant,search,result }
- end
- end
- for k=1,#names do
- local filename=names[k]
- if trace_details then
- report_resolving("checking name %a",filename)
- end
- local basename=filebasename(filename)
- local pathname=filedirname(filename)
- if pathname=="" or find(pathname,"^%.") then
- pathname=false
- else
- pathname=gsub(pathname,"%*",".*")
- pathname="/"..pathname.."$"
- end
- local hashes=instance.hashes
- local files=instance.files
- for h=1,#hashes do
- local hash=hashes[h]
- local hashname=hash.name
- local content=hashname and files[hashname]
- if content then
- if trace_details then
- report_resolving("deep checking %a, base %a, pattern %a",hashname,basename,pathname)
- end
- local path,name=lookup(content,basename)
- if path then
- local metadata=content.metadata
- local realroot=metadata and metadata.path or hashname
- if type(path)=="string" then
- check(hash,realroot,pathname,path,basename,name)
- else
- for i=1,#path do
- check(hash,realroot,pathname,path[i],basename,name)
- end
- end
- end
- elseif trace_locating then
- report_resolving("no match in %a (%s)",hashname,basename)
- end
- end
- end
- return noffiles>0 and filelist or nil
-end
-local fit={}
-function resolvers.registerintrees(filename,format,filetype,usedmethod,foundname)
- local foundintrees=instance.foundintrees
- if usedmethod=="direct" and filename==foundname and fit[foundname] then
- else
- local collapsed=collapsepath(foundname,true)
- local t={
- filename=filename,
- format=format~="" and format or nil,
- filetype=filetype~="" and filetype or nil,
- usedmethod=usedmethod,
- foundname=foundname,
- fullname=collapsed,
- }
- fit[foundname]=t
- foundintrees[#foundintrees+1]=t
- end
-end
-function resolvers.foundintrees()
- return instance.foundintrees or {}
-end
-function resolvers.foundintree(fullname)
- local f=fit[fullname]
- return f and f.usedmethod=="database"
-end
-local function can_be_dir(name)
- local fakepaths=instance.fakepaths
- if not fakepaths[name] then
- if isdir(name) then
- fakepaths[name]=1
- else
- fakepaths[name]=2
- end
- end
- return fakepaths[name]==1
-end
-local preparetreepattern=Cs((P(".")/"%%."+P("-")/"%%-"+P(1))^0*Cc("$"))
-local collect_instance_files
-local function find_analyze(filename,askedformat,allresults)
- local filetype=''
- local filesuffix=suffixonly(filename)
- local wantedfiles={}
- wantedfiles[#wantedfiles+1]=filename
- if askedformat=="" then
- if filesuffix=="" or not suffixmap[filesuffix] then
- local defaultsuffixes=resolvers.defaultsuffixes
- for i=1,#defaultsuffixes do
- local forcedname=filename..'.'..defaultsuffixes[i]
- wantedfiles[#wantedfiles+1]=forcedname
- filetype=formatofsuffix(forcedname)
- if trace_locating then
- report_resolving("forcing filetype %a",filetype)
- end
- end
- else
- filetype=formatofsuffix(filename)
- if trace_locating then
- report_resolving("using suffix based filetype %a",filetype)
- end
- end
- else
- if filesuffix=="" or not suffixmap[filesuffix] then
- local format_suffixes=suffixes[askedformat]
- if format_suffixes then
- for i=1,#format_suffixes do
- wantedfiles[#wantedfiles+1]=filename.."."..format_suffixes[i]
- end
- end
- end
- filetype=askedformat
- if trace_locating then
- report_resolving("using given filetype %a",filetype)
- end
- end
- return filetype,wantedfiles
-end
-local function find_direct(filename,allresults)
- if not dangerous[askedformat] and isreadable(filename) then
- if trace_details then
- report_resolving("file %a found directly",filename)
- end
- return "direct",{ filename }
- end
-end
-local function find_wildcard(filename,allresults)
- if find(filename,'*',1,true) then
- if trace_locating then
- report_resolving("checking wildcard %a",filename)
- end
- local result=resolvers.findwildcardfiles(filename)
- if result then
- return "wildcard",result
- end
- end
-end
-local function find_qualified(filename,allresults,askedformat,alsostripped)
- if not is_qualified_path(filename) then
- return
- end
- if trace_locating then
- report_resolving("checking qualified name %a",filename)
- end
- if isreadable(filename) then
- if trace_details then
- report_resolving("qualified file %a found",filename)
- end
- return "qualified",{ filename }
- end
- if trace_details then
- report_resolving("locating qualified file %a",filename)
- end
- local forcedname,suffix="",suffixonly(filename)
- if suffix=="" then
- local format_suffixes=askedformat=="" and resolvers.defaultsuffixes or suffixes[askedformat]
- if format_suffixes then
- for i=1,#format_suffixes do
- local suffix=format_suffixes[i]
- forcedname=filename.."."..suffix
- if isreadable(forcedname) then
- if trace_locating then
- report_resolving("no suffix, forcing format filetype %a",suffix)
- end
- return "qualified",{ forcedname }
- end
- end
- end
- end
- if alsostripped and suffix and suffix~="" then
- local basename=filebasename(filename)
- local pattern=lpegmatch(preparetreepattern,filename)
- local savedformat=askedformat
- local format=savedformat or ""
- if format=="" then
- askedformat=formatofsuffix(suffix)
- end
- if not format then
- askedformat="othertextfiles"
- end
- if basename~=filename then
- local resolved=collect_instance_files(basename,askedformat,allresults)
- if #resolved==0 then
- local lowered=lower(basename)
- if filename~=lowered then
- resolved=collect_instance_files(lowered,askedformat,allresults)
- end
- end
- resolvers.format=savedformat
- if #resolved>0 then
- local result={}
- for r=1,#resolved do
- local rr=resolved[r]
- if find(rr,pattern) then
- result[#result+1]=rr
- end
- end
- if #result>0 then
- return "qualified",result
- end
- end
- end
- end
-end
-local function check_subpath(fname)
- if isreadable(fname) then
- if trace_details then
- report_resolving("found %a by deep scanning",fname)
- end
- return fname
- end
-end
-local function makepathlist(list,filetype)
- local typespec=resolvers.variableofformat(filetype)
- local pathlist=expandedpathlist(typespec,filetype and usertypes[filetype])
- local entry={}
- if pathlist and #pathlist>0 then
- for k=1,#pathlist do
- local path=pathlist[k]
- local prescanned=find(path,'^!!')
- local resursive=find(path,'//$')
- local pathname=lpegmatch(inhibitstripper,path)
- local expression=makepathexpression(pathname)
- local barename=gsub(pathname,"/+$","")
- barename=resolveprefix(barename)
- local scheme=urlhasscheme(barename)
- local schemename=gsub(barename,"%.%*$",'')
- entry[k]={
- path=path,
- pathname=pathname,
- prescanned=prescanned,
- recursive=recursive,
- expression=expression,
- barename=barename,
- scheme=scheme,
- schemename=schemename,
- }
- end
- entry.typespec=typespec
- list[filetype]=entry
- else
- list[filetype]=false
- end
- return entry
-end
-local function find_intree(filename,filetype,wantedfiles,allresults)
- local pathlists=instance.pathlists
- if not pathlists then
- pathlists=setmetatableindex({},makepathlist)
- instance.pathlists=pathlists
- end
- local pathlist=pathlists[filetype]
- if pathlist then
- local method="intree"
- local filelist=collect_files(wantedfiles)
- local dirlist={}
- local result={}
- if filelist then
- for i=1,#filelist do
- dirlist[i]=filedirname(filelist[i][3]).."/"
- end
- end
- if trace_details then
- report_resolving("checking filename %a in tree",filename)
- end
- for k=1,#pathlist do
- local entry=pathlist[k]
- local path=entry.path
- local pathname=entry.pathname
- local done=false
- if filelist then
- local expression=entry.expression
- if trace_details then
- report_resolving("using pattern %a for path %a",expression,pathname)
- end
- for k=1,#filelist do
- local fl=filelist[k]
- local f=fl[2]
- local d=dirlist[k]
- if find(d,expression) or find(resolveprefix(d),expression) then
- result[#result+1]=resolveprefix(fl[3])
- done=true
- if allresults then
- if trace_details then
- report_resolving("match to %a in hash for file %a and path %a, continue scanning",expression,f,d)
- end
- else
- if trace_details then
- report_resolving("match to %a in hash for file %a and path %a, quit scanning",expression,f,d)
- end
- break
- end
- elseif trace_details then
- report_resolving("no match to %a in hash for file %a and path %a",expression,f,d)
- end
- end
- end
- if done then
- method="database"
- else
- method="filesystem"
- local scheme=entry.scheme
- if not scheme or scheme=="file" then
- local pname=entry.schemename
- if not find(pname,"*",1,true) then
- if can_be_dir(pname) then
- if not done and not entry.prescanned then
- if trace_details then
- report_resolving("quick root scan for %a",pname)
- end
- for k=1,#wantedfiles do
- local w=wantedfiles[k]
- local fname=check_subpath(filejoin(pname,w))
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- end
- if not done and entry.recursive then
- if trace_details then
- report_resolving("scanning filesystem for %a",pname)
- end
- local files=resolvers.simplescanfiles(pname,false,true)
- for k=1,#wantedfiles do
- local w=wantedfiles[k]
- local subpath=files[w]
- if not subpath or subpath=="" then
- elseif type(subpath)=="string" then
- local fname=check_subpath(filejoin(pname,subpath,w))
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- else
- for i=1,#subpath do
- local sp=subpath[i]
- if sp=="" then
- else
- local fname=check_subpath(filejoin(pname,sp,w))
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- end
- end
- if done and not allresults then
- break
- end
- end
- end
- end
- end
- end
- else
- end
- else
- for k=1,#wantedfiles do
- local pname=entry.barename
- local fname=methodhandler('finders',pname.."/"..wantedfiles[k])
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- end
- end
- end
- if done and not allresults then
- break
- end
- end
- if #result>0 then
- return method,result
- end
- end
-end
-local function find_onpath(filename,filetype,wantedfiles,allresults)
- if trace_details then
- report_resolving("checking filename %a, filetype %a, wanted files %a",filename,filetype,concat(wantedfiles," | "))
- end
- local result={}
- for k=1,#wantedfiles do
- local fname=wantedfiles[k]
- if fname and isreadable(fname) then
- filename=fname
- result[#result+1]=filejoin('.',fname)
- if not allresults then
- break
- end
- end
- end
- if #result>0 then
- return "onpath",result
- end
-end
-local function find_otherwise(filename,filetype,wantedfiles,allresults)
- local filelist=collect_files(wantedfiles)
- local fl=filelist and filelist[1]
- if fl then
- return "otherwise",{ resolveprefix(fl[3]) }
- end
-end
-collect_instance_files=function(filename,askedformat,allresults)
- if not filename or filename=="" then
- return {}
- end
- askedformat=askedformat or ""
- filename=collapsepath(filename,".")
- filename=gsub(filename,"^%./",getcurrentdir().."/")
- if allresults then
- local filetype,wantedfiles=find_analyze(filename,askedformat)
- local results={
- { find_direct (filename,true) },
- { find_wildcard (filename,true) },
- { find_qualified(filename,true,askedformat) },
- { find_intree (filename,filetype,wantedfiles,true) },
- { find_onpath (filename,filetype,wantedfiles,true) },
- { find_otherwise(filename,filetype,wantedfiles,true) },
- }
- local result={}
- local status={}
- local done={}
- for k,r in next,results do
- local method,list=r[1],r[2]
- if method and list then
- for i=1,#list do
- local c=collapsepath(list[i])
- if not done[c] then
- result[#result+1]=c
- done[c]=true
- end
- status[#status+1]=formatters["%-10s: %s"](method,c)
- end
- end
- end
- if trace_details then
- report_resolving("lookup status: %s",table.serialize(status,filename))
- end
- return result,status
- else
- local method,result,stamp,filetype,wantedfiles
- if instance.remember then
- if askedformat=="" then
- stamp=formatters["%s::%s"](suffixonly(filename),filename)
- else
- stamp=formatters["%s::%s"](askedformat,filename)
- end
- result=stamp and instance.found[stamp]
- if result then
- if trace_locating then
- report_resolving("remembered file %a",filename)
- end
- return result
- end
- end
- method,result=find_direct(filename)
- if not result then
- method,result=find_wildcard(filename)
- if not result then
- method,result=find_qualified(filename,false,askedformat)
- if not result then
- filetype,wantedfiles=find_analyze(filename,askedformat)
- method,result=find_intree(filename,filetype,wantedfiles)
- if not result then
- method,result=find_onpath(filename,filetype,wantedfiles)
- if resolve_otherwise and not result then
- method,result=find_otherwise(filename,filetype,wantedfiles)
- end
- end
- end
- end
- end
- if result and #result>0 then
- local foundname=collapsepath(result[1])
- resolvers.registerintrees(filename,askedformat,filetype,method,foundname)
- result={ foundname }
- else
- result={}
- end
- if stamp then
- if trace_locating then
- report_resolving("remembering file %a using hash %a",filename,stamp)
- end
- instance.found[stamp]=result
- end
- return result
- end
-end
-local function findfiles(filename,filetype,allresults)
- if not filename or filename=="" then
- return {}
- end
- if allresults==nil then
- allresults=true
- end
- local result,status=collect_instance_files(filename,filetype or "",allresults)
- if not result or #result==0 then
- local lowered=lower(filename)
- if filename~=lowered then
- result,status=collect_instance_files(lowered,filetype or "",allresults)
- end
- end
- return result or {},status
-end
-local function findfile(filename,filetype)
- if not filename or filename=="" then
- return ""
- else
- return findfiles(filename,filetype,false)[1] or ""
- end
-end
-resolvers.findfiles=findfiles
-resolvers.findfile=findfile
-resolvers.find_file=findfile
-resolvers.find_files=findfiles
-function resolvers.findpath(filename,filetype)
- return filedirname(findfiles(filename,filetype,false)[1] or "")
-end
-local function findgivenfiles(filename,allresults)
- local hashes=instance.hashes
- local files=instance.files
- local base=filebasename(filename)
- local result={}
- local function okay(hash,path,name)
- local found=methodhandler('concatinators',hash.type,hash.name,path,name)
- if found and found~="" then
- result[#result+1]=resolveprefix(found)
- return not allresults
- end
- end
- for k=1,#hashes do
- local hash=hashes[k]
- local content=files[hash.name]
- if content then
- local path,name=lookup(content,base)
- if not path then
- elseif type(path)=="string" then
- if okay(hash,path,name) then
- return result
- end
- else
- for i=1,#path do
- if okay(hash,path[i],name) then
- return result
- end
- end
- end
- end
- end
- return result
-end
-function resolvers.findgivenfiles(filename)
- return findgivenfiles(filename,true)
-end
-function resolvers.findgivenfile(filename)
- return findgivenfiles(filename,false)[1] or ""
-end
-local makewildcard=Cs(
- (P("^")^0*P("/")*P(-1)+P(-1))/".*"+(P("^")^0*P("/")/"")^0*(P("*")/".*"+P("-")/"%%-"+P(".")/"%%."+P("?")/"."+P("\\")/"/"+P(1))^0
-)
-function resolvers.wildcardpattern(pattern)
- return lpegmatch(makewildcard,pattern) or pattern
-end
-local function findwildcardfiles(filename,allresults,result)
- local files=instance.files
- local hashes=instance.hashes
- local result=result or {}
- local base=filebasename(filename)
- local dirn=filedirname(filename)
- local path=lower(lpegmatch(makewildcard,dirn) or dirn)
- local name=lower(lpegmatch(makewildcard,base) or base)
- if find(name,"*",1,true) then
- local function okay(found,path,base,hashname,hashtype)
- if find(found,path) then
- local full=methodhandler('concatinators',hashtype,hashname,found,base)
- if full and full~="" then
- result[#result+1]=resolveprefix(full)
- return not allresults
- end
- end
- end
- for k=1,#hashes do
- local hash=hashes[k]
- local hashname=hash.name
- local hashtype=hash.type
- if hashname and hashtype then
- for found,base in filtered(files[hashname],name) do
- if type(found)=='string' then
- if okay(found,path,base,hashname,hashtype) then
- break
- end
- else
- for i=1,#found do
- if okay(found[i],path,base,hashname,hashtype) then
- break
- end
- end
- end
- end
- end
- end
- else
- local function okayokay(found,path,base,hashname,hashtype)
- if find(found,path) then
- local full=methodhandler('concatinators',hashtype,hashname,found,base)
- if full and full~="" then
- result[#result+1]=resolveprefix(full)
- return not allresults
- end
- end
- end
- for k=1,#hashes do
- local hash=hashes[k]
- local hashname=hash.name
- local hashtype=hash.type
- if hashname and hashtype then
- local found,base=lookup(content,base)
- if not found then
- elseif type(found)=='string' then
- if okay(found,path,base,hashname,hashtype) then
- break
- end
- else
- for i=1,#found do
- if okay(found[i],path,base,hashname,hashtype) then
- break
- end
- end
- end
- end
- end
- end
- return result
-end
-function resolvers.findwildcardfiles(filename,result)
- return findwildcardfiles(filename,true,result)
-end
-function resolvers.findwildcardfile(filename)
- return findwildcardfiles(filename,false)[1] or ""
-end
-do
- local starttiming=statistics.starttiming
- local stoptiming=statistics.stoptiming
- local elapsedtime=statistics.elapsedtime
- function resolvers.starttiming()
- starttiming(instance)
- end
- function resolvers.stoptiming()
- stoptiming(instance)
- end
- function resolvers.loadtime()
- return elapsedtime(instance)
- end
-end
-function resolvers.automount()
-end
-function resolvers.load(option)
- resolvers.starttiming()
- identify_configuration_files()
- load_configuration_files()
- if option~="nofiles" then
- load_databases()
- resolvers.automount()
- end
- resolvers.stoptiming()
- local files=instance.files
- return files and next(files) and true
-end
-local function report(str)
- if trace_locating then
- report_resolving(str)
- else
- print(str)
- end
-end
-function resolvers.dowithfilesandreport(command,files,...)
- if files and #files>0 then
- if trace_locating then
- report('')
- end
- if type(files)=="string" then
- files={ files }
- end
- for f=1,#files do
- local file=files[f]
- local result=command(file,...)
- if type(result)=='string' then
- report(result)
- else
- for i=1,#result do
- report(result[i])
- end
- end
- end
- end
-end
-function resolvers.showpath(str)
- return joinpath(expandedpathlist(resolvers.formatofvariable(str)))
-end
-function resolvers.registerfile(files,name,path)
- if files[name] then
- if type(files[name])=='string' then
- files[name]={ files[name],path }
- else
- files[name]=path
- end
- else
- files[name]=path
- end
-end
-function resolvers.dowithpath(name,func)
- local pathlist=expandedpathlist(name)
- for i=1,#pathlist do
- func("^"..cleanpath(pathlist[i]))
- end
-end
-function resolvers.dowithvariable(name,func)
- func(expandedvariable(name))
-end
-function resolvers.locateformat(name)
- local engine=environment.ownmain or "luatex"
- local barename=removesuffix(file.basename(name))
- local fullname=addsuffix(barename,"fmt")
- local fmtname=caches.getfirstreadablefile(fullname,"formats",engine) or ""
- if fmtname=="" then
- fmtname=findfile(fullname)
- fmtname=cleanpath(fmtname)
- end
- if fmtname~="" then
- local barename=removesuffix(fmtname)
- local luaname=addsuffix(barename,luasuffixes.lua)
- local lucname=addsuffix(barename,luasuffixes.luc)
- local luiname=addsuffix(barename,luasuffixes.lui)
- if isfile(luiname) then
- return fmtname,luiname
- elseif isfile(lucname) then
- return fmtname,lucname
- elseif isfile(luaname) then
- return fmtname,luaname
- end
- end
- return nil,nil
-end
-function resolvers.booleanvariable(str,default)
- local b=expansion(str)
- if b=="" then
- return default
- else
- b=toboolean(b)
- return (b==nil and default) or b
- end
-end
-function resolvers.dowithfilesintree(pattern,handle,before,after)
- local hashes=instance.hashes
- local files=instance.files
- for i=1,#hashes do
- local hash=hashes[i]
- local blobtype=hash.type
- local blobpath=hash.name
- if blobtype and blobpath then
- local total=0
- local checked=0
- local done=0
- if before then
- before(blobtype,blobpath,pattern)
- end
- for path,name in filtered(files[blobpath],pattern) do
- if type(path)=="string" then
- checked=checked+1
- if handle(blobtype,blobpath,path,name) then
- done=done+1
- end
- else
- checked=checked+#path
- for i=1,#path do
- if handle(blobtype,blobpath,path[i],name) then
- done=done+1
- end
- end
- end
- end
- if after then
- after(blobtype,blobpath,pattern,checked,done)
- end
- end
- end
-end
-function resolvers.knownvariables(pattern)
- if instance then
- local environment=instance.environment
- local variables=instance.variables
- local expansions=instance.expansions
- local order=instance.order
- local pattern=upper(pattern or "")
- local result={}
- for i=1,#order do
- for key in next,order[i] do
- if result[key]==nil and key~="" and (pattern=="" or find(upper(key),pattern)) then
- result[key]={
- environment=rawget(environment,key),
- variable=key,
- expansion=expansions[key],
- resolved=resolveprefix(expansions[key]),
- }
- end
- end
- end
- return result
- else
- return {}
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-pre"] = package.loaded["data-pre"] or true
-
--- original size: 5088, stripped down to: 3144
-
-if not modules then modules={} end modules ['data-pre']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local insert,remove=table.insert,table.remove
-local resolvers=resolvers
-local prefixes=resolvers.prefixes
-local cleanpath=resolvers.cleanpath
-local findgivenfile=resolvers.findgivenfile
-local expansion=resolvers.expansion
-local getenv=resolvers.getenv
-local basename=file.basename
-local dirname=file.dirname
-local joinpath=file.join
-local isfile=lfs.isfile
-prefixes.environment=function(str)
- return cleanpath(expansion(str))
-end
-local function relative(str,n)
- if not isfile(str) then
- local pstr="./"..str
- if isfile(pstr) then
- str=pstr
- else
- local p="../"
- for i=1,n or 2 do
- local pstr=p..str
- if isfile(pstr) then
- str=pstr
- break
- else
- p=p.."../"
- end
- end
- end
- end
- return cleanpath(str)
-end
-local function locate(str)
- local fullname=findgivenfile(str) or ""
- return cleanpath(fullname~="" and fullname or str)
-end
-prefixes.relative=relative
-prefixes.locate=locate
-prefixes.auto=function(str)
- local fullname=relative(str)
- if not isfile(fullname) then
- fullname=locate(str)
- end
- return fullname
-end
-prefixes.filename=function(str)
- local fullname=findgivenfile(str) or ""
- return cleanpath(basename((fullname~="" and fullname) or str))
-end
-prefixes.pathname=function(str)
- local fullname=findgivenfile(str) or ""
- return cleanpath(dirname((fullname~="" and fullname) or str))
-end
-prefixes.selfautoloc=function(str)
- local pth=getenv('SELFAUTOLOC')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.selfautoparent=function(str)
- local pth=getenv('SELFAUTOPARENT')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.selfautodir=function(str)
- local pth=getenv('SELFAUTODIR')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.home=function(str)
- local pth=getenv('HOME')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.env=prefixes.environment
-prefixes.rel=prefixes.relative
-prefixes.loc=prefixes.locate
-prefixes.kpse=prefixes.locate
-prefixes.full=prefixes.locate
-prefixes.file=prefixes.filename
-prefixes.path=prefixes.pathname
-local inputstack={}
-local stackpath=resolvers.stackpath
-local function toppath()
- if not inputstack then
- return "."
- end
- local pathname=dirname(inputstack[#inputstack] or "")
- if pathname=="" then
- return "."
- else
- return pathname
- end
-end
-local function jobpath()
- local path=stackpath()
- if not path or path=="" then
- return "."
- else
- return path
- end
-end
-local function pushinputname(name)
- insert(inputstack,name)
-end
-local function popinputname(name)
- return remove(inputstack)
-end
-resolvers.toppath=toppath
-resolvers.jobpath=jobpath
-resolvers.pushinputname=pushinputname
-resolvers.popinputname=popinputname
-prefixes.toppath=function(str) return cleanpath(joinpath(toppath(),str)) end
-prefixes.jobpath=function(str) return cleanpath(joinpath(jobpath(),str)) end
-resolvers.setdynamic("toppath")
-resolvers.setdynamic("jobpath")
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-inp"] = package.loaded["data-inp"] or true
-
--- original size: 910, stripped down to: 818
-
-if not modules then modules={} end modules ['data-inp']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local allocate=utilities.storage.allocate
-local resolvers=resolvers
-local methodhandler=resolvers.methodhandler
-local registermethod=resolvers.registermethod
-local finders=allocate { helpers={},notfound=function() end }
-local openers=allocate { helpers={},notfound=function() end }
-local loaders=allocate { helpers={},notfound=function() return false,nil,0 end }
-registermethod("finders",finders,"uri")
-registermethod("openers",openers,"uri")
-registermethod("loaders",loaders,"uri")
-resolvers.finders=finders
-resolvers.openers=openers
-resolvers.loaders=loaders
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-out"] = package.loaded["data-out"] or true
-
--- original size: 551, stripped down to: 470
-
-if not modules then modules={} end modules ['data-out']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local allocate=utilities.storage.allocate
-local resolvers=resolvers
-local registermethod=resolvers.registermethod
-local savers=allocate { helpers={} }
-resolvers.savers=savers
-registermethod("savers",savers,"uri")
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-fil"] = package.loaded["data-fil"] or true
-
--- original size: 4365, stripped down to: 3452
-
-if not modules then modules={} end modules ['data-fil']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local ioopen=io.open
-local isdir=lfs.isdir
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_files=logs.reporter("resolvers","files")
-local resolvers=resolvers
-local resolveprefix=resolvers.resolve
-local findfile=resolvers.findfile
-local scanfiles=resolvers.scanfiles
-local registerfilehash=resolvers.registerfilehash
-local appendhash=resolvers.appendhash
-local loadcachecontent=caches.loadcontent
-function resolvers.locators.file(specification)
- local filename=specification.filename
- local realname=resolveprefix(filename)
- if realname and realname~='' and isdir(realname) then
- if trace_locating then
- report_files("file locator %a found as %a",filename,realname)
- end
- appendhash('file',filename,true)
- elseif trace_locating then
- report_files("file locator %a not found",filename)
- end
-end
-function resolvers.hashers.file(specification)
- local pathname=specification.filename
- local content=loadcachecontent(pathname,'files')
- registerfilehash(pathname,content,content==nil)
-end
-function resolvers.generators.file(specification)
- local pathname=specification.filename
- local content=scanfiles(pathname,false,true)
- registerfilehash(pathname,content,true)
-end
-resolvers.concatinators.file=file.join
-local finders=resolvers.finders
-local notfound=finders.notfound
-function finders.file(specification,filetype)
- local filename=specification.filename
- local foundname=findfile(filename,filetype)
- if foundname and foundname~="" then
- if trace_locating then
- report_files("file finder: %a found",filename)
- end
- return foundname
- else
- if trace_locating then
- report_files("file finder: %a not found",filename)
- end
- return notfound()
- end
-end
-local openers=resolvers.openers
-local notfound=openers.notfound
-local overloaded=false
-local function textopener(tag,filename,f)
- return {
- reader=function() return f:read () end,
- close=function() return f:close() end,
- }
-end
-function openers.helpers.textopener(...)
- return textopener(...)
-end
-function openers.helpers.settextopener(opener)
- if overloaded then
- report_files("file opener: %s overloaded","already")
- else
- if trace_locating then
- report_files("file opener: %s overloaded","once")
- end
- overloaded=true
- textopener=opener
- end
-end
-function openers.file(specification,filetype)
- local filename=specification.filename
- if filename and filename~="" then
- local f=ioopen(filename,"r")
- if f then
- if trace_locating then
- report_files("file opener: %a opened",filename)
- end
- return textopener("file",filename,f)
- end
- end
- if trace_locating then
- report_files("file opener: %a not found",filename)
- end
- return notfound()
-end
-local loaders=resolvers.loaders
-local notfound=loaders.notfound
-function loaders.file(specification,filetype)
- local filename=specification.filename
- if filename and filename~="" then
- local f=ioopen(filename,"rb")
- if f then
- if trace_locating then
- report_files("file loader: %a loaded",filename)
- end
- local s=f:read("*a")
- f:close()
- if s then
- return true,s,#s
- end
- end
- end
- if trace_locating then
- report_files("file loader: %a not found",filename)
- end
- return notfound()
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-con"] = package.loaded["data-con"] or true
-
--- original size: 5388, stripped down to: 3685
-
-if not modules then modules={} end modules ['data-con']={
- version=1.100,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local setmetatable=setmetatable
-local format,lower,gsub=string.format,string.lower,string.gsub
-local trace_cache=false trackers.register("resolvers.cache",function(v) trace_cache=v end)
-local trace_containers=false trackers.register("resolvers.containers",function(v) trace_containers=v end)
-local trace_storage=false trackers.register("resolvers.storage",function(v) trace_storage=v end)
-containers=containers or {}
-local containers=containers
-containers.usecache=true
-local getwritablepath=caches.getwritablepath
-local getreadablepaths=caches.getreadablepaths
-local cacheiswritable=caches.is_writable
-local loaddatafromcache=caches.loaddata
-local savedataincache=caches.savedata
-local report_containers=logs.reporter("resolvers","containers")
-local allocated={}
-local mt={
- __index=function(t,k)
- if k=="writable" then
- local writable=getwritablepath(t.category,t.subcategory) or { "." }
- t.writable=writable
- return writable
- elseif k=="readables" then
- local readables=getreadablepaths(t.category,t.subcategory) or { "." }
- t.readables=readables
- return readables
- end
- end,
- __storage__=true
-}
-function containers.define(category,subcategory,version,enabled)
- if category and subcategory then
- local c=allocated[category]
- if not c then
- c={}
- allocated[category]=c
- end
- local s=c[subcategory]
- if not s then
- s={
- category=category,
- subcategory=subcategory,
- storage={},
- enabled=enabled,
- version=version or math.pi,
- trace=false,
- }
- setmetatable(s,mt)
- c[subcategory]=s
- end
- return s
- end
-end
-function containers.is_usable(container,name)
- return container.enabled and caches and cacheiswritable(container.writable,name)
-end
-function containers.is_valid(container,name)
- if name and name~="" then
- local storage=container.storage[name]
- return storage and storage.cache_version==container.version
- else
- return false
- end
-end
-function containers.read(container,name)
- local storage=container.storage
- local stored=storage[name]
- if not stored and container.enabled and caches and containers.usecache then
- stored=loaddatafromcache(container.readables,name,container.writable)
- if stored and stored.cache_version==container.version then
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","load",container.subcategory,name)
- end
- else
- stored=nil
- end
- storage[name]=stored
- elseif stored then
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","reuse",container.subcategory,name)
- end
- end
- return stored
-end
-function containers.write(container,name,data,fast)
- if data then
- data.cache_version=container.version
- if container.enabled and caches then
- local unique=data.unique
- local shared=data.shared
- data.unique=nil
- data.shared=nil
- savedataincache(container.writable,name,data,fast)
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","save",container.subcategory,name)
- end
- data.unique=unique
- data.shared=shared
- end
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","store",container.subcategory,name)
- end
- container.storage[name]=data
- end
- return data
-end
-function containers.content(container,name)
- return container.storage[name]
-end
-function containers.cleanname(name)
- return (gsub(lower(name),"[^%w\128-\255]+","-"))
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-use"] = package.loaded["data-use"] or true
-
--- original size: 5785, stripped down to: 2905
-
-if not modules then modules={} end modules ['data-use']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local format=string.format
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_mounts=logs.reporter("resolvers","mounts")
-local resolvers=resolvers
-local findfile=resolvers.findfile
-statistics.register("used config file",function() return caches.configfiles() end)
-statistics.register("used cache path",function() return caches.usedpaths() end)
-function statistics.savefmtstatus(texname,formatbanner,sourcefile,banner)
- local enginebanner=status.banner
- if formatbanner and enginebanner and sourcefile then
- local luvname=file.replacesuffix(texname,"luv")
- local luvdata={
- enginebanner=enginebanner,
- formatbanner=formatbanner,
- sourcehash=md5.hex(io.loaddata(findfile(sourcefile)) or "unknown"),
- sourcefile=sourcefile,
- luaversion=LUAVERSION,
- formatid=LUATEXFORMATID,
- functionality=LUATEXFUNCTIONALITY,
- }
- io.savedata(luvname,table.serialize(luvdata,true))
- lua.registerfinalizer(function()
- if jit then
- logs.report("format banner","%s lua: %s jit",banner,LUAVERSION)
- else
- logs.report("format banner","%s lua: %s",banner,LUAVERSION)
- end
- logs.newline()
- end)
- end
-end
-function statistics.checkfmtstatus(texname)
- local enginebanner=status.banner
- if enginebanner and texname then
- local luvname=file.replacesuffix(texname,"luv")
- if lfs.isfile(luvname) then
- local luv=dofile(luvname)
- if luv and luv.sourcefile then
- local sourcehash=md5.hex(io.loaddata(findfile(luv.sourcefile)) or "unknown")
- local luvbanner=luv.enginebanner or "?"
- if luvbanner~=enginebanner then
- return format("engine mismatch (luv: %s <> bin: %s)",luvbanner,enginebanner)
- end
- local luvhash=luv.sourcehash or "?"
- if luvhash~=sourcehash then
- return format("source mismatch (luv: %s <> bin: %s)",luvhash,sourcehash)
- end
- local luvluaversion=luv.luaversion or 0
- local engluaversion=LUAVERSION or 0
- if luvluaversion~=engluaversion then
- return format("lua mismatch (luv: %s <> bin: %s)",luvluaversion,engluaversion)
- end
- local luvfunctionality=luv.functionality or 0
- local engfunctionality=status.development_id or 0
- if luvfunctionality~=engfunctionality then
- return format("functionality mismatch (luv: %s <> bin: %s)",luvfunctionality,engfunctionality)
- end
- local luvformatid=luv.formatid or 0
- local engformatid=status.format_id or 0
- if luvformatid~=engformatid then
- return format("formatid mismatch (luv: %s <> bin: %s)",luvformatid,engformatid)
- end
- else
- return "invalid status file"
- end
- else
- return "missing status file"
- end
- end
- return true
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-zip"] = package.loaded["data-zip"] or true
-
--- original size: 10725, stripped down to: 7949
-
-if not modules then modules={} end modules ['data-zip']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local format,find,match=string.format,string.find,string.match
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_zip=logs.reporter("resolvers","zip")
-local resolvers=resolvers
-local findfile=resolvers.findfile
-local registerfile=resolvers.registerfile
-local splitmethod=resolvers.splitmethod
-local prependhash=resolvers.prependhash
-local starttiming=resolvers.starttiming
-local extendtexmf=resolvers.extendtexmfvariable
-local stoptiming=resolvers.stoptiming
-local urlquery=url.query
-zip=zip or {}
-local zip=zip
-local archives=zip.archives or {}
-zip.archives=archives
-local registeredfiles=zip.registeredfiles or {}
-zip.registeredfiles=registeredfiles
-local zipfiles=utilities.zipfiles
-local openzip,closezip,validfile,wholefile,filehandle,traversezip
-if zipfiles then
- local ipairs=ipairs
- openzip=zipfiles.open
- closezip=zipfiles.close
- validfile=zipfiles.found
- wholefile=zipfiles.unzip
- local listzip=zipfiles.list
- traversezip=function(zfile)
- return ipairs(listzip(zfile))
- end
- local streams=utilities.streams
- local openstream=streams.open
- local readstring=streams.readstring
- local streamsize=streams.size
- local metatable={
- close=streams.close,
- read=function(stream,n)
- readstring(stream,n=="*a" and streamsize(stream) or n)
- end
- }
- filehandle=function(zfile,queryname)
- local data=wholefile(zfile,queryname)
- if data then
- local stream=openstream(data)
- if stream then
- return setmetatableindex(stream,metatable)
- end
- end
- end
-else
- openzip=zip.open
- closezip=zip.close
- validfile=function(zfile,queryname)
- local dfile=zfile:open(queryname)
- if dfile then
- dfile:close()
- return true
- end
- return false
- end
- traversezip=function(zfile)
- return z:files()
- end
- wholefile=function(zfile,queryname)
- local dfile=zfile:open(queryname)
- if dfile then
- local s=dfile:read("*all")
- dfile:close()
- return s
- end
- end
- filehandle=function(zfile,queryname)
- local dfile=zfile:open(queryname)
- if dfile then
- return dfile
- end
- end
-end
-local function validzip(str)
- if not find(str,"^zip://") then
- return "zip:///"..str
- else
- return str
- end
-end
-local function openarchive(name)
- if not name or name=="" then
- return nil
- else
- local arch=archives[name]
- if not arch then
- local full=findfile(name) or ""
- arch=full~="" and openzip(full) or false
- archives[name]=arch
- end
- return arch
- end
-end
-local function closearchive(name)
- if not name or (name=="" and archives[name]) then
- closezip(archives[name])
- archives[name]=nil
- end
-end
-zip.openarchive=openarchive
-zip.closearchive=closearchive
-function resolvers.locators.zip(specification)
- local archive=specification.filename
- local zipfile=archive and archive~="" and openarchive(archive)
- if trace_locating then
- if zipfile then
- report_zip("locator: archive %a found",archive)
- else
- report_zip("locator: archive %a not found",archive)
- end
- end
-end
-function resolvers.concatinators.zip(zipfile,path,name)
- if not path or path=="" then
- return format('%s?name=%s',zipfile,name)
- else
- return format('%s?name=%s/%s',zipfile,path,name)
- end
-end
-local finders=resolvers.finders
-local notfound=finders.notfound
-function finders.zip(specification)
- local original=specification.original
- local archive=specification.filename
- if archive then
- local query=urlquery(specification.query)
- local queryname=query.name
- if queryname then
- local zfile=openarchive(archive)
- if zfile then
- if trace_locating then
- report_zip("finder: archive %a found",archive)
- end
- if validfile(zfile,queryname) then
- if trace_locating then
- report_zip("finder: file %a found",queryname)
- end
- return specification.original
- elseif trace_locating then
- report_zip("finder: file %a not found",queryname)
- end
- elseif trace_locating then
- report_zip("finder: unknown archive %a",archive)
- end
- end
- end
- if trace_locating then
- report_zip("finder: %a not found",original)
- end
- return notfound()
-end
-local openers=resolvers.openers
-local notfound=openers.notfound
-local textopener=openers.helpers.textopener
-function openers.zip(specification)
- local original=specification.original
- local archive=specification.filename
- if archive then
- local query=urlquery(specification.query)
- local queryname=query.name
- if queryname then
- local zfile=openarchive(archive)
- if zfile then
- if trace_locating then
- report_zip("opener; archive %a opened",archive)
- end
- local handle=filehandle(zfile,queryname)
- if handle then
- if trace_locating then
- report_zip("opener: file %a found",queryname)
- end
- return textopener('zip',original,handle)
- elseif trace_locating then
- report_zip("opener: file %a not found",queryname)
- end
- elseif trace_locating then
- report_zip("opener: unknown archive %a",archive)
- end
- end
- end
- if trace_locating then
- report_zip("opener: %a not found",original)
- end
- return notfound()
-end
-local loaders=resolvers.loaders
-local notfound=loaders.notfound
-function loaders.zip(specification)
- local original=specification.original
- local archive=specification.filename
- if archive then
- local query=urlquery(specification.query)
- local queryname=query.name
- if queryname then
- local zfile=openarchive(archive)
- if zfile then
- if trace_locating then
- report_zip("loader: archive %a opened",archive)
- end
- local data=wholefile(zfile,queryname)
- if data then
- if trace_locating then
- report_zip("loader; file %a loaded",original)
- end
- return true,data,#data
- elseif trace_locating then
- report_zip("loader: file %a not found",queryname)
- end
- elseif trace_locating then
- report_zip("loader; unknown archive %a",archive)
- end
- end
- end
- if trace_locating then
- report_zip("loader: %a not found",original)
- end
- return notfound()
-end
-local function registerzipfile(z,tree)
- local names={}
- local files={}
- local remap={}
- local n=0
- local filter=tree=="" and "^(.+)/(.-)$" or format("^%s/(.+)/(.-)$",tree)
- if trace_locating then
- report_zip("registering: using filter %a",filter)
- end
- starttiming()
- for i in traversezip(z) do
- local filename=i.filename
- local path,name=match(filename,filter)
- if not path then
- n=n+1
- registerfile(names,filename,"")
- local usedname=lower(filename)
- files[usedname]=""
- if usedname~=filename then
- remap[usedname]=filename
- end
- elseif name and name~="" then
- n=n+1
- register(names,name,path)
- local usedname=lower(name)
- files[usedname]=path
- if usedname~=name then
- remap[usedname]=name
- end
- else
- end
- end
- stoptiming()
- report_zip("registering: %s files registered",n)
- return {
- files=files,
- remap=remap,
- }
-end
-local function usezipfile(archive)
- local specification=splitmethod(archive)
- local archive=specification.filename
- if archive and not registeredfiles[archive] then
- local z=openarchive(archive)
- if z then
- local tree=urlquery(specification.query).tree or ""
- if trace_locating then
- report_zip("registering: archive %a",archive)
- end
- prependhash('zip',archive)
- extendtexmf(archive)
- registeredfiles[archive]=z
- registerfilehash(archive,registerzipfile(z,tree))
- elseif trace_locating then
- report_zip("registering: unknown archive %a",archive)
- end
- elseif trace_locating then
- report_zip("registering: archive %a not found",archive)
- end
-end
-resolvers.usezipfile=usezipfile
-resolvers.registerzipfile=registerzipfile
-function resolvers.hashers.zip(specification)
- local archive=specification.filename
- if trace_locating then
- report_zip("loading file %a",archive)
- end
- usezipfile(specification.original)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-tre"] = package.loaded["data-tre"] or true
-
--- original size: 10802, stripped down to: 6619
-
-if not modules then modules={} end modules ['data-tre']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type=type
-local find,gsub,lower=string.find,string.gsub,string.lower
-local basename,dirname,joinname=file.basename,file.dirname,file.join
-local globdir,isdir,isfile=dir.glob,lfs.isdir,lfs.isfile
-local P,lpegmatch=lpeg.P,lpeg.match
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_trees=logs.reporter("resolvers","trees")
-local resolvers=resolvers
-local finders=resolvers.finders
-local openers=resolvers.openers
-local loaders=resolvers.loaders
-local locators=resolvers.locators
-local hashers=resolvers.hashers
-local generators=resolvers.generators
-do
- local collectors={}
- local found={}
- local notfound=finders.notfound
- function finders.tree(specification)
- local spec=specification.filename
- local okay=found[spec]
- if okay==nil then
- if spec~="" then
- local path=dirname(spec)
- local name=basename(spec)
- if path=="" then
- path="."
- end
- local names=collectors[path]
- if not names then
- local pattern=find(path,"/%*+$") and path or (path.."/*")
- names=globdir(pattern)
- collectors[path]=names
- end
- local pattern="/"..gsub(name,"([%.%-%+])","%%%1").."$"
- for i=1,#names do
- local fullname=names[i]
- if find(fullname,pattern) then
- found[spec]=fullname
- return fullname
- end
- end
- local pattern=lower(pattern)
- for i=1,#names do
- local fullname=lower(names[i])
- if find(fullname,pattern) then
- if isfile(fullname) then
- found[spec]=fullname
- return fullname
- else
- break
- end
- end
- end
- end
- okay=notfound()
- found[spec]=okay
- end
- return okay
- end
-end
-do
- local resolveprefix=resolvers.resolve
- local appendhash=resolvers.appendhash
- local function dolocate(specification)
- local name=specification.filename
- local realname=resolveprefix(name)
- if realname and realname~='' and isdir(realname) then
- if trace_locating then
- report_trees("locator %a found",realname)
- end
- appendhash('tree',name,false)
- elseif trace_locating then
- report_trees("locator %a not found",name)
- end
- end
- locators.tree=dolocate
- locators.dirlist=dolocate
- locators.dirfile=dolocate
-end
-do
- local filegenerator=generators.file
- generators.dirlist=filegenerator
- generators.dirfile=filegenerator
-end
-do
- local filegenerator=generators.file
- local methodhandler=resolvers.methodhandler
- local function dohash(specification)
- local name=specification.filename
- if trace_locating then
- report_trees("analyzing %a",name)
- end
- methodhandler("hashers",name)
- filegenerator(specification)
- end
- hashers.tree=dohash
- hashers.dirlist=dohash
- hashers.dirfile=dohash
-end
-local resolve do
- local collectors={}
- local splitter=lpeg.splitat("/**/")
- local stripper=lpeg.replacer { [P("/")*P("*")^1*P(-1)]="" }
- local loadcontent=caches.loadcontent
- local savecontent=caches.savecontent
- local notfound=finders.notfound
- local scanfiles=resolvers.scanfiles
- local lookup=resolvers.get_from_content
- table.setmetatableindex(collectors,function(t,k)
- local rootname=lpegmatch(stripper,k)
- local dataname=joinname(rootname,"dirlist")
- local content=loadcontent(dataname,"files",dataname)
- if not content then
- content=scanfiles(rootname,nil,nil,false,true)
- savecontent(dataname,"files",content,dataname)
- end
- t[k]=content
- return content
- end)
- local function checked(root,p,n)
- if p then
- if type(p)=="table" then
- for i=1,#p do
- local fullname=joinname(root,p[i],n)
- if isfile(fullname) then
- return fullname
- end
- end
- else
- local fullname=joinname(root,p,n)
- if isfile(fullname) then
- return fullname
- end
- end
- end
- return notfound()
- end
- resolve=function(specification)
- local filename=specification.filename
- if filename~="" then
- local root,rest=lpegmatch(splitter,filename)
- if root and rest then
- local path,name=dirname(rest),basename(rest)
- if name~=rest then
- local content=collectors[root]
- local p,n=lookup(content,name)
- if not p then
- return notfound()
- end
- local pattern=".*/"..path.."$"
- local istable=type(p)=="table"
- if istable then
- for i=1,#p do
- local pi=p[i]
- if pi==path or find(pi,pattern) then
- local fullname=joinname(root,pi,n)
- if isfile(fullname) then
- return fullname
- end
- end
- end
- elseif p==path or find(p,pattern) then
- local fullname=joinname(root,p,n)
- if isfile(fullname) then
- return fullname
- end
- end
- local queries=specification.queries
- if queries and queries.option=="fileonly" then
- return checked(root,p,n)
- else
- return notfound()
- end
- end
- end
- local path=dirname(filename)
- local name=basename(filename)
- local root=lpegmatch(stripper,path)
- local content=collectors[path]
- local p,n=lookup(content,name)
- if p then
- return checked(root,p,n)
- end
- end
- return notfound()
- end
- finders.dirlist=resolve
- function finders.dirfile(specification)
- local queries=specification.queries
- if queries then
- queries.option="fileonly"
- else
- specification.queries={ option="fileonly" }
- end
- return resolve(specification)
- end
-end
-do
- local fileopener=openers.file
- local fileloader=loaders.file
- openers.dirlist=fileopener
- loaders.dirlist=fileloader
- openers.dirfile=fileopener
- loaders.dirfile=fileloader
-end
-do
- local hashfile="dirhash.lua"
- local kind="HASH256"
- local version=1.0
- local loadtable=table.load
- local savetable=table.save
- local loaddata=io.loaddata
- function resolvers.dirstatus(patterns)
- local t=type(patterns)
- if t=="string" then
- patterns={ patterns }
- elseif t~="table" then
- return false
- end
- local status=loadtable(hashfile)
- if not status or status.version~=version or status.kind~=kind then
- status={
- version=1.0,
- kind=kind,
- hashes={},
- }
- end
- local hashes=status.hashes
- local changed={}
- local action=sha2[kind]
- local update={}
- for i=1,#patterns do
- local pattern=patterns[i]
- local files=globdir(pattern)
- for i=1,#files do
- local name=files[i]
- local hash=action(loaddata(name))
- if hashes[name]~=hash then
- changed[#changed+1]=name
- end
- update[name]=hash
- end
- end
- status.hashes=update
- savetable(hashfile,status)
- return #changed>0 and changed or false
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-sch"] = package.loaded["data-sch"] or true
-
--- original size: 6945, stripped down to: 5408
-
-if not modules then modules={} end modules ['data-sch']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local load,tonumber=load,tonumber
-local gsub,format=string.gsub,string.format
-local sortedhash,concat=table.sortedhash,table.concat
-local finders,openers,loaders=resolvers.finders,resolvers.openers,resolvers.loaders
-local addsuffix,suffix,splitbase=file.addsuffix,file.suffix,file.splitbase
-local md5hex=md5.hex
-local trace_schemes=false trackers.register("resolvers.schemes",function(v) trace_schemes=v end)
-local report_schemes=logs.reporter("resolvers","schemes")
-local http=require("socket.http")
-local ltn12=require("ltn12")
-if mbox then mbox=nil end
-local resolvers=resolvers
-local schemes=resolvers.schemes or {}
-resolvers.schemes=schemes
-local cleaners={}
-schemes.cleaners=cleaners
-local threshold=24*60*60
-directives.register("schemes.threshold",function(v) threshold=tonumber(v) or threshold end)
-function cleaners.none(specification)
- return specification.original
-end
-function cleaners.strip(specification)
- local path,name=splitbase(specification.original)
- if path=="" then
- return (gsub(name,"[^%a%d%.]+","-"))
- else
- return (gsub((gsub(path,"%.","-").."-"..name),"[^%a%d%.]+","-"))
- end
-end
-function cleaners.md5(specification)
- return addsuffix(md5hex(specification.original),suffix(specification.path))
-end
-local cleaner=cleaners.strip
-directives.register("schemes.cleanmethod",function(v) cleaner=cleaners[v] or cleaners.strip end)
-function resolvers.schemes.cleanname(specification)
- local hash=cleaner(specification)
- if trace_schemes then
- report_schemes("hashing %a to %a",specification.original,hash)
- end
- return hash
-end
-local cached={}
-local loaded={}
-local reused={}
-local thresholds={}
-local handlers={}
-local runner=sandbox.registerrunner {
- name="curl resolver",
- method="execute",
- program="curl",
- template='--silent --insecure --create-dirs --output "%cachename%" "%original%"',
- checkers={
- cachename="cache",
- original="url",
- }
-}
-local function fetch(specification)
- local original=specification.original
- local scheme=specification.scheme
- local cleanname=schemes.cleanname(specification)
- local cachename=caches.setfirstwritablefile(cleanname,"schemes")
- if not cached[original] then
- statistics.starttiming(schemes)
- if not io.exists(cachename) or (os.difftime(os.time(),lfs.attributes(cachename).modification)>(thresholds[protocol] or threshold)) then
- cached[original]=cachename
- local handler=handlers[scheme]
- if handler then
- if trace_schemes then
- report_schemes("fetching %a, protocol %a, method %a",original,scheme,"built-in")
- end
- logs.flush()
- handler(specification,cachename)
- else
- if trace_schemes then
- report_schemes("fetching %a, protocol %a, method %a",original,scheme,"curl")
- end
- logs.flush()
- runner {
- original=original,
- cachename=cachename,
- }
- end
- end
- if io.exists(cachename) then
- cached[original]=cachename
- if trace_schemes then
- report_schemes("using cached %a, protocol %a, cachename %a",original,scheme,cachename)
- end
- else
- cached[original]=""
- if trace_schemes then
- report_schemes("using missing %a, protocol %a",original,scheme)
- end
- end
- loaded[scheme]=loaded[scheme]+1
- statistics.stoptiming(schemes)
- else
- if trace_schemes then
- report_schemes("reusing %a, protocol %a",original,scheme)
- end
- reused[scheme]=reused[scheme]+1
- end
- return cached[original]
-end
-local function finder(specification,filetype)
- return resolvers.methodhandler("finders",fetch(specification),filetype)
-end
-local opener=openers.file
-local loader=loaders.file
-local function install(scheme,handler,newthreshold)
- handlers [scheme]=handler
- loaded [scheme]=0
- reused [scheme]=0
- finders [scheme]=finder
- openers [scheme]=opener
- loaders [scheme]=loader
- thresholds[scheme]=newthreshold or threshold
-end
-schemes.install=install
-local function http_handler(specification,cachename)
- local tempname=cachename..".tmp"
- local handle=io.open(tempname,"wb")
- local status,message=http.request {
- url=specification.original,
- sink=ltn12.sink.file(handle)
- }
- if not status then
- os.remove(tempname)
- else
- os.remove(cachename)
- os.rename(tempname,cachename)
- end
- return cachename
-end
-install('http',http_handler)
-install('https')
-install('ftp')
-statistics.register("scheme handling time",function()
- local l,r,nl,nr={},{},0,0
- for k,v in sortedhash(loaded) do
- if v>0 then
- nl=nl+1
- l[nl]=k..":"..v
- end
- end
- for k,v in sortedhash(reused) do
- if v>0 then
- nr=nr+1
- r[nr]=k..":"..v
- end
- end
- local n=nl+nr
- if n>0 then
- if nl==0 then l={ "none" } end
- if nr==0 then r={ "none" } end
- return format("%s seconds, %s processed, threshold %s seconds, loaded: %s, reused: %s",
- statistics.elapsedtime(schemes),n,threshold,concat(l," "),concat(l," "))
- else
- return nil
- end
-end)
-local httprequest=http.request
-local toquery=url.toquery
-local function fetchstring(url,data)
- local q=data and toquery(data)
- if q then
- url=url.."?"..q
- end
- local reply=httprequest(url)
- return reply
-end
-schemes.fetchstring=fetchstring
-function schemes.fetchtable(url,data)
- local reply=fetchstring(url,data)
- if reply then
- local s=load("return "..reply)
- if s then
- return s()
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-lua"] = package.loaded["data-lua"] or true
-
--- original size: 4227, stripped down to: 3049
-
-if not modules then modules={} end modules ['data-lua']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local package,lpeg=package,lpeg
-local loadfile=loadfile
-local addsuffix=file.addsuffix
-local P,S,Cs,lpegmatch=lpeg.P,lpeg.S,lpeg.Cs,lpeg.match
-local luasuffixes={ 'tex','lua' }
-local libsuffixes={ 'lib' }
-local luaformats={ 'TEXINPUTS','LUAINPUTS' }
-local libformats={ 'CLUAINPUTS' }
-local helpers=package.helpers or {}
-local methods=helpers.methods or {}
-local resolvers=resolvers
-local resolveprefix=resolvers.resolve
-local expandedpaths=resolvers.expandedpathlistfromvariable
-local findfile=resolvers.findfile
-helpers.report=logs.reporter("resolvers","libraries")
-trackers.register("resolvers.libraries",function(v) helpers.trace=v end)
-trackers.register("resolvers.locating",function(v) helpers.trace=v end)
-helpers.sequence={
- "already loaded",
- "preload table",
- "lua variable format",
- "lib variable format",
- "lua extra list",
- "lib extra list",
- "path specification",
- "cpath specification",
- "all in one fallback",
- "not loaded",
-}
-local pattern=Cs(P("!")^0/""*(P("/")*P(-1)/"/"+P("/")^1/"/"+1)^0)
-function helpers.cleanpath(path)
- return resolveprefix(lpegmatch(pattern,path))
-end
-local loadedaslib=helpers.loadedaslib
-local registerpath=helpers.registerpath
-local lualibfile=helpers.lualibfile
-local luaformatpaths
-local libformatpaths
-local function getluaformatpaths()
- if not luaformatpaths then
- luaformatpaths={}
- for i=1,#luaformats do
- registerpath("lua format","lua",luaformatpaths,expandedpaths(luaformats[i]))
- end
- end
- return luaformatpaths
-end
-local function getlibformatpaths()
- if not libformatpaths then
- libformatpaths={}
- for i=1,#libformats do
- registerpath("lib format","lib",libformatpaths,expandedpaths(libformats[i]))
- end
- end
- return libformatpaths
-end
-local function loadedbyformat(name,rawname,suffixes,islib,what)
- local trace=helpers.trace
- local report=helpers.report
- for i=1,#suffixes do
- local format=suffixes[i]
- local resolved=findfile(name,format) or ""
- if trace then
- report("%s format, identifying %a using format %a",what,name,format)
- end
- if resolved~="" then
- if trace then
- report("%s format, %a found on %a",what,name,resolved)
- end
- if islib then
- return loadedaslib(resolved,rawname)
- else
- return loadfile(resolved)
- end
- end
- end
-end
-helpers.loadedbyformat=loadedbyformat
-methods["lua variable format"]=function(name)
- if helpers.trace then
- helpers.report("%s format, checking %s paths","lua",#getluaformatpaths())
- end
- return loadedbyformat(addsuffix(lualibfile(name),"lua"),name,luasuffixes,false,"lua")
-end
-methods["lib variable format"]=function(name)
- if helpers.trace then
- helpers.report("%s format, checking %s paths","lib",#getlibformatpaths())
- end
- return loadedbyformat(addsuffix(lualibfile(name),os.libsuffix),name,libsuffixes,true,"lib")
-end
-resolvers.loadlualib=require
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-aux"] = package.loaded["data-aux"] or true
-
--- original size: 2610, stripped down to: 2019
-
-if not modules then modules={} end modules ['data-aux']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local find=string.find
-local type,next=type,next
-local addsuffix,removesuffix=file.addsuffix,file.removesuffix
-local loaddata,savedata=io.loaddata,io.savedata
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local resolvers=resolvers
-local cleanpath=resolvers.cleanpath
-local findfiles=resolvers.findfiles
-local report_scripts=logs.reporter("resolvers","scripts")
-function resolvers.updatescript(oldname,newname)
- local scriptpath="context/lua"
- local oldscript=cleanpath(oldname)
- local newname=addsuffix(newname,"lua")
- local newscripts=findfiles(newname) or {}
- if trace_locating then
- report_scripts("to be replaced old script %a",oldscript)
- end
- if #newscripts==0 then
- if trace_locating then
- report_scripts("unable to locate new script")
- end
- else
- for i=1,#newscripts do
- local newscript=cleanpath(newscripts[i])
- if trace_locating then
- report_scripts("checking new script %a",newscript)
- end
- if oldscript==newscript then
- if trace_locating then
- report_scripts("old and new script are the same")
- end
- elseif not find(newscript,scriptpath,1,true) then
- if trace_locating then
- report_scripts("new script should come from %a",scriptpath)
- end
- elseif not (find(oldscript,removesuffix(newname).."$") or find(oldscript,newname.."$")) then
- if trace_locating then
- report_scripts("invalid new script name")
- end
- else
- local newdata=loaddata(newscript)
- if newdata then
- if trace_locating then
- report_scripts("old script content replaced by new content: %s",oldscript)
- end
- savedata(oldscript,newdata)
- break
- elseif trace_locating then
- report_scripts("unable to load new script")
- end
- end
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-tmf"] = package.loaded["data-tmf"] or true
-
--- original size: 2601, stripped down to: 1549
-
-if not modules then modules={} end modules ['data-tmf']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local resolvers=resolvers
-local report_tds=logs.reporter("resolvers","tds")
-function resolvers.load_tree(tree,resolve)
- if type(tree)=="string" and tree~="" then
- local getenv,setenv=resolvers.getenv,resolvers.setenv
- local texos="texmf-"..os.platform
- local oldroot=environment.texroot
- local newroot=file.collapsepath(tree)
- local newtree=file.join(newroot,texos)
- local newpath=file.join(newtree,"bin")
- if not lfs.isdir(newtree) then
- report_tds("no %a under tree %a",texos,tree)
- os.exit()
- end
- if not lfs.isdir(newpath) then
- report_tds("no '%s/bin' under tree %a",texos,tree)
- os.exit()
- end
- local texmfos=newtree
- environment.texroot=newroot
- environment.texos=texos
- environment.texmfos=texmfos
- if resolve then
- resolvers.luacnfspec=resolvers.resolve(resolvers.luacnfspec)
- end
- setenv('SELFAUTOPARENT',newroot)
- setenv('SELFAUTODIR',newtree)
- setenv('SELFAUTOLOC',newpath)
- setenv('TEXROOT',newroot)
- setenv('TEXOS',texos)
- setenv('TEXMFOS',texmfos)
- setenv('TEXMFCNF',resolvers.luacnfspec,true)
- setenv('PATH',newpath..io.pathseparator..getenv('PATH'))
- report_tds("changing from root %a to %a",oldroot,newroot)
- report_tds("prepending %a to PATH",newpath)
- report_tds("setting TEXMFCNF to %a",resolvers.luacnfspec)
- report_tds()
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-lst"] = package.loaded["data-lst"] or true
-
--- original size: 2038, stripped down to: 1696
-
-if not modules then modules={} end modules ['data-lst']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type=type
-local sortedhash=table.sortedhash
-local isdir=lfs.isdir
-local resolvers=resolvers
-local listers=resolvers.listers or {}
-resolvers.listers=listers
-local resolveprefix=resolvers.resolve
-local configurationfiles=resolvers.configurationfiles
-local expandedpathfromlist=resolvers.expandedpathfromlist
-local splitpath=resolvers.splitpath
-local knownvariables=resolvers.knownvariables
-local report_lists=logs.reporter("resolvers","lists")
-local report_resolved=logs.reporter("system","resolved")
-local function tabstr(str)
- if not str then
- return "unset"
- elseif type(str)=='table' then
- return concat(str," | ")
- else
- return str
- end
-end
-function listers.variables(pattern)
- local result=resolvers.knownvariables(pattern)
- for key,value in sortedhash(result) do
- report_lists(key)
- report_lists(" env: %s",tabstr(value.environment))
- report_lists(" var: %s",tabstr(value.variable))
- report_lists(" exp: %s",tabstr(value.expansion))
- report_lists(" res: %s",tabstr(value.resolved))
- end
-end
-function listers.configurations()
- local configurations=configurationfiles()
- for i=1,#configurations do
- report_resolved("file : %s",resolveprefix(configurations[i]))
- end
- report_resolved("")
- local list=expandedpathfromlist(splitpath(resolvers.luacnfspec))
- for i=1,#list do
- local li=resolveprefix(list[i])
- if isdir(li) then
- report_resolved("path - %s",li)
- else
- report_resolved("path + %s",li)
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["libs-ini"] = package.loaded["libs-ini"] or true
-
--- original size: 6459, stripped down to: 4006
-
-if not modules then modules={} end modules ['libs-ini']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,unpack=type,unpack
-local find=string.find
-local nameonly=file.nameonly
-local joinfile=file.join
-local addsuffix=file.addsuffix
-local qualifiedpath=file.is_qualified_path
-local isfile=lfs.isfile
-local findfile=resolvers.findfile
-local expandpaths=resolvers.expandedpathlistfromvariable
-local report=logs.reporter("resolvers","libraries")
-local trace=false
-local silent=false
-trackers.register("resolvers.lib",function(v) trace=v end)
-trackers.register("resolvers.lib.silent",function(v) silent=v end)
-local function findlib(required)
- local suffix=os.libsuffix or "so"
- if not qualifiedpath(required) then
- local list=directives.value("system.librarynames" )
- local only=nameonly(required)
- if type(list)=="table" then
- list=list[only]
- if type(list)~="table" then
- list={ only }
- end
- else
- list={ only }
- end
- if trace then
- report("using lookup list for library %a: % | t",only,list)
- end
- for i=1,#list do
- local name=list[i]
- local found=findfile(name,"lib")
- if not found then
- found=findfile(addsuffix(name,suffix),"lib")
- end
- if found then
- if trace then
- report("library %a resolved via %a path to %a",name,"tds lib",found)
- end
- return found
- end
- end
- if expandpaths then
- local list=expandpaths("PATH")
- local base=addsuffix(only,suffix)
- for i=1,#list do
- local full=joinfile(list[i],base)
- local found=isfile(full) and full
- if found then
- if trace then
- report("library %a resolved via %a path to %a",name,"system",found)
- end
- return found
- end
- end
- end
- elseif isfile(addsuffix(required,suffix)) then
- if trace then
- report("library with qualified name %a %sfound",required,"")
- end
- return required
- else
- if trace then
- report("library with qualified name %a %sfound",required,"not ")
- end
- end
- return false
-end
-local foundlibraries=table.setmetatableindex(function(t,k)
- local v=findlib(k)
- t[k]=v
- return v
-end)
-function resolvers.findlib(required)
- return foundlibraries[required]
-end
-local libraries={}
-resolvers.libraries=libraries
-local report=logs.reporter("optional")
-if optional then optional.loaded={} end
-function libraries.validoptional(name)
- local thelib=optional and optional[name]
- if not thelib then
- elseif thelib.initialize then
- return thelib
- else
- report("invalid optional library %a",libname)
- end
-end
-function libraries.optionalloaded(name,libnames)
- local thelib=optional and optional[name]
- if not thelib then
- report("no optional %a library found",name)
- else
- local thelib_initialize=thelib.initialize
- if not thelib_initialize then
- report("invalid optional library %a",name)
- else
- if type(libnames)=="string" then
- libnames={ libnames }
- end
- if type(libnames)=="table" then
- for i=1,#libnames do
- local libname=libnames[i]
- local filename=foundlibraries[libname]
- if filename then
- libnames[i]=filename
- else
- report("unable to locate library %a",libname)
- return
- end
- end
- local initialized=thelib_initialize(unpack(libnames))
- if not initialized then
- report("unable to initialize library '% + t'",libnames)
- elseif not silent then
- report("using library '% + t'",libnames)
- end
- return initialized
- end
- end
- end
-end
-if FFISUPPORTED and ffi and ffi.load then
- local ffiload=ffi.load
- function ffi.load(name)
- local full=name and foundlibraries[name]
- if full then
- return ffiload(full)
- else
- return ffiload(name)
- end
- end
-end
-local dofile=dofile
-local savedrequire=require
-function require(name,version)
- if find(name,"%.lua$") or find(name,"%.lmt$") then
- local m=dofile(findfile(name))
- if m then
- package.loaded[name]=m
- return m
- end
- else
- return savedrequire(name)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["luat-sta"] = package.loaded["luat-sta"] or true
-
--- original size: 5703, stripped down to: 2321
-
-if not modules then modules={} end modules ['luat-sta']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local gmatch,match=string.gmatch,string.match
-local type=type
-states=states or {}
-local states=states
-states.data=states.data or {}
-local data=states.data
-states.hash=states.hash or {}
-local hash=states.hash
-states.tag=states.tag or ""
-states.filename=states.filename or ""
-function states.save(filename,tag)
- tag=tag or states.tag
- filename=file.addsuffix(filename or states.filename,'lus')
- io.savedata(filename,
- "-- generator : luat-sta.lua\n".."-- state tag : "..tag.."\n\n"..table.serialize(data[tag or states.tag] or {},true)
- )
-end
-function states.load(filename,tag)
- states.filename=filename
- states.tag=tag or "whatever"
- states.filename=file.addsuffix(states.filename,'lus')
- data[states.tag],hash[states.tag]=(io.exists(filename) and dofile(filename)) or {},{}
-end
-local function set_by_tag(tag,key,value,default,persistent)
- local d,h=data[tag],hash[tag]
- if d then
- if type(d)=="table" then
- local dkey,hkey=key,key
- local pre,post=match(key,"(.+)%.([^%.]+)$")
- if pre and post then
- for k in gmatch(pre,"[^%.]+") do
- local dk=d[k]
- if not dk then
- dk={}
- d[k]=dk
- elseif type(dk)=="string" then
- break
- end
- d=dk
- end
- dkey,hkey=post,key
- end
- if value==nil then
- value=default
- elseif value==false then
- elseif persistent then
- value=value or d[dkey] or default
- else
- value=value or default
- end
- d[dkey],h[hkey]=value,value
- elseif type(d)=="string" then
- data[tag],hash[tag]=value,value
- end
- end
-end
-local function get_by_tag(tag,key,default)
- local h=hash[tag]
- if h and h[key] then
- return h[key]
- else
- local d=data[tag]
- if d then
- for k in gmatch(key,"[^%.]+") do
- local dk=d[k]
- if dk~=nil then
- d=dk
- else
- return default
- end
- end
- if d==false then
- return false
- else
- return d or default
- end
- end
- end
-end
-states.set_by_tag=set_by_tag
-states.get_by_tag=get_by_tag
-function states.set(key,value,default,persistent)
- set_by_tag(states.tag,key,value,default,persistent)
-end
-function states.get(key,default)
- return get_by_tag(states.tag,key,default)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["luat-fmt"] = package.loaded["luat-fmt"] or true
-
--- original size: 11691, stripped down to: 8350
-
-if not modules then modules={} end modules ['luat-fmt']={
- version=1.001,
- comment="companion to mtxrun",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local format=string.format
-local concat=table.concat
-local quoted=string.quoted
-local luasuffixes=utilities.lua.suffixes
-local report_format=logs.reporter("resolvers","formats")
-local function primaryflags(arguments)
- local flags={}
- if arguments.silent then
- flags[#flags+1]="--interaction=batchmode"
- end
- return concat(flags," ")
-end
-local function secondaryflags(arguments)
- local trackers=arguments.trackers
- local directives=arguments.directives
- local flags={}
- if trackers and trackers~="" then
- flags[#flags+1]="--c:trackers="..quoted(trackers)
- end
- if directives and directives~="" then
- flags[#flags+1]="--c:directives="..quoted(directives)
- end
- if arguments.silent then
- flags[#flags+1]="--c:silent"
- end
- if arguments.errors then
- flags[#flags+1]="--c:errors"
- end
- if arguments.ansi then
- flags[#flags+1]="--c:ansi"
- end
- if arguments.ansilog then
- flags[#flags+1]="--c:ansilog"
- end
- if arguments.strip then
- flags[#flags+1]="--c:strip"
- end
- if arguments.lmtx then
- flags[#flags+1]="--c:lmtx"
- end
- return concat(flags," ")
-end
-local template=[[--ini %primaryflags% --lua=%luafile% %texfile% %secondaryflags% %redirect%]]
-local checkers={
- primaryflags="verbose",
- secondaryflags="verbose",
- luafile="readable",
- texfile="readable",
- redirect="string",
- binarypath="string",
-}
-local runners={
- luametatex=sandbox.registerrunner {
- name="make luametatex format",
- program="luametatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luatex=sandbox.registerrunner {
- name="make luatex format",
- program="luatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luajittex=sandbox.registerrunner {
- name="make luajittex format",
- program="luajittex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
-}
-local stubfiles={
- luametatex="luat-cod.lmt",
- luatex="luat-cod.lua",
- luajittex="luat-cod.lua",
-}
-local suffixes={
- luametatex="mkxl",
- luatex="mkiv",
- luajittex="mkiv",
-}
-local function validbinarypath()
- if not environment.arguments.nobinarypath then
- local path=environment.ownpath or file.dirname(environment.ownname)
- if path and path~="" then
- path=dir.expandname(path)
- if path~="" and lfs.isdir(path) then
- return path
- end
- end
- end
-end
-local function fatalerror(startupdir,...)
- report_format(...)
- lfs.chdir(startupdir)
-end
-function environment.make_format(formatname)
- local arguments=environment.arguments
- local engine=environment.ownmain or "luatex"
- local silent=arguments.silent
- local errors=arguments.errors
- local runner=runners[engine]
- local startupdir=dir.current()
- if not runner then
- return fatalerror(startupdir,"the format %a cannot be generated, no runner available for engine %a",name,engine)
- end
- local luasourcename=stubfiles[engine]
- if not luasourcename then
- return fatalerror(startupdir,"no lua stub file specified for %a",engine)
- end
- local texsourcename=file.addsuffix(formatname,suffixes[engine])
- local fulltexsourcename=resolvers.findfile(texsourcename,"tex") or ""
- if fulltexsourcename=="" then
- return fatalerror(startupdir,"no tex source file with name %a (mkiv or tex)",formatname)
- end
- local fulltexsourcename=dir.expandname(fulltexsourcename)
- local texsourcepath=file.dirname(fulltexsourcename)
- if lfs.isfile(fulltexsourcename) then
- report_format("using tex source file %a",fulltexsourcename)
- else
- return fatalerror(startupdir,"no accessible tex source file with name %a",fulltexsourcename)
- end
- local fullluasourcename=dir.expandname(file.join(texsourcepath,luasourcename) or "")
- if lfs.isfile(fullluasourcename) then
- report_format("using lua stub file %a",fullluasourcename)
- else
- return fatalerror(startupdir,"no accessible lua stub file with name %a",fulltexsourcename)
- end
- local validformatpath=caches.getwritablepath("formats",engine) or ""
- if validformatpath=="" then
- return fatalerror(startupdir,"invalid format path, insufficient write access")
- end
- local binarypath=validbinarypath()
- report_format("changing to format path %a",validformatpath)
- if not lfs.chdir(validformatpath) then
- return fatalerror(startupdir,"unable to change to format path %a",validformatpath)
- end
- local primaryflags=primaryflags(arguments)
- local secondaryflags=secondaryflags(arguments)
- local specification={
- binarypath=binarypath,
- primaryflags=primaryflags,
- secondaryflags=secondaryflags,
- luafile=quoted(fullluasourcename),
- texfile=quoted(fulltexsourcename),
- }
- if silent then
- specification.redirect="> temp.log"
- end
- statistics.starttiming("format")
- local result=runner(specification)
- statistics.stoptiming("format")
- if silent then
- os.remove("temp.log")
- end
- report_format()
- if binarypath and binarypath~="" then
- report_format("binary path : %s",binarypath or "?")
- end
- report_format("format path : %s",validformatpath)
- report_format("luatex engine : %s",engine)
- report_format("lua startup file : %s",fullluasourcename)
- if primaryflags~="" then
- report_format("primary flags : %s",primaryflags)
- end
- if secondaryflags~="" then
- report_format("secondary flags : %s",secondaryflags)
- end
- report_format("context file : %s",fulltexsourcename)
- report_format("run time : %.3f seconds",statistics.elapsed("format"))
- report_format("return value : %s",result==0 and "okay" or "error")
- report_format()
- lfs.chdir(startupdir)
-end
-local template=[[%primaryflags% --fmt=%fmtfile% --lua=%luafile% %texfile% %secondaryflags%]]
-local checkers={
- primaryflags="verbose",
- secondaryflags="verbose",
- fmtfile="readable",
- luafile="readable",
- texfile="readable",
-}
-local runners={
- luatex=sandbox.registerrunner {
- name="run luatex format",
- program="luatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luametatex=sandbox.registerrunner {
- name="run luametatex format",
- program="luametatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luajittex=sandbox.registerrunner {
- name="run luajittex format",
- program="luajittex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
-}
-function environment.run_format(formatname,scriptname,filename,primaryflags,secondaryflags,verbose)
- local engine=environment.ownmain or "luatex"
- if not formatname or formatname=="" then
- report_format("missing format name")
- return
- end
- if not scriptname or scriptname=="" then
- report_format("missing script name")
- return
- end
- if not lfs.isfile(formatname) or not lfs.isfile(scriptname) then
- formatname,scriptname=resolvers.locateformat(formatname)
- end
- if not formatname or formatname=="" then
- report_format("invalid format name")
- return
- end
- if not scriptname or scriptname=="" then
- report_format("invalid script name")
- return
- end
- local runner=runners[engine]
- if not runner then
- report_format("format %a cannot be run, no runner available for engine %a",file.nameonly(name),engine)
- return
- end
- if not filename then
- filename ""
- end
- local binarypath=validbinarypath()
- local specification={
- binarypath=binarypath,
- primaryflags=primaryflags or "",
- secondaryflags=secondaryflags or "",
- fmtfile=quoted(formatname),
- luafile=quoted(scriptname),
- texfile=filename~="" and quoted(filename) or "",
- }
- statistics.starttiming("make format")
- local result=runner(specification)
- statistics.stoptiming("make format")
- if verbose then
- report_format()
- if binarypath and binarypath~="" then
- report_format("binary path : %s",binarypath)
- end
- report_format("luatex engine : %s",engine)
- report_format("lua startup file : %s",scriptname)
- report_format("tex format file : %s",formatname)
- if filename~="" then
- report_format("tex input file : %s",filename)
- end
- if primaryflags~="" then
- report_format("primary flags : %s",primaryflags)
- end
- if secondaryflags~="" then
- report_format("secondary flags : %s",secondaryflags)
- end
- report_format("run time : %0.3f seconds",statistics.elapsed("make format"))
- report_format("return value : %s",result==0 and "okay" or "error")
- report_format()
- end
- return result
-end
-
-
-end -- of closure
-
--- used libraries : l-bit32.lua l-lua.lua l-macro.lua l-sandbox.lua l-package.lua l-lpeg.lua l-function.lua l-string.lua l-table.lua l-io.lua l-number.lua l-set.lua l-os.lua l-file.lua l-gzip.lua l-md5.lua l-sha.lua l-url.lua l-dir.lua l-boolean.lua l-unicode.lua l-math.lua util-str.lua util-tab.lua util-fil.lua util-sac.lua util-sto.lua util-prs.lua util-fmt.lua util-soc-imp-reset.lua util-soc-imp-socket.lua util-soc-imp-copas.lua util-soc-imp-ltn12.lua util-soc-imp-mime.lua util-soc-imp-url.lua util-soc-imp-headers.lua util-soc-imp-tp.lua util-soc-imp-http.lua util-soc-imp-ftp.lua util-soc-imp-smtp.lua trac-set.lua trac-log.lua trac-inf.lua trac-pro.lua util-lua.lua util-deb.lua util-tpl.lua util-sbx.lua util-mrg.lua util-env.lua luat-env.lua util-zip.lua lxml-tab.lua lxml-lpt.lua lxml-mis.lua lxml-aux.lua lxml-xml.lua trac-xml.lua data-ini.lua data-exp.lua data-env.lua data-tmp.lua data-met.lua data-res.lua data-pre.lua data-inp.lua data-out.lua data-fil.lua data-con.lua data-use.lua data-zip.lua data-tre.lua data-sch.lua data-lua.lua data-aux.lua data-tmf.lua data-lst.lua libs-ini.lua luat-sta.lua luat-fmt.lua
--- skipped libraries : -
--- original bytes : 1025947
--- stripped bytes : 405652
-
--- end library merge
-
--- We need this hack till luatex is fixed.
---
--- for k,v in pairs(arg) do print(k,v) end
-
-if arg and (arg[0] == 'luatex' or arg[0] == 'luatex.exe') and arg[1] == "--luaonly" then
- arg[-1]=arg[0] arg[0]=arg[2] for k=3,#arg do arg[k-2]=arg[k] end arg[#arg]=nil arg[#arg]=nil
-end
-
--- End of hack.
-
-local format, gsub, gmatch, match, find = string.format, string.gsub, string.gmatch, string.match, string.find
-local concat = table.concat
-
-local ownname = environment and environment.ownname or arg[0] or 'mtxrun.lua'
-local ownpath = gsub(match(ownname,"^(.+)[\\/].-$") or ".","\\","/")
-local owntree = environment and environment.ownpath or ownpath
-
-local ownlibs = { -- order can be made better
-
- 'l-bit32.lua',
- 'l-lua.lua',
- 'l-macro.lua',
- 'l-sandbox.lua',
- 'l-package.lua',
- 'l-lpeg.lua',
- 'l-function.lua',
- 'l-string.lua',
- 'l-table.lua',
- 'l-io.lua',
- 'l-number.lua',
- 'l-set.lua',
- 'l-os.lua',
- 'l-file.lua',
- 'l-gzip.lua',
- 'l-md5.lua',
- 'l-sha.lua',
- 'l-url.lua',
- 'l-dir.lua',
- 'l-boolean.lua',
- 'l-unicode.lua',
- 'l-math.lua',
-
- 'util-str.lua', -- code might move to l-string
- 'util-tab.lua',
- 'util-fil.lua',
- 'util-sac.lua',
- 'util-sto.lua',
- 'util-prs.lua',
- 'util-fmt.lua',
-
- 'util-soc-imp-reset.lua',
- 'util-soc-imp-socket.lua',
- 'util-soc-imp-copas.lua',
- 'util-soc-imp-ltn12.lua',
- -- 'util-soc-imp-mbox.lua',
- 'util-soc-imp-mime.lua',
- 'util-soc-imp-url.lua',
- 'util-soc-imp-headers.lua',
- 'util-soc-imp-tp.lua',
- 'util-soc-imp-http.lua',
- 'util-soc-imp-ftp.lua',
- 'util-soc-imp-smtp.lua',
-
- 'trac-set.lua',
- 'trac-log.lua',
- 'trac-inf.lua', -- was before trac-set
- 'trac-pro.lua', -- not really needed
- 'util-lua.lua', -- indeed here?
- 'util-deb.lua',
-
- 'util-tpl.lua',
- 'util-sbx.lua',
- 'util-mrg.lua',
-
- 'util-env.lua',
- 'luat-env.lua', -- can come before inf (as in mkiv)
-
- 'util-zip.lua',
-
- 'lxml-tab.lua',
- 'lxml-lpt.lua',
- -- 'lxml-ent.lua',
- 'lxml-mis.lua',
- 'lxml-aux.lua',
- 'lxml-xml.lua',
-
- 'trac-xml.lua',
-
- 'data-ini.lua',
- 'data-exp.lua',
- 'data-env.lua',
- 'data-tmp.lua',
- 'data-met.lua',
- 'data-res.lua',
- 'data-pre.lua',
- 'data-inp.lua',
- 'data-out.lua',
- 'data-fil.lua',
- 'data-con.lua',
- 'data-use.lua',
--- 'data-tex.lua',
--- 'data-bin.lua',
- 'data-zip.lua',
- 'data-tre.lua',
- 'data-sch.lua',
- 'data-lua.lua',
- 'data-aux.lua', -- updater
- 'data-tmf.lua',
- 'data-lst.lua',
-
- 'libs-ini.lua',
-
- 'luat-sta.lua',
- 'luat-fmt.lua',
-
-}
-
--- c:/data/develop/tex-context/tex/texmf-win64/bin/../../texmf-context/tex/context/base/mkiv/data-tmf.lua
--- c:/data/develop/context/sources/data-tmf.lua
-
-local ownlist = {
- -- '.',
- -- ownpath ,
- owntree .. "/../../../../context/sources", -- HH's development path
- --
- owntree .. "/../../texmf-local/tex/context/base/mkiv",
- owntree .. "/../../texmf-context/tex/context/base/mkiv",
- owntree .. "/../../texmf/tex/context/base/mkiv",
- owntree .. "/../../../texmf-local/tex/context/base/mkiv",
- owntree .. "/../../../texmf-context/tex/context/base/mkiv",
- owntree .. "/../../../texmf/tex/context/base/mkiv",
- --
- owntree .. "/../../texmf-local/tex/context/base",
- owntree .. "/../../texmf-context/tex/context/base",
- owntree .. "/../../texmf/tex/context/base",
- owntree .. "/../../../texmf-local/tex/context/base",
- owntree .. "/../../../texmf-context/tex/context/base",
- owntree .. "/../../../texmf/tex/context/base",
-}
-
-if ownpath == "." then table.remove(ownlist,1) end
-
-own = {
- name = ownname,
- path = ownpath,
- tree = owntree,
- list = ownlist,
- libs = ownlibs,
-}
-
-local function locate_libs()
- for l=1,#ownlibs do
- local lib = ownlibs[l]
- for p =1,#ownlist do
- local pth = ownlist[p]
- local filename = pth .. "/" .. lib
- local found = lfs.isfile(filename)
- if found then
- package.path = package.path .. ";" .. pth .. "/?.lua" -- in case l-* does a require
- return pth
- end
- end
- end
-end
-
-local function load_libs()
- local found = locate_libs()
- if found then
- for l=1,#ownlibs do
- local filename = found .. "/" .. ownlibs[l]
- local codeblob = loadfile(filename)
- if codeblob then
- codeblob()
- end
- end
- else
- resolvers = nil
- end
-end
-
-if not resolvers then
- load_libs()
-end
-
-if not resolvers then
- print("")
- print("Mtxrun is unable to start up due to lack of libraries. You may")
- print("try to run 'lua mtxrun.lua --selfmerge' in the path where this")
- print("script is located (normally under ..../scripts/context/lua) which")
- print("will make this script library independent.")
- os.exit()
-end
-
--- verbosity
-
------ e_verbose = environment.arguments["verbose"]
-
-local e_verbose = false
-
--- some common flags (also passed through environment)
-
-local e_silent = environment.argument("silent")
-local e_errors = environment.argument("errors")
-local e_noconsole = environment.argument("noconsole")
-
-local e_trackers = environment.argument("trackers")
-local e_directives = environment.argument("directives")
-local e_experiments = environment.argument("experiments")
-
-local t = { }
-
-if type(e_directives) == "string" then
- t[#t+1] = e_directives
-end
-
-if type(e_silent) == "string" then
- t[#t+1] = format("logs.blocked={%s}",e_silent)
-elseif e_silent == true then
- t[#t+1] = "logs.blocked"
-end
-
-if type(e_errors) == "string" then
- t[#t+1] = format("logs.errors={%s}",e_errors)
-elseif e_errors == true then
- t[#t+1] = "logs.errors"
-end
-
-if e_noconsole then
- t[#t+1] = format("logs.target=file")
-end
-
-if #t > 0 then
- e_directives = concat(t,",")
-end
-
-if e_trackers then trackers .enable(e_trackers) end
-if e_directives then directives .enable(e_directives) end
-if e_experiments then experiments.enable(e_experiments) end
-
-if not environment.trackers then environment.trackers = e_trackers end
-if not environment.directives then environment.directives = e_directives end
-if not environment.experiments then environment.experiments = e_experiments end
-
---
-
-resolvers.reset()
-
-local helpinfo = [[
-<?xml version="1.0" ?>
-<application>
- <metadata>
- <entry name="name">mtxrun</entry>
- <entry name="detail">ConTeXt TDS Runner Tool</entry>
- <entry name="version">1.33</entry>
- </metadata>
- <flags>
- <category name="basic">
- <subcategory>
- <flag name="script"><short>run an mtx script (lua prefered method) (<ref name="noquotes"/>), no script gives list</short></flag>
- <flag name="evaluate"><short>run code passed on the commandline (between quotes) (=loop) (exit|quit aborts)</short></flag>
- <flag name="execute"><short>run a script or program (texmfstart method) (<ref name="noquotes"/>)</short></flag>
- <flag name="resolve"><short>resolve prefixed arguments</short></flag>
- <flag name="ctxlua"><short>run internally (using preloaded libs)</short></flag>
- <flag name="internal"><short>run script using built in libraries (same as <ref name="ctxlua"/>)</short></flag>
- <flag name="locate"><short>locate given filename in database (default) or system (<ref name="first"/> <ref name="all"/> <ref name="detail"/>)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="tree" value="pathtotree"><short>use given texmf tree (default file: setuptex.tmf)</short></flag>
- <flag name="path" value="runpath"><short>go to given path before execution</short></flag>
- <flag name="ifchanged" value="filename"><short>only execute when given file has changed (md checksum)</short></flag>
- <flag name="iftouched" value="old,new"><short>only execute when given file has changed (time stamp)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="makestubs"><short>create stubs for (context related) scripts</short></flag>
- <flag name="removestubs"><short>remove stubs (context related) scripts</short></flag>
- <flag name="stubpath" value="binpath"><short>paths where stubs wil be written</short></flag>
- <flag name="windows"><short>create windows (mswin) stubs</short></flag>
- <flag name="unix"><short>create unix (linux) stubs</short></flag>
- <flag name="addbinarypath"><short>prepend the (found) binarypath to runners</short></flag>
- </subcategory>
- <subcategory>
- <flag name="verbose"><short>give a bit more info</short></flag>
- <flag name="trackers" value="list"><short>enable given trackers</short></flag>
- <flag name="progname" value="str"><short>format or backend</short></flag>
- <flag name="systeminfo" value="str"><short>show current operating system, processor, etc</short></flag>
- </subcategory>
- <subcategory>
- <flag name="edit"><short>launch editor with found file</short></flag>
- <flag name="launch"><short>launch files like manuals, assumes os support (<ref name="all"/>,<ref name="list"/>)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="timedrun"><short>run a script and time its run</short></flag>
- <flag name="autogenerate"><short>regenerate databases if needed (handy when used to run context in an editor)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="usekpse"><short>use kpse as fallback (when no mkiv and cache installed, often slower)</short></flag>
- <flag name="forcekpse"><short>force using kpse (handy when no mkiv and cache installed but less functionality)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="prefixes"><short>show supported prefixes</short></flag>
- </subcategory>
- <subcategory>
- <flag name="generate"><short>generate file database</short></flag>
- </subcategory>
- <subcategory>
- <flag name="variables"><short>show configuration variables</short></flag>
- <flag name="configurations"><short>show configuration order</short></flag>
- </subcategory>
- <subcategory>
- <flag name="directives"><short>show (known) directives</short></flag>
- <flag name="trackers"><short>show (known) trackers</short></flag>
- <flag name="experiments"><short>show (known) experiments</short></flag>
- </subcategory>
- <subcategory>
- <flag name="expand-braces"><short>expand complex variable</short></flag>
- <flag name="resolve-path"><short>expand variable (completely resolve paths)</short></flag>
- <flag name="expand-path"><short>expand variable (resolve paths)</short></flag>
- <flag name="expand-var"><short>expand variable (resolve references)</short></flag>
- <flag name="show-path"><short>show path expansion of ...</short></flag>
- <flag name="var-value"><short>report value of variable</short></flag>
- <flag name="find-file"><short>report file location</short></flag>
- <flag name="find-path"><short>report path of file</short></flag>
- </subcategory>
- <subcategory>
- <flag name="pattern" value="string"><short>filter variables</short></flag>
- </subcategory>
- </category>
- </flags>
-</application>
-]]
-
-local application = logs.application {
- name = "mtxrun",
- banner = "ConTeXt TDS Runner Tool 1.32",
- helpinfo = helpinfo,
-}
-
-local report = application.report
-
-messages = messages or { } -- for the moment
-
-runners = runners or { } -- global (might become local)
-
-runners.applications = {
- ["lua"] = "luatex --luaonly",
- ["luc"] = "luatex --luaonly",
- ["pl"] = "perl",
- ["py"] = "python",
- ["rb"] = "ruby",
-}
-
-runners.suffixes = {
- 'rb', 'lua', 'py', 'pl'
-}
-
-runners.registered = {
- texexec = { 'texexec.rb', false }, -- context mkii runner (only tool not to be luafied)
- texutil = { 'texutil.rb', true }, -- old perl based index sorter for mkii (old versions need it)
- texfont = { 'texfont.pl', true }, -- perl script that makes mkii font metric files
- texfind = { 'texfind.pl', false }, -- perltk based tex searching tool, mostly used at pragma
- texshow = { 'texshow.pl', false }, -- perltk based context help system, will be luafied
- -- texwork = { 'texwork.pl', false }, -- perltk based editing environment, only used at pragma
- makempy = { 'makempy.pl', true },
- mptopdf = { 'mptopdf.pl', true },
- pstopdf = { 'pstopdf.rb', true }, -- converts ps (and some more) images, does some cleaning (replaced)
- -- examplex = { 'examplex.rb', false },
- concheck = { 'concheck.rb', false },
- runtools = { 'runtools.rb', true },
- textools = { 'textools.rb', true },
- tmftools = { 'tmftools.rb', true },
- ctxtools = { 'ctxtools.rb', true },
- rlxtools = { 'rlxtools.rb', true },
- pdftools = { 'pdftools.rb', true },
- mpstools = { 'mpstools.rb', true },
- -- exatools = { 'exatools.rb', true },
- xmltools = { 'xmltools.rb', true },
- -- luatools = { 'luatools.lua', true },
- mtxtools = { 'mtxtools.rb', true },
- pdftrimwhite = { 'pdftrimwhite.pl', false },
-}
-
-runners.launchers = {
- windows = { },
- unix = { },
-}
-
--- like runners.libpath("framework"): looks on script's subpath
-
-function runners.libpath(...)
- package.prepend_libpath(file.dirname(environment.ownscript),...)
- package.prepend_libpath(file.dirname(environment.ownname) ,...)
-end
-
-function runners.prepare()
- local checkname = environment.argument("ifchanged")
- if type(checkname) == "string" and checkname ~= "" then
- local oldchecksum = file.loadchecksum(checkname)
- local newchecksum = file.checksum(checkname)
- if oldchecksum == newchecksum then
- if e_verbose then
- report("file '%s' is unchanged",checkname)
- end
- return "skip"
- elseif e_verbose then
- report("file '%s' is changed, processing started",checkname)
- end
- file.savechecksum(checkname)
- end
- local touchname = environment.argument("iftouched")
- if type(touchname) == "string" and touchname ~= "" then
- local oldname, newname = string.splitup(touchname, ",")
- if oldname and newname and oldname ~= "" and newname ~= "" then
- if not file.needs_updating(oldname,newname) then
- if e_verbose then
- report("file '%s' and '%s' have same age",oldname,newname)
- end
- return "skip"
- elseif e_verbose then
- report("file '%s' is older than '%s'",oldname,newname)
- end
- end
- end
- local runpath = environment.argument("path")
- if type(runpath) == "string" and not lfs.chdir(runpath) then
- report("unable to change to path '%s'",runpath)
- return "error"
- end
- runners.prepare = function() end
- return "run"
-end
-
-function runners.execute_script(fullname,internal,nosplit)
- local noquote = environment.argument("noquotes")
- if fullname and fullname ~= "" then
- local state = runners.prepare()
- if state == 'error' then
- return false
- elseif state == 'skip' then
- return true
- elseif state == "run" then
- local path, name, suffix = file.splitname(fullname)
- local result = ""
- if path ~= "" then
- result = fullname
- elseif name then
- name = gsub(name,"^int[%a]*:",function()
- internal = true
- return ""
- end )
- name = gsub(name,"^script:","")
- if suffix == "" and runners.registered[name] and runners.registered[name][1] then
- name = runners.registered[name][1]
- suffix = file.suffix(name)
- end
- if suffix == "" then
- -- loop over known suffixes
- for _,s in pairs(runners.suffixes) do
- result = resolvers.findfile(name .. "." .. s, 'texmfscripts')
- if result ~= "" then
- break
- end
- end
- elseif runners.applications[suffix] then
- result = resolvers.findfile(name, 'texmfscripts')
- else
- -- maybe look on path
- result = resolvers.findfile(name, 'other text files')
- end
- end
- if result and result ~= "" then
- if not no_split then
- local before, after = environment.splitarguments(fullname) -- already done
- environment.arguments_before, environment.arguments_after = before, after
- end
- if internal then
- arg = { } for _,v in pairs(environment.arguments_after) do arg[#arg+1] = v end
- environment.ownscript = result
- dofile(result)
- else
-local texmfcnf = resolvers.getenv("TEXMFCNF")
-if not texmfcnf or texmfcnf == "" then
- texmfcnf = resolvers.expandedpathfromlist(resolvers.splitpath(resolvers.resolve(resolvers.luacnfspec)))
- resolvers.setenv("TEXMFCNF",table.concat(texmfcnf,";")) -- for running texexec etc (after tl change to texmf-dist)
-end
- local binary = runners.applications[file.suffix(result)]
- result = string.quoted(string.unquoted(result))
- -- if string.match(result,' ') and not string.match(result,"^\".*\"$") then
- -- result = '"' .. result .. '"'
- -- end
- if binary and binary ~= "" then
- result = binary .. " " .. result
- end
- local command = result .. " " .. environment.reconstructcommandline(environment.arguments_after,noquote)
- if e_verbose then
- report()
- report("executing: %s",command)
- report()
- report()
- io.flush()
- end
- local code = os.execute(command)
- if code == 0 then
- return true
- else
- if binary then
- binary = file.addsuffix(binary,os.binsuffix)
- for p in gmatch(os.getenv("PATH"),"[^"..io.pathseparator.."]+") do
- if lfs.isfile(file.join(p,binary)) then
- return false
- end
- end
- report()
- report("This script needs '%s' which seems not to be installed.",binary)
- report()
- end
- return false
- end
- end
- end
- end
- end
- return false
-end
-
-function runners.execute_program(fullname)
- local noquote = environment.argument("noquotes")
- if fullname and fullname ~= "" then
- local state = runners.prepare()
- if state == 'error' then
- return false
- elseif state == 'skip' then
- return true
- elseif state == "run" then
- local before, after = environment.splitarguments(fullname)
- for k=1,#after do after[k] = resolvers.resolve(after[k]) end
- environment.initializearguments(after)
- fullname = gsub(fullname,"^bin:","")
- local command = fullname .. " " .. (environment.reconstructcommandline(after or "",noquote) or "")
- report()
- report("executing: %s",command)
- report()
- report()
- io.flush()
- local code = os.execute(command)
- return code == 0
- end
- end
- return false
-end
-
--- the --usekpse flag will fallback (not default) on kpse (hm, we can better update mtx-stubs)
-
-local windows_stub = '@echo off\013\010setlocal\013\010set ownpath=%%~dp0%%\013\010texlua "%%ownpath%%mtxrun.lua" --usekpse --execute %s %%*\013\010endlocal\013\010'
-local unix_stub = '#!/bin/sh\010mtxrun --usekpse --execute %s \"$@\"\010'
-
-function runners.handle_stubs(create)
- local stubpath = environment.argument('stubpath') or '.' -- 'auto' no longer subpathssupported
- local windows = environment.argument('windows') or environment.argument('mswin') or false
- local unix = environment.argument('unix') or environment.argument('linux') or false
- if not windows and not unix then
- if os.platform == "unix" then
- unix = true
- else
- windows = true
- end
- end
- for _,v in pairs(runners.registered) do
- local name, doit = v[1], v[2]
- if doit then
- local base = gsub(file.basename(name), "%.(.-)$", "")
- if create then
- if windows then
- io.savedata(file.join(stubpath,base..".bat"),format(windows_stub,name))
- report("windows stub for '%s' created",base)
- end
- if unix then
- io.savedata(file.join(stubpath,base),format(unix_stub,name))
- report("unix stub for '%s' created",base)
- end
- else
- if windows and (os.remove(file.join(stubpath,base..'.bat')) or os.remove(file.join(stubpath,base..'.cmd'))) then
- report("windows stub for '%s' removed", base)
- end
- if unix and (os.remove(file.join(stubpath,base)) or os.remove(file.join(stubpath,base..'.sh'))) then
- report("unix stub for '%s' removed",base)
- end
- end
- end
- end
-end
-
-function runners.resolve_string(filename)
- if filename and filename ~= "" then
- runners.report_location(resolvers.resolve(filename))
- end
-end
-
--- differs from texmfstart where locate appends .com .exe .bat ... todo
-
-function runners.locate_file(filename) -- was given file but only searches in tree
- if filename and filename ~= "" then
- if environment.argument("first") then
- runners.report_location(resolvers.findfile(filename))
- -- resolvers.dowithfilesandreport(resolvers.findfile,filename)
- elseif environment.argument("all") then
- local result, status = resolvers.findfiles(filename)
- if status and environment.argument("detail") then
- runners.report_location(status)
- else
- runners.report_location(result)
- end
- else
- runners.report_location(resolvers.findgivenfile(filename))
- -- resolvers.dowithfilesandreport(resolvers.findgivenfile,filename)
- end
- end
-end
-
-function runners.locate_platform()
- runners.report_location(os.platform)
-end
-
-function runners.report_location(result)
- if type(result) == "table" then
- for i=1,#result do
- if i > 1 then
- io.write("\n")
- end
- io.write(result[i])
- end
- else
- io.write(result)
- end
-end
-
-function runners.edit_script(filename) -- we assume that gvim is present on most systems (todo: also in cnf file)
- local editor = os.getenv("MTXRUN_EDITOR") or os.getenv("TEXMFSTART_EDITOR") or os.getenv("EDITOR") or 'gvim'
- local rest = resolvers.resolve(filename)
- if rest ~= "" then
- local command = editor .. " " .. rest
- if e_verbose then
- report()
- report("starting editor: %s",command)
- report()
- report()
- end
- os.launch(command)
- end
-end
-
-function runners.save_script_session(filename, list)
- if type(list) == "table" then
- local t = { }
- for i=1,#list do
- local key = list[i]
- t[key] = environment.arguments[key]
- end
- io.savedata(filename,table.serialize(t,true))
- end
-end
-
-function runners.load_script_session(filename)
- if lfs.isfile(filename) then
- local t = io.loaddata(filename)
- if t then
- t = loadstring(t)
- if t then t = t() end
- for key, value in pairs(t) do
- environment.arguments[key] = value
- end
- end
- end
-end
-
-function resolvers.launch(str)
- -- maybe we also need to test on mtxrun.launcher.suffix environment
- -- variable or on windows consult the assoc and ftype vars and such
- local launchers = runners.launchers[os.platform] if launchers then
- local suffix = file.suffix(str) if suffix then
- local runner = launchers[suffix] if runner then
- str = runner .. " " .. str
- end
- end
- end
- os.launch(str)
-end
-
-function runners.launch_file(filename)
- local allresults = environment.arguments["all"]
- local pattern = environment.arguments["pattern"]
- local listonly = environment.arguments["list"]
- if not pattern or pattern == "" then
- pattern = filename
- end
- if not pattern or pattern == "" then
- report("provide name or --pattern=")
- else
- local t = resolvers.findfiles(pattern,nil,allresults)
- if not t or #t == 0 then
- t = resolvers.findfiles("*/" .. pattern,nil,allresults)
- end
- if not t or #t == 0 then
- t = resolvers.findfiles("*/" .. pattern .. "*",nil,allresults)
- end
- if t and #t > 0 then
- for i=1,#t do
- local name = t[i]
- if listonly then
- report("% 3i: %-30s %s",i,file.basename(name),file.dirname(name))
- else
- report("launching: %s",name)
- resolvers.launch(name)
- if not allresults then
- break
- end
- end
- end
- if listonly then
- io.write("\n")
- io.write("\n[select number]\n\n>> ")
- local answer = tonumber(io.read())
- if answer then
- io.write("\n")
- local name = t[answer]
- if name then
- report("launching: %s",name)
- resolvers.launch(name)
- else
- report("invalid number")
- end
- end
- end
- else
- report("no match for %s", pattern)
- end
- end
-end
-
-local mtxprefixes = {
- { "^mtx%-", "mtx-" },
- { "^mtx%-t%-", "mtx-t-" },
-}
-
-function runners.find_mtx_script(filename)
- local function found(name)
- local path = file.dirname(name)
- if path and path ~= "" then
- return false
- else
- local fullname = own and own.path and file.join(own.path,name)
- return io.exists(fullname) and fullname
- end
- end
- filename = file.addsuffix(filename,"lua")
- local basename = file.removesuffix(file.basename(filename))
- local suffix = file.suffix(filename)
- -- qualified path, raw name
- local fullname = file.is_qualified_path(filename) and io.exists(filename) and filename
- if fullname and fullname ~= "" then
- return fullname
- end
- -- current path, raw name
- fullname = "./" .. filename
- fullname = io.exists(fullname) and fullname
- if fullname and fullname ~= "" then
- return fullname
- end
- -- mtx- prefix checking
- for i=1,#mtxprefixes do
- local mtxprefix = mtxprefixes[i]
- mtxprefix = find(filename,mtxprefix[1]) and "" or mtxprefix[2]
- -- context namespace, mtx-<filename>
- fullname = mtxprefix .. filename
- fullname = found(fullname) or resolvers.findfile(fullname)
- if fullname and fullname ~= "" then
- return fullname
- end
- -- context namespace, mtx-<filename>s
- fullname = mtxprefix .. basename .. "s" .. "." .. suffix
- fullname = found(fullname) or resolvers.findfile(fullname)
- if fullname and fullname ~= "" then
- return fullname
- end
- -- context namespace, mtx-<filename minus trailing s>
- fullname = mtxprefix .. gsub(basename,"s$","") .. "." .. suffix
- fullname = found(fullname) or resolvers.findfile(fullname)
- if fullname and fullname ~= "" then
- return fullname
- end
- end
- -- context namespace, just <filename>
- fullname = resolvers.findfile(filename)
- return fullname
-end
-
-function runners.register_arguments(...)
- local arguments = environment.arguments_after
- local passedon = { ... }
- for i=#passedon,1,-1 do
- local pi = passedon[i]
- if pi then
- table.insert(arguments,1,pi)
- end
- end
-end
-
-function runners.execute_ctx_script(filename,...)
- runners.register_arguments(...)
- local arguments = environment.arguments_after
- local fullname = runners.find_mtx_script(filename) or ""
- if file.suffix(fullname) == "cld" then
- -- handy in editors where we force --autopdf
- report("running cld script: %s",filename)
- table.insert(arguments,1,fullname)
- table.insert(arguments,"--autopdf")
- fullname = runners.find_mtx_script("context") or ""
- end
- -- retry after generate but only if --autogenerate
- if fullname == "" and environment.argument("autogenerate") then -- might become the default
- resolvers.renewcache()
- trackers.enable("resolvers.locating")
- resolvers.load()
- --
- fullname = runners.find_mtx_script(filename) or ""
- end
- -- that should do it
- if fullname ~= "" then
- local state = runners.prepare()
- if state == 'error' then
- return false
- elseif state == 'skip' then
- return true
- elseif state == "run" then
- -- load and save ... kind of undocumented
- arg = { } for _,v in pairs(arguments) do arg[#arg+1] = resolvers.resolve(v) end
- environment.initializearguments(arg)
- local loadname = environment.arguments['load']
- if loadname then
- if type(loadname) ~= "string" then loadname = file.basename(fullname) end
- loadname = file.replacesuffix(loadname,"cfg")
- runners.load_script_session(loadname)
- end
- filename = environment.files[1]
- if e_verbose then
- report("using script: %s (if --path is used don't run on path where mtxrun lives)\n",fullname)
- end
- environment.ownscript = fullname
- dofile(fullname)
- local savename = environment.arguments['save']
- if savename then
- if type(savename) ~= "string" then savename = file.basename(fullname) end
- savename = file.replacesuffix(savename,"cfg")
- runners.save_script_session(savename,save_list)
- end
- return true
- end
- else
- if filename == "" or filename == "help" then
- local context = resolvers.findfile("mtx-context.lua")
- trackers.enable("resolvers.locating")
- if context ~= "" then
- local result = dir.glob((gsub(context,"mtx%-context","mtx-*"))) -- () needed
- local valid = { }
- table.sort(result)
- for i=1,#result do
- local scriptname = result[i]
- local scriptbase = match(scriptname,".*mtx%-([^%-]-)%.lua")
- if scriptbase then
- local data = io.loaddata(scriptname)
- local application = match(data,"local application.-=.-(%{.-%})")
- if application then
- application = loadstring("return " .. application)
- if application then
- application = application()
- local banner = application.banner
- if banner then
- local description, version = match(banner,"^(.-) ([%d.]+)$")
- if description then
- valid[#valid+1] = { scriptbase, version, description }
- else
- valid[#valid+1] = { scriptbase, "", banner }
- end
- end
- end
- end
- end
- end
- if #valid > 0 then
- application.identify()
- report("no script name given, known scripts:")
- report()
- for k=1,#valid do
- local v = valid[k]
- report("%-12s %4s %s",v[1],v[2],v[3])
- end
- end
- else
- report("no script name given")
- end
- else
- filename = file.addsuffix(filename,"lua")
- if file.is_qualified_path(filename) then
- report("unknown script '%s'",filename)
- else
- report("unknown script '%s' or 'mtx-%s'",filename,filename)
- end
- end
- return false
- end
-end
-
-function runners.prefixes()
- application.identify()
- report()
- report(concat(resolvers.allprefixes(true)," "))
-end
-
-function runners.timedrun(filename) -- just for me
- if filename and filename ~= "" then
- runners.timed(function() os.execute(filename) end)
- end
-end
-
-function runners.timed(action)
- statistics.timed(action,true)
-end
-
-function runners.associate(filename)
- os.launch(filename)
-end
-
-function runners.evaluate(code,filename) -- for Luigi
- local environment = table.setmetatableindex(_G)
- if code == "loop" then
- while true do
- io.write("lua > ")
- local code = io.read()
- if code == "quit" or code == "exit" then
- break
- elseif code ~= "" then
- local temp = string.match(code,"^= (.*)$")
- if temp then
- code = "inspect("..temp..")"
- end
- local compiled, message = load(code,"console","t",environment)
- if type(compiled) ~= "function" then
- compiled = load("inspect("..code..")","console","t",environment)
- end
- if type(compiled) ~= "function" then
- io.write("! " .. (message or code).."\n")
- else
- io.write(compiled())
- end
- end
- end
- else
- if type(code) ~= "string" or code == "" then
- code = filename
- end
- if code ~= "" then
- local compiled, message = load(code,"console","t",environment)
- if type(compiled) ~= "function" then
- compiled = load("inspect("..code..")","console","t",environment)
- end
- if type(compiled) ~= "function" then
- io.write("invalid lua code: " .. (message or code))
- return
- end
- io.write(compiled())
- end
- end
-end
-
-function runners.gethelp(filename)
- local url = environment.argument("url")
- if url and url ~= "" then
- local command = string.gsub(environment.argument("command") or "unknown","^%s*\\*(.-)%s*$","%1")
- url = utilities.templates.replace(url,{ command = command })
- os.launch(url)
- else
- report("no --url given")
- end
-end
-
-function runners.systeminfo()
- report("architecture : %s",os.platform or "<unset>")
- report("operating system : %s",os.name or "<unset>")
- report("file architecture : %s",os.type or "<unset>")
- report("binary path : %s",os.selfdir or "<unset>")
- report("binary suffix : %s",os.binsuffix or "<unset>")
- report("library suffix : %s",os.libsuffix or "<unset>")
-end
-
--- this is a bit dirty ... first we store the first filename and next we
--- split the arguments so that we only see the ones meant for this script
--- ... later we will use the second half
-
-local filename = environment.files[1] or ""
-local ok = true
-
-local before, after = environment.splitarguments(filename)
-environment.arguments_before, environment.arguments_after = before, after
-environment.initializearguments(before)
-
-e_verbose = environment.arguments["verbose"] -- delayed till here (we need the ones before script)
-
-if e_verbose then
- trackers.enable("resolvers.locating")
-end
-
--- maybe the unset has to go to this level
-
-local is_mkii_stub = runners.registered[file.removesuffix(file.basename(filename))]
-
-local e_argument = environment.argument
-
-if e_argument("timedlog") then
- logs.settimedlog()
-end
-
-if e_argument("usekpse") or e_argument("forcekpse") or is_mkii_stub then
-
- resolvers.load_tree(e_argument('tree'),true) -- force resolve of TEXMFCNF
-
- os.setenv("engine","")
- os.setenv("progname","")
-
- local remapper = {
- otf = "opentype fonts",
- ttf = "truetype fonts",
- ttc = "truetype fonts",
- pfb = "type1 fonts",
- other = "other text files",
- }
-
- local progname = e_argument("progname") or 'context'
-
- local function kpse_initialized()
- texconfig.kpse_init = true
- local t = os.clock()
- local k = kpse.original.new("luatex",progname)
- local dummy = k:find_file("mtxrun.lua") -- so that we're initialized
- report("kpse fallback with progname '%s' initialized in %s seconds",progname,os.clock()-t)
- kpse_initialized = function() return k end
- return k
- end
-
- local findfile = resolvers.findfile
- local showpath = resolvers.showpath
-
- if e_argument("forcekpse") then
-
- function resolvers.findfile(name,kind)
- return (kpse_initialized():find_file(resolvers.cleanpath(name),(kind ~= "" and (remapper[kind] or kind)) or "tex") or "") or ""
- end
- function resolvers.showpath(name)
- return (kpse_initialized():show_path(name)) or ""
- end
-
- elseif e_argument("usekpse") or is_mkii_stub then
-
- resolvers.load()
-
- function resolvers.findfile(name,kind)
- local found = findfile(name,kind) or ""
- if found ~= "" then
- return found
- else
- return (kpse_initialized():find_file(resolvers.cleanpath(name),(kind ~= "" and (remapper[kind] or kind)) or "tex") or "") or ""
- end
- end
- function resolvers.showpath(name)
- local found = showpath(name) or ""
- if found ~= "" then
- return found
- else
- return (kpse_initialized():show_path(name)) or ""
- end
- end
-
- end
-
- function runners.loadbase()
- end
-
-else
-
- function runners.loadbase(...)
- if not resolvers.load(...) then
- report("forcing cache reload")
- resolvers.renewcache()
- trackers.enable("resolvers.locating")
- if not resolvers.load(...) then
- report("the resolver databases are not present or outdated")
- end
- end
- end
-
- resolvers.load_tree(e_argument('tree'),e_argument("resolve"))
-
-end
-
--- joke .. reminds me of messing with gigi terminals
-
-do
-
- local a_locale = e_argument("locale")
-
- if a_locale then
-
- -- I really hate this crap but am too tired of discussing it over and over
- -- again so for the sake of usiage outside context we will provide ways to
- -- use locales in an otherwise supposed to be locale agnostic system. And
- -- forget about support in case of interferences.
-
- report()
- report(what == "force" and "forcing locale:" or "original locale:")
- report()
- report(" collate : %s",status.lc_collate or "<unset>")
- report(" ctype : %s",status.lc_ctype or "<unset>")
- report(" monetary : %s",status.lc_monetary or "<unset>")
- report(" numeric : %s",status.lc_numeric or "<unset>")
- report(" time : %s",status.lc_time or "<unset>")
- report()
-
- end
-
- if a_locale == "force" then
- os.setlocale(status.lc_collate ,"collate")
- os.setlocale(status.lc_ctype ,"ctype")
- os.setlocale(status.lc_monetary,"monetary")
- os.setlocale(status.lc_numeric ,"numeric")
- os.setlocale(status.lc_time ,"time")
- else
- function os.setlocale()
- end
- end
-
-end
-
--- if e_argument("ansi") or e_argument("ansilog") then
-
--- logs.setformatters(e_argument("ansi") and "ansi" or "ansilog")
-
--- -- local script = e_argument("script") or e_argument("scripts")
--- --
--- -- if type(script) == "string" then
--- -- logs.writer("]0;"..script.."") -- for Alan to test
--- -- end
-
--- end
-
-if e_argument("script") or e_argument("scripts") then
-
- -- run a script by loading it (using libs), pass args
-
- if e_argument("nofiledatabase") then
- -- handy for mtx-update
- else
- runners.loadbase()
- end
- if is_mkii_stub then
- ok = runners.execute_script(filename,false,true)
- else
- ok = runners.execute_ctx_script(filename)
- end
-
-elseif e_argument("evaluate") then
-
- runners.evaluate(e_argument("evaluate"),filename)
-
-elseif e_argument("selfmerge") then
-
- -- embed used libraries
-
- runners.loadbase()
- local found = locate_libs()
-
- if found then
- local mtxrun = resolvers.findfile("mtxrun.lua") -- includes local name
- if lfs.isfile(mtxrun) then
- utilities.merger.selfmerge(mtxrun,own.libs,{ found })
- application.report("runner updated on resolved path: %s",mtxrun)
- else
- utilities.merger.selfmerge(own.name,own.libs,{ found })
- application.report("runner updated on relative path: %s",own.name)
- end
- end
-
-elseif e_argument("selfclean") then
-
- -- remove embedded libraries
-
- runners.loadbase()
-
- local mtxrun = resolvers.findfile("mtxrun.lua") -- includes local name
- if lfs.isfile(mtxrun) then
- utilities.merger.selfclean(mtxrun)
- application.report("runner cleaned on resolved path: %s",mtxrun)
- else
- utilities.merger.selfclean(own.name)
- application.report("runner cleaned on relative path: %s",own.name)
- end
-
-elseif e_argument("selfupdate") then
-
- runners.loadbase()
- trackers.enable("resolvers.locating")
- resolvers.updatescript(own.name,"mtxrun")
-
-elseif e_argument("ctxlua") or e_argument("internal") then
-
- -- run a script by loading it (using libs)
-
- runners.loadbase()
- ok = runners.execute_script(filename,true)
-
-elseif e_argument("execute") then
-
- -- execute script
-
- runners.loadbase()
- ok = runners.execute_script(filename)
-
-elseif e_argument("direct") then
-
- -- equals bin:
-
- runners.loadbase()
- ok = runners.execute_program(filename)
-
-elseif e_argument("edit") then
-
- -- edit file
-
- runners.loadbase()
- runners.edit_script(filename)
-
-elseif e_argument("launch") then
-
- runners.loadbase()
- runners.launch_file(filename)
-
-elseif e_argument("associate") then
-
- runners.associate(filename)
-
-elseif e_argument("gethelp") then
-
- runners.gethelp()
-
-elseif e_argument("makestubs") then
-
- -- make stubs (depricated)
-
- runners.handle_stubs(true)
-
-elseif e_argument("removestubs") then
-
- -- remove stub (depricated)
-
- runners.loadbase()
- runners.handle_stubs(false)
-
-elseif e_argument("resolve") then
-
- -- resolve string
-
- runners.loadbase()
- runners.resolve_string(filename)
-
-elseif e_argument("locate") then
-
- -- locate file (only database)
-
- runners.loadbase()
- runners.locate_file(filename)
-
-elseif e_argument("platform") or e_argument("show-platform") then
-
- -- locate platform
-
- runners.loadbase()
- runners.locate_platform()
-
-elseif e_argument("prefixes") then
-
- runners.loadbase()
- runners.prefixes()
-
-elseif e_argument("timedrun") then
-
- -- locate platform
-
- runners.loadbase()
- runners.timedrun(filename)
-
-elseif e_argument("variables") or e_argument("show-variables") or e_argument("expansions") or e_argument("show-expansions") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expansions",filename)
-
- resolvers.load("nofiles")
- resolvers.listers.variables(e_argument("pattern"))
-
-elseif e_argument("configurations") or e_argument("show-configurations") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--configurations",filename)
-
- resolvers.load("nofiles")
- resolvers.listers.configurations()
-
-elseif e_argument("find-file") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--find-file",filename)
-
- resolvers.load()
- local e_all = e_argument("all")
- local e_pattern = e_argument("pattern")
- local e_format = e_argument("format")
- local finder = e_all and resolvers.findfiles or resolvers.findfile
- if not e_pattern then
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(finder,environment.files,e_format)
- elseif type(e_pattern) == "string" then
- resolvers.dowithfilesandreport(finder,{ e_pattern },e_format)
- end
-
-elseif e_argument("find-path") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--find-path",filename)
-
- resolvers.load()
- local path = resolvers.findpath(filename)
- if e_verbose then
- report(path)
- else
- print(path)
- end
-
-elseif e_argument("expand-braces") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expand-braces",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.expandbraces, environment.files)
-
-elseif e_argument("expand-path") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expand-path",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.expandpath, environment.files)
-
-elseif e_argument("resolve-path") then
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.cleanedpathlist, environment.files)
-
-elseif e_argument("expand-var") or e_argument("expand-variable") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expand-var",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.expansion, environment.files)
-
-elseif e_argument("show-path") or e_argument("path-value") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--show-path",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.showpath, environment.files)
-
-elseif e_argument("var-value") or e_argument("show-value") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--show-value",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.variable,environment.files)
-
-elseif e_argument("format-path") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--format-path",filename)
-
- resolvers.load()
- report(caches.getwritablepath("format"))
-
--- elseif e_argument("pattern") then
---
--- -- luatools
---
--- runners.execute_ctx_script("mtx-base","--pattern='" .. e_argument("pattern") .. "'",filename)
-
-elseif e_argument("generate") then
-
- -- luatools
-
- if filename and filename ~= "" then
- resolvers.load("nofiles")
- trackers.enable("resolvers.locating")
- resolvers.renew(filename)
- else
- resolvers.renewcache()
- trackers.enable("resolvers.locating")
- resolvers.load()
- end
-
- e_verbose = true
-
-elseif e_argument("make") or e_argument("ini") or e_argument("compile") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--make",filename)
-
- resolvers.load()
- trackers.enable("resolvers.locating")
- environment.make_format(filename)
-
-elseif e_argument("run") then
-
- -- luatools
-
- runners.execute_ctx_script("mtx-base","--run",filename)
-
-elseif e_argument("fmt") then
-
- -- luatools
-
- runners.execute_ctx_script("mtx-base","--fmt",filename)
-
-elseif e_argument("help") and filename=='base' then
-
- -- luatools
-
- runners.execute_ctx_script("mtx-base","--help")
-
-elseif e_argument("version") then
-
- application.version()
-
- application.report("source path",environment.ownbin)
-
-elseif e_argument("directives") then
-
- directives.show()
-
-elseif e_argument("trackers") then
-
- trackers.show()
-
-elseif e_argument("experiments") then
-
- experiments.show()
-
-elseif e_argument("exporthelp") then
-
- runners.loadbase()
- application.export(e_argument("exporthelp"),filename)
-
-elseif e_argument("systeminfo") then
-
- runners.systeminfo()
-
-elseif e_argument("locale") then
-
- -- already done
-
-elseif e_argument("help") or filename=='help' or filename == "" then
-
- application.help()
-
-elseif find(filename,"^bin:") then
-
- runners.loadbase()
- ok = runners.execute_program(filename)
-
-elseif is_mkii_stub then
-
- -- execute mkii script
-
- runners.loadbase()
- ok = runners.execute_script(filename,false,true)
-
-elseif false then
-
- runners.loadbase()
- ok = runners.execute_ctx_script(filename)
- if not ok then
- ok = runners.execute_script(filename)
- end
-
-elseif environment.files[1] == 'texmfcnf.lua' then -- so that we don't need to load mtx-base
-
- resolvers.load("nofiles")
- resolvers.listers.configurations()
-
-else
- runners.loadbase()
- runners.execute_ctx_script("mtx-base",filename)
-
-end
-
-if e_verbose then
- report()
- report("elapsed lua time: %0.3f seconds",os.runtime())
-end
-
-if os.type ~= "windows" then
- texio.write("\n") -- is this still valid?
-end
-
-if ok == false then ok = 1 elseif ok == true or ok == nil then ok = 0 end
-
--- os.exit(ok,true) -- true forces a cleanup in 5.2+
-
-os.exit(ok) -- true forces a cleanup in 5.2+ but reports a wrong number then
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/mtxrunjit.exe b/Master/texmf-dist/scripts/context/stubs/mswin/mtxrunjit.exe
deleted file mode 100755
index 0e7882cf926..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/mtxrunjit.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/pstopdf.exe b/Master/texmf-dist/scripts/context/stubs/mswin/pstopdf.exe
deleted file mode 100755
index 0e7882cf926..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/pstopdf.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/texexec.exe b/Master/texmf-dist/scripts/context/stubs/mswin/texexec.exe
deleted file mode 100755
index 0e7882cf926..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/texexec.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/mswin/texmfstart.exe b/Master/texmf-dist/scripts/context/stubs/mswin/texmfstart.exe
deleted file mode 100755
index 0e7882cf926..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/mswin/texmfstart.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/setup/setuptex b/Master/texmf-dist/scripts/context/stubs/setup/setuptex
deleted file mode 100644
index fb65788b61a..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/setup/setuptex
+++ /dev/null
@@ -1,222 +0,0 @@
-# Example setup file for ConTeXt distribution
-#
-# Author: Hans Hagen
-# Patches: Arthur R. & Mojca M.
-#
-# Usage:
-# . setuptex [texroot]
-#
-# On the first run also execute:
-# mktexlsr
-# texexec --make --alone
-
-#
-# PLATFORM
-#
-
-# we will try to guess the platform first
-# (needs to be kept in sync with first-setup.sh and mtxrun)
-# if yours is missing, let us know
-
-system=`uname -s`
-cpu=`uname -m`
-
-case "$system" in
- # linux
- Linux)
- if command -v ldd >/dev/null && ldd --version 2>&1 | grep -E '^musl' >/dev/null
- then
- libc=musl
- else
- libc=glibc
- fi
- case "$cpu" in
- i*86)
- case "$libc" in
- glibc) platform="linux" ;;
- musl) platform="linuxmusl" ;;
- esac ;;
- x86_64|ia64)
- case "$libc" in
- glibc) platform="linux-64" ;;
- musl) platform="linuxmusl-64" ;;
- esac ;;
-
- # a little bit of cheating with ppc64 (won't work on Gentoo)
- ppc|ppc64) platform="linux-ppc" ;;
-
- # we currently support just mipsel, but Debian is lying (reports mips64)
- # we need more hacks to fix the situation, this is just a temporary solution
- mips|mips64|mipsel|mips64el) platform="linux-mipsel" ;;
-
- armv7l) platform="linux-armhf"
- # machine id output by uname(1) is insufficent to determine whether this
- # is a soft or hard float system so we check ourselves.
- # a) binutils, this should work almost everywhere
- if $(which readelf >/dev/null 2>&1); then
- readelf -A /proc/self/exe | grep -q '^ \+Tag_ABI_VFP_args'
- if [ ! $? ]; then
- platform="linux-armel"
- fi
- # b) debian-specific fallback
- elif $(which dpkg >/dev/null 2>&1); then
- if [ "$(dpkg --print-architecture)" = armel ]; then
- platform="linux-armel"
- fi
- fi
- # else go with hard fp
- ;;
-
- *) platform="unknown" ;;
- esac ;;
- # Mac OS X
- Darwin)
- case "$cpu" in
- i*86) platform="osx-intel" ;;
- x86_64) platform="osx-64" ;;
- ppc*|powerpc|power*|Power*) platform="osx-ppc" ;;
- *) platform="unknown" ;;
- esac ;;
- # FreeBSD
- FreeBSD|freebsd)
- case "$cpu" in
- i*86) platform="freebsd" ;;
- x86_64) platform="freebsd" ;;
- amd64) platform="freebsd-amd64" ;;
- *) platform="unknown" ;;
- esac ;;
- # OpenBSD
- OpenBSD)
- case "$cpu" in
- i*86) platform="openbsd" ;;
- amd64) platform="openbsd-amd64" ;;
- *) platform="unknown" ;;
- esac ;;
- # kFreeBSD (Debian)
- GNU/kFreeBSD)
- case "$cpu" in
- i*86) platform="kfreebsd-i386" ;;
- x86_64|amd64) platform="kfreebsd-amd64" ;;
- *) platform="unknown" ;;
- esac ;;
- # MSYS2
- MSYS_NT-10.0)
- case "$cpu" in
- i*86) platform="win32" ;;
- x86_64) platform="win64" ;;
- *) platform="unknown" ;;
- esac ;;
- # cygwin
- CYGWIN)
- case "$cpu" in
- i*86) platform="cygwin" ;;
- x86_64|ia64) platform="cygwin-64" ;;
- *) platform="unknown" ;;
- esac ;;
- # SunOS/Solaris
- SunOS)
- case "$cpu" in
- sparc) platform="solaris-sparc" ;;
- i86pc) platform="solaris-intel" ;;
- *) platform="unknown" ;;
- esac ;;
- *) platform="unknown"
-esac
-
-# temporary fix for Snow Leopard
-if test "$platform" = "osx-intel"; then
- # running Snow Leopard or later
- if test `uname -r|cut -f1 -d"."` -ge 10 ; then
- # working on 64-bit hardware
- if test `sysctl -n hw.cpu64bit_capable` = 1; then
- platform="osx-64"
- fi
- fi
-fi
-
-if test "$platform" = "unknown" ; then
- echo "Error: your system \"$system $cpu\" is not supported yet."
- echo "Please report to the ConTeXt mailing-list (ntg-context@ntg.nl)"
-elif test "$platform" = "linux-ppc" ; then
- echo "Error: support for your system \"$platform\" has been dropped."
- echo "Please ask on to the ConTeXt mailing-list if you still need it (ntg-context@ntg.nl)"
-fi
-
-#
-# PATH
-#
-
-# this resolves to path of the setuptex script
-# We use $0 for determine the path to the script, except for:
-# * bash where $0 always is bash; here we use BASH_SOURCE
-# * ksh93 where we use ${.sh.file}
-# Thanks to Vasile Gaburici and Alessandro Perucchi for reporting this
-# * http://www.ntg.nl/pipermail/ntg-context/2008/033953.html
-# * http://www.ntg.nl/pipermail/ntg-context/2012/068658.html
-if [ z"$BASH_SOURCE" != z ]; then
- SCRIPTPATH="$BASH_SOURCE"
-elif [ z"$KSH_VERSION" != z ]; then
- SCRIPTPATH="${.sh.file}"
-else
- SCRIPTPATH="$0"
-fi
-
-OWNPATH=$(cd -P -- "$(dirname -- "$SCRIPTPATH")" && pwd -P)
-
-# but one can also call
-# . setuptex path-to-tree
-
-TEXROOT=""
-# first check if any path has been provided in the argument, and try to use that one
-if [ $# -ne 0 ] ; then
- # TODO: resolve any errors
- ARGPATH=$(cd -P -- "$(dirname -- "$1")" && pwd -P) && ARGPATH=$ARGPATH/$(basename -- "$1")
- if test -f "$ARGPATH/texmf/tex/plain/base/plain.tex" ; then
- if [ -d "$ARGPATH/texmf-$platform/bin" ]; then
- TEXROOT="$ARGPATH"
- else
- echo "Binaries for platform '$platform' are missing."
- echo "(There is no folder \"$ARGPATH/texmf-$platform/bin\")"
- fi
- else
- echo "The argument \"$ARGPATH\" is not a valid TEXROOT path."
- echo "(There is no file \"$ARGPATH/texmf/tex/plain/base/plain.tex\")"
-
- if [ -f "$OWNPATH/texmf/tex/plain/base/plain.tex" ]; then
- TEXROOT="$OWNPATH"
- fi
- fi
-else
- if [ -f "$OWNPATH/texmf/tex/plain/base/plain.tex" ]; then
- if [ -d "$OWNPATH/texmf-$platform/bin" ]; then
- TEXROOT="$OWNPATH"
- else
- echo "Binaries for platform '$platform' are missing."
- echo "(There is no folder \"$OWNPATH/texmf-$platform/bin\")"
- fi
- else
- echo "\"$OWNPATH\" is not a valid TEXROOT path."
- echo "(There is no file \"$OWNPATH/texmf/tex/plain/base/plain.tex\")"
- fi
-fi
-
-if [ "$TEXROOT" != "" ]; then
- # for Alan Braslau's server :)
- if [ "x$PS1" != "x" ] ; then
- echo "Setting \"$TEXROOT\" as ConTeXt root."
- fi
-
-# ConTeXt binaries have to be added to PATH
-TEXMFOS=$TEXROOT/texmf-$platform
-export PATH=$TEXMFOS/bin:$PATH
-
-# unset variables that won't be used lately
-unset platform cpu system OWNPATH SCRIPTPATH ARGPATH TEXMFOS
-
-# not sure why this would be needed
-# export CTXMINIMAL=yes
-
-else
- echo "provide a proper tex root (like '. setuptex /something/tex')" ;
-fi
-
diff --git a/Master/texmf-dist/scripts/context/stubs/setup/setuptex.bat b/Master/texmf-dist/scripts/context/stubs/setup/setuptex.bat
deleted file mode 100755
index b61fd44941e..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/setup/setuptex.bat
+++ /dev/null
@@ -1,70 +0,0 @@
-@ECHO OFF
-
-REM author: Hans Hagen - PRAGMA ADE - Hasselt NL - www.pragma-ade.com
-
-:userpath
-
-if "%SETUPTEX%"=="done" goto done
-
-if "%~s1"=="" goto selftest
-
-set TEXMFOS=%~s1texmf-mswin-64
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~s1\texmf-mswin-64
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~s1texmf-win64
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~s1\texmf-win64
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~s1texmf-mswin
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~s1\texmf-mswin
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~s1texmf-win32
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~s1\texmf-win32
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-:selftest
-
-set TEXMFOS=%~d0%~p0texmf-mswin-64
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~d0%~p0\texmf-mswin-64
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~d0%~p0texmf-win64
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~d0%~p0\texmf-win64
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~d0%~p0texmf-mswin
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~d0%~p0\texmf-mswin
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~d0%~p0texmf-win32
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-set TEXMFOS=%~d0%~p0\texmf-win32
-if exist %TEXMFOS%\bin\mtxrun.exe goto start
-
-:start
-
-set PATH=%TEXMFOS%\bin;%PATH%
-
-:register
-
-set SETUPTEX=done
-set CTXMINIMAL=yes
-
-:done
diff --git a/Master/texmf-dist/scripts/context/stubs/setup/setuptex.csh b/Master/texmf-dist/scripts/context/stubs/setup/setuptex.csh
deleted file mode 100644
index 62ca0356934..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/setup/setuptex.csh
+++ /dev/null
@@ -1,177 +0,0 @@
-# Example setup file for ConTeXt distribution
-#
-# Author: Hans Hagen
-# Patches: Arthur R. & Mojca M.
-# (t)csh version: Alan B.
-#
-# Usage :
-# source setuptex.csh [texroot]
-#
-# On the first run also execute:
-# mktexlsr
-# texexec --make --alone
-
-echo "We are considering removing setuptex.csh in case that nobody uses it."
-echo "If you still use this file please drop us some mail at"
-echo " gardeners (at) contextgarden (dot) net"
-echo "If we don't get any response, we will delete it in near future."
-
-#
-# PLATFORM
-#
-
-# we will try to guess the platform first
-# (needs to be kept in sync with first-setup.sh and mtxrun)
-# if yours is missing, let us know
-
-set system=`uname -s`
-set cpu=`uname -m`
-
-switch ( $system )
- # linux
- case Linux:
- switch ( $cpu )
- case i*86:
- set platform="linux"
- breaksw
- case x86_64:
- case ia64:
- set platform="linux-64"
- breaksw
- case ppc:
- case ppc64:
- set platform="linux-ppc"
- breaksw
- default:
- set platform="unknown"
- endsw
- breaksw
- # Mac OS X
- case Darwin:
- switch ( $cpu )
- case i*86:
- set platform="osx-intel"
- breaksw
- case x86_64:
- set platform="osx-64"
- breaksw
- case ppc*:
- case powerpc:
- case power*:
- case Power*:
- set platform="osx-ppc"
- breaksw
- default:
- set platform="unknown"
- endsw
- breaksw
- # FreeBSD
- case FreeBSD:
- case freebsd:
- switch ( $cpu )
- case i*86:
- set platform="freebsd"
- breaksw
- case x86_64:
- set platform="freebsd"
- breaksw
- case amd64:
- set platform="freebsd-amd64"
- breaksw
- default:
- set platform="unknown"
- endsw
- breaksw
- # OpenBSD
- case OpenBSD:
- switch ( $cpu )
- case i*86:
- set platform="openbsd"
- breaksw
- case amd64:
- set platform="openbsd-amd64"
- breaksw
- default:
- set platform="unknown"
- endsw
- breaksw
- # cygwin
- case CYGWIN:
- switch ( $cpu )
- case i*86:
- set platform="cygwin"
- breaksw
- case x86_64:
- case ia64:
- set platform="cygwin-64"
- breaksw
- default:
- set platform="unknown"
- endsw
- breaksw
- # SunOS/Solaris
- case SunOS:
- switch ( $cpu )
- case sparc:
- set platform="solaris-sparc"
- breaksw
- case i86pc:
- set platform="solaris-intel"
- default:
- set platform="unknown"
- endsw
- breaksw
- # Other
- default:
- set platform="unknown"
-endsw
-
-if ( $platform == "unknown" ) then
- echo Error: your system \"$system $cpu\" is not supported yet.
- echo Please report to the ConTeXt mailing-list (ntg-context@ntg.nl).
-endif
-
-#
-# PATH
-#
-
-# this resolves to path of the setuptex script
-# We use $0 for determine the path to the script, except for bash and (t)csh where $0
-# always is bash or (t)csh.
-
-# but one can also call
-# . setuptex path-to-tex-tree
-
-# first check if any path has been provided in the argument, and try to use that one
-if ( $# > 0 ) then
- setenv TEXROOT $1
-else
- # $_ should be `history -h 1` but doesn't seem to work...
- set cmd=`history -h 1`
- if ( $cmd[2]:h == $cmd[2]:t ) then
- setenv TEXROOT $cwd
- else
- setenv TEXROOT $cmd[2]:h
- endif
- unset cmd
-endif
-cd $TEXROOT; setenv TEXROOT $cwd; cd -
-
-if ( -f "$TEXROOT/texmf/tex/plain/base/plain.tex" ) then
- echo Setting \"$TEXROOT\" as TEXROOT.
-else
- echo \"$TEXROOT\" is not a valid TEXROOT path.
- echo There is no file \"$TEXROOT/texmf/tex/plain/base/plain.tex\".
- echo Please provide a proper tex root (like \"source setuptex /path/tex\")
- unsetenv TEXROOT
- exit
-endif
-
-unsetenv TEXINPUTS MPINPUTS MFINPUTS
-
-# ConTeXt binaries have to be added to PATH
-setenv TEXMFOS $TEXROOT/texmf-$platform
-setenv PATH $TEXMFOS/bin:$PATH
-# TODO: we could set OSFONTDIR on Mac for example
-
-# setenv CTXMINIMAL yes
diff --git a/Master/texmf-dist/scripts/context/stubs/source/mtxrun_dll.c b/Master/texmf-dist/scripts/context/stubs/source/mtxrun_dll.c
deleted file mode 100644
index fc2e260f5a2..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/source/mtxrun_dll.c
+++ /dev/null
@@ -1,306 +0,0 @@
-/************************************************************************
-
- Copyright:
-
- Public Domain
- Originally written in 2010 by Tomasz M. Trzeciak and Hans Hagen
-
- This program is derived from the 'runscript' program originally
- written in 2009 by T.M. Trzeciak. It has been adapted for use in
- ConTeXt MkIV.
-
- Comment:
-
- In ConTeXt MkIV we have two core scripts: luatools.lua and
- mtxrun.lua where the second one is used to launch other scripts.
- Normally a user will use a call like:
-
- mtxrun --script font --reload
-
- Here mtxrun is a lua script. In order to avoid the usage of a cmd
- file on windows this runner will start texlua directly. If the
- shared library luatex.dll is available, texlua will be started in
- the same process avoiding thus any additional overhead. Otherwise
- it will be spawned in a new proces.
-
- We also don't want to use other runners, like those that use kpse
- to locate the script as this is exactly what mtxrun itself is doing
- already. Therefore the runscript program is adapted to a more direct
- approach suitable for mtxrun.
-
- Compilation:
-
- with gcc (size optimized):
-
- gcc -Os -s -shared -o mtxrun.dll mtxrun_dll.c
- gcc -Os -s -o mtxrun.exe mtxrun_exe.c -L./ -lmtxrun
-
- with tcc (extra small size):
-
- tcc -shared -o mtxrun.dll mtxrun_dll.c
- tcc -o mtxrun.exe mtxrun_exe.c mtxrun.def
-
-************************************************************************/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <windows.h>
-
-//#define STATIC
-#define IS_WHITESPACE(c) ((c == ' ') || (c == '\t'))
-#define MAX_CMD 32768
-#define DIE(...) { \
- fprintf( stderr, "mtxrun: " ); \
- fprintf( stderr, __VA_ARGS__ ); \
- return 1; \
-}
-
-static char cmdline[MAX_CMD];
-static char dirpath[MAX_PATH];
-static char progname[MAX_PATH];
-static char scriptpath[MAX_PATH];
-static char luatexpath[MAX_PATH];
-HMODULE dllluatex = NULL;
-typedef int ( *mainlikeproc )( int, char ** );
-
-#ifdef STATIC
-int main( int argc, char *argv[] )
-#else
-__declspec(dllexport) int dllrunscript( int argc, char *argv[] )
-#endif
-{
- char *binary, *s, *luatexfname, *argstr, **lua_argv;
- int k, quoted, lua_argc;
- int passprogname = 0;
- unsigned char is_jit=0;
-
- // directory of this module/executable
- HMODULE module_handle = GetModuleHandle( "mtxrun.dll" );
- // if ( module_handle == NULL ) exe path will be used, which is OK too
- k = (int) GetModuleFileName( module_handle, dirpath, MAX_PATH );
- if ( !k || ( k == MAX_PATH ) )
- DIE( "unable to determine a valid module name\n" );
- s = strrchr(dirpath, '\\');
- if ( s == NULL ) DIE( "no directory part in module path: %s\n", dirpath );
- *(++s) = '\0'; //remove file name, leave trailing backslash
-
- // program name
- k = strlen(argv[0]);
- while ( k && (argv[0][k-1] != '/') && (argv[0][k-1] != '\\') ) k--;
- strcpy(progname, &argv[0][k]);
- s = progname;
- if ( s = strrchr(s, '.') ) *s = '\0'; // remove file extension part
-
- /* check "jit" : strlen("jit") = 3 */
- if (strncmp(progname + strlen(progname) - 3, "jit", 3) == 0) {
- is_jit = 1;
- progname[strlen(progname) - 3]='\0';
- }
- else
- is_jit = 0;
-
- // script path
-
- strcpy( scriptpath, dirpath );
- k = strlen(progname);
- if ( k < 6 ) k = 6; // in case the program name is shorter than "mtxrun"
- if ( strlen(dirpath) + k + 4 >= MAX_PATH )
- DIE( "path too long: %s%s\n", dirpath, progname );
-
- if ( strcmpi(progname,"mtxrun") == 0 ) {
- strcat( scriptpath, progname );
- strcat( scriptpath, ".lua" );
- } else if ( strcmpi(progname,"luatools") == 0 ) {
- strcat( scriptpath, "mtxrun.lua" );
- strcpy( progname, "base" );
- passprogname = 1;
- } else if ( strcmpi(progname,"texmfstart") == 0 ) {
- strcat( scriptpath, "mtxrun.lua" );
- } else {
- strcat( scriptpath, "mtxrun.lua" );
- passprogname = 1;
- }
- if ( GetFileAttributes(scriptpath) == INVALID_FILE_ATTRIBUTES )
- DIE( "file not found: %s\n", scriptpath );
-
- // find luatex.exe /luajittex.exe
- if ( SearchPath(
- dirpath, // was getenv( "PATH" ), // path to search (optional)
- (is_jit ? "luajittex.exe":"luatex.exe"), // file name to search
- NULL, // file extension to add (optional)
- MAX_PATH, // output buffer size
- luatexpath, // output buffer pointer
- &luatexfname ) // pointer to a file part in the output buffer (optional)
- ) {
- binary = (is_jit ? "luajittex.exe":"luatex.exe");
- } else if ( SearchPath(
- dirpath, // was getenv( "PATH" ), // path to search (optional)
- (is_jit ? "texluajit.exe":"texlua.exe"), // file name to search
- NULL, // file extension to add (optional)
- MAX_PATH, // output buffer size
- luatexpath, // output buffer pointer
- &luatexfname ) // pointer to a file part in the output buffer (optional)
- ) {
- binary = (is_jit ? "texluajit.exe":"texlua.exe");
- } else if ( SearchPath(
- getenv("PATH"), // was dirpath, // path to search (optional)
- (is_jit ? "luajittex.exe":"luatex.exe"), // file name to search
- NULL, // file extension to add (optional)
- MAX_PATH, // output buffer size
- luatexpath, // output buffer pointer
- &luatexfname ) // pointer to a file part in the output buffer (optional)
- ) {
- binary = (is_jit ? "luajittex.exe":"luatex.exe");
- } else if ( SearchPath(
- getenv("PATH") , // was dirpath, // path to search (optional)
- (is_jit ? "texluajit.exe":"texlua.exe"), // file name to search
- NULL, // file extension to add (optional)
- MAX_PATH, // output buffer size
- luatexpath, // output buffer pointer
- &luatexfname ) // pointer to a file part in the output buffer (optional)
- ) {
- binary = (is_jit ? "texluajit.exe":"texlua.exe");
- }else {
- DIE( "unable to locate texlua.exe on the search path" );
- }
-
- /* if ( SearchPath( */
- /* dirpath, // was getenv( "PATH" ), // path to search (optional) */
- /* (is_jit ? "luajittex.exe":"luatex.exe"), // file name to search */
- /* NULL, // file extension to add (optional) */
- /* MAX_PATH, // output buffer size */
- /* luatexpath, // output buffer pointer */
- /* &luatexfname ) // pointer to a file part in the output buffer (optional) */
- /* ) { */
- /* binary = (is_jit ? "luajittex.exe":"luatex.exe"); */
- /* }else if ( SearchPath( */
- /* getenv("PATH"), // was dirpath, // path to search (optional) */
- /* (is_jit ? "luajittex.exe":"luatex.exe"), // file name to search */
- /* NULL, // file extension to add (optional) */
- /* MAX_PATH, // output buffer size */
- /* luatexpath, // output buffer pointer */
- /* &luatexfname ) // pointer to a file part in the output buffer (optional) */
- /* ) { */
- /* binary = (is_jit ? "luajittex.exe":"luatex.exe"); */
- /* }else if ( SearchPath( */
- /* dirpath, // was getenv( "PATH" ), // path to search (optional) */
- /* (is_jit ? "texluajit.exe":"texlua.exe"), // file name to search */
- /* NULL, // file extension to add (optional) */
- /* MAX_PATH, // output buffer size */
- /* luatexpath, // output buffer pointer */
- /* &luatexfname ) // pointer to a file part in the output buffer (optional) */
- /* ) { */
- /* binary = (is_jit ? "texluajit.exe":"texlua.exe"); */
- /* }else if ( SearchPath( */
- /* getenv("PATH") , // was dirpath, // path to search (optional) */
- /* (is_jit ? "texluajit.exe":"texlua.exe"), // file name to search */
- /* NULL, // file extension to add (optional) */
- /* MAX_PATH, // output buffer size */
- /* luatexpath, // output buffer pointer */
- /* &luatexfname ) // pointer to a file part in the output buffer (optional) */
- /* ) { */
- /* binary = (is_jit ? "texluajit.exe":"texlua.exe"); */
- /* }else { */
- /* DIE( "unable to locate texlua.exe on the search path" ); */
- /* } */
-
-
-
-
- // link directly with luatex.dll if available in texlua's dir
- strcpy( luatexfname, (is_jit ? "luajittex.dll":"luatex.dll") );
- if ( dllluatex = LoadLibrary(luatexpath) )
- {
- mainlikeproc dllluatexmain = (mainlikeproc) GetProcAddress( dllluatex, (is_jit ? "dllluajittexmain": "dllluatexmain" ));
- if ( dllluatexmain == NULL )
- if (is_jit)
- DIE( "unable to locate dllluatexmain procedure in luajittex.dll" )
- else
- DIE( "unable to locate dllluatexmain procedure in luatex.dll" );
-
- // set up argument list for texlua script
-
- lua_argv = (char **)malloc( (argc + 5) * sizeof(char *) );
- if ( lua_argv == NULL ) DIE( "out of memory\n" );
- lua_argv[lua_argc=0] = luatexfname;
- lua_argv[++lua_argc] = "--luaonly";
- lua_argv[++lua_argc] = scriptpath; // script to execute
- if (passprogname) {
- lua_argv[++lua_argc] = "--script";
- lua_argv[++lua_argc] = progname;
- }
- for ( k = 1; k < argc; k++ ) lua_argv[++lua_argc] = argv[k];
- lua_argv[++lua_argc] = NULL;
-
- // call texlua interpreter
- // dllluatexmain never returns, but we pretend that it does
-
- k = dllluatexmain( lua_argc, lua_argv );
- if (lua_argv) free( lua_argv );
- return k;
- }
- // we are still here, so no luatex.dll; spawn texlua.exe instead
-
- strcpy( luatexfname,binary);
- strcpy( cmdline, " --luaonly " );
- strcpy( cmdline, "\"" );
- strcat( cmdline, luatexpath );
- strcat( cmdline, "\" \"" );
- strcat( cmdline, scriptpath );
- strcat( cmdline, "\"" );
- if (passprogname) {
- strcat( cmdline, " --script " );
- strcat( cmdline, progname );
- }
- argstr = GetCommandLine(); // get the command line of this process
- if ( argstr == NULL ) DIE( "unable to retrieve the command line string\n" );
-
- // skip over argv[0] in the argument string
- // (it can contain embedded double quotes if launched from cmd.exe!)
-
- for ( quoted = 0; (*argstr) && ( !IS_WHITESPACE(*argstr) || quoted ); argstr++ )
- if (*argstr == '"') quoted = !quoted;
-
- // pass through all the arguments
-
- if ( strlen(cmdline) + strlen(argstr) >= MAX_CMD )
- DIE( "command line string too long:\n%s%s\n", cmdline, argstr );
- strcat( cmdline, argstr );
-
- // create child process
-
- STARTUPINFO si;
- PROCESS_INFORMATION pi;
- ZeroMemory( &si, sizeof(si) );
- si.cb = sizeof(si);
- si.dwFlags = STARTF_USESTDHANDLES;// | STARTF_USESHOWWINDOW;
- //si.dwFlags = STARTF_USESHOWWINDOW;
- //si.wShowWindow = SW_HIDE ; // can be used to hide console window (requires STARTF_USESHOWWINDOW flag)
- si.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
- si.hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
- si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
- ZeroMemory( &pi, sizeof(pi) );
- if( !CreateProcess(
- NULL, // module name (uses command line if NULL)
- cmdline, // command line
- NULL, // process security atrributes
- NULL, // thread security atrributes
- TRUE, // handle inheritance
- 0, // creation flags, e.g. CREATE_NEW_CONSOLE, CREATE_NO_WINDOW, DETACHED_PROCESS
- NULL, // pointer to environment block (uses parent if NULL)
- NULL, // starting directory (uses parent if NULL)
- &si, // STARTUPINFO structure
- &pi ) // PROCESS_INFORMATION structure
- ) DIE( "command execution failed: %s\n", cmdline );
- DWORD ret = 0;
- CloseHandle( pi.hThread ); // thread handle is not needed
- if ( WaitForSingleObject( pi.hProcess, INFINITE ) == WAIT_OBJECT_0 ) {
- if ( !GetExitCodeProcess( pi.hProcess, &ret) )
- DIE( "unable to retrieve process exit code: %s\n", cmdline );
- } else DIE( "failed to wait for process termination: %s\n", cmdline );
- CloseHandle( pi.hProcess );
-
- // propagate exit code from the child process
- return ret;
-
-}
diff --git a/Master/texmf-dist/scripts/context/stubs/source/mtxrun_exe.c b/Master/texmf-dist/scripts/context/stubs/source/mtxrun_exe.c
deleted file mode 100644
index 0c27c272e37..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/source/mtxrun_exe.c
+++ /dev/null
@@ -1,8 +0,0 @@
-// This is the .exe part of the mtxrun program, see mtxrun_dll.c
-// for more details.
-
-#include <windows.h>
-
-__declspec(dllimport) int dllrunscript( int argc, char *argv[] );
-
-int main( int argc, char *argv[] ) { return dllrunscript( argc, argv ); }
diff --git a/Master/texmf-dist/scripts/context/stubs/source/readme.txt b/Master/texmf-dist/scripts/context/stubs/source/readme.txt
deleted file mode 100644
index 72892ee2f11..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/source/readme.txt
+++ /dev/null
@@ -1,40 +0,0 @@
-Copyright:
-
-The originally 'runscript' program was written by in 2009 by T.M.Trzeciak and is
-public domain. This derived mtxrun program is an adapted version by Hans Hagen and
-Luigi Scarso.
-
-Comment:
-
-In ConTeXt MkIV we have two core scripts: luatools.lua and mtxrun.lua where the
-second one is used to launch other scripts. The mtxrun.exe program calls luatex.exe.
-
-Normally a user will use a call like:
-
- mtxrun --script font --reload
-
-Here mtxrun is a lua script. In order to avoid the usage of a cmd file on windows this
-runner will start texlua directly. In TeXlive a runner is added for each cmd file but
-we don't want that overhead (and extra files). By using an exe we can call these
-scripts in batch files without the need for using call.
-
-The mtxrun.exe file can be copied to a mtxrunjit.exe file in which case luajittex.exe
-is called.
-
- mtxrunjit --script font --reload
-
-We also don't want to use other runners, like those that use kpse to locate the script
-as this is exactly what mtxrun itself is doing already. Therefore the runscript program
-is adapted to a more direct approach suitable for mtxrun.
-
-Compilation:
-
-with gcc (size optimized):
-
- gcc -Os -s -shared -o mtxrun.dll mtxrun_dll.c
- gcc -Os -s -o mtxrun.exe mtxrun_exe.c -L./ -lmtxrun
-
-with tcc (ver. 0.9.24), extra small size
-
- tcc -shared -o runscript.dll runscript_dll.c
- tcc -o runscript.exe runscript_exe.c runscript.def
diff --git a/Master/texmf-dist/scripts/context/stubs/unix/context b/Master/texmf-dist/scripts/context/stubs/unix/context
deleted file mode 100755
index fa62ba8d109..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/unix/context
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-mtxrun --script context "$@"
diff --git a/Master/texmf-dist/scripts/context/stubs/unix/contextjit b/Master/texmf-dist/scripts/context/stubs/unix/contextjit
deleted file mode 100755
index 5ac1947c78e..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/unix/contextjit
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/bin/sh
-
-luajittex --luaonly $(dirname $0)/mtxrun --script context "$@"
-
-# luajittex --luaonly ${0%contextjit}mtxrun --script context "$@"
diff --git a/Master/texmf-dist/scripts/context/stubs/unix/ctxtools b/Master/texmf-dist/scripts/context/stubs/unix/ctxtools
deleted file mode 100644
index 2e6bd4afaa0..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/unix/ctxtools
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-mtxrun --script ctxtools "$@"
diff --git a/Master/texmf-dist/scripts/context/stubs/unix/luatools b/Master/texmf-dist/scripts/context/stubs/unix/luatools
deleted file mode 100755
index c17b483be53..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/unix/luatools
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-mtxrun --script base "$@"
diff --git a/Master/texmf-dist/scripts/context/stubs/unix/mptopdf b/Master/texmf-dist/scripts/context/stubs/unix/mptopdf
deleted file mode 100644
index 1473337405a..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/unix/mptopdf
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-mtxrun --script mptopdf "$@"
diff --git a/Master/texmf-dist/scripts/context/stubs/unix/mtxrun b/Master/texmf-dist/scripts/context/stubs/unix/mtxrun
deleted file mode 100755
index 6fc17adb022..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/unix/mtxrun
+++ /dev/null
@@ -1,27376 +0,0 @@
-#!/usr/bin/env texlua
-
-if not modules then modules = { } end modules ['mtxrun'] = {
- version = 1.001,
- comment = "runner, lua replacement for texmfstart.rb",
- author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright = "PRAGMA ADE / ConTeXt Development Team",
- license = "see context related readme files"
-}
-
--- one can make a stub:
-
--- mtxrun :
---
--- #!/bin/sh
--- env LUATEXDIR=/....../texmf/scripts/context/lua luatex --luaonly mtxrun.lua "$@"
-
--- mtxrun.cmd :
---
--- @luatex --luaonly %~d0%~p0mtxrun.lua %*
-
--- filename : mtxrun.lua
--- comment : companion to context.tex
--- author : Hans Hagen, PRAGMA-ADE, Hasselt NL
--- copyright: PRAGMA ADE / ConTeXt Development Team
--- license : see context related readme files
-
--- This script is based on texmfstart.rb but does not use kpsewhich to locate files.
--- Although kpse is a library it never came to opening up its interface to other
--- programs (esp scripting languages) and so we do it ourselves. The lua variant
--- evolved out of an experimental ruby one. Interesting is that using a scripting
--- language instead of c does not have a speed penalty. Actually the lua variant is
--- more efficient, especially when multiple calls to kpsewhich are involved. The lua
--- library also gives way more control.
-
--- When libraries used here are updates you can run
---
--- mtxrun --selfmerge
---
--- to update the embedded code. After that you might need to run
---
--- mtxrun --selfupdate
---
--- to copy the new script (from scripts/context/lua) to location where
--- binaries are expected. If you want to remove the embedded code you can run
---
--- mtxxun --selfclean
-
--- to be done / considered
---
--- support for --exec or make it default
--- support for jar files (or maybe not, never used, too messy)
--- support for $RUBYINPUTS cum suis (if still needed)
--- remember for subruns: _CTX_K_V_#{original}_
--- remember for subruns: _CTX_K_S_#{original}_
--- remember for subruns: TEXMFSTART.#{original} [tex.rb texmfstart.rb]
-
--- begin library merge
-
-
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-bit32"] = package.loaded["l-bit32"] or true
-
--- original size: 3607, stripped down to: 3009
-
-if not modules then modules={} end modules ['l-bit32']={
- version=1.001,
- license="the same as regular Lua",
- source="bitwise.lua, v 1.24 2014/12/26 17:20:53 roberto",
- comment="drop-in for bit32, adapted a bit by Hans Hagen",
-}
-if bit32 then
-elseif utf8 then
- load ([[
-local select = select -- instead of: arg = { ... }
-bit32 = {
- bnot = function (a)
- return ~a & 0xFFFFFFFF
- end,
- band = function (x, y, z, ...)
- if not z then
- return ((x or -1) & (y or -1)) & 0xFFFFFFFF
- else
- local res = x & y & z
- for i=1,select("#",...) do
- res = res & select(i,...)
- end
- return res & 0xFFFFFFFF
- end
- end,
- bor = function (x, y, z, ...)
- if not z then
- return ((x or 0) | (y or 0)) & 0xFFFFFFFF
- else
- local res = x | y | z
- for i=1,select("#",...) do
- res = res | select(i,...)
- end
- return res & 0xFFFFFFFF
- end
- end,
- bxor = function (x, y, z, ...)
- if not z then
- return ((x or 0) ~ (y or 0)) & 0xFFFFFFFF
- else
- local res = x ~ y ~ z
- for i=1,select("#",...) do
- res = res ~ select(i,...)
- end
- return res & 0xFFFFFFFF
- end
- end,
- btest = function (x, y, z, ...)
- if not z then
- return (((x or -1) & (y or -1)) & 0xFFFFFFFF) ~= 0
- else
- local res = x & y & z
- for i=1,select("#",...) do
- res = res & select(i,...)
- end
- return (res & 0xFFFFFFFF) ~= 0
- end
- end,
- lshift = function (a, b)
- return ((a & 0xFFFFFFFF) << b) & 0xFFFFFFFF
- end,
- rshift = function (a, b)
- return ((a & 0xFFFFFFFF) >> b) & 0xFFFFFFFF
- end,
- arshift = function (a, b)
- a = a & 0xFFFFFFFF
- if b <= 0 or (a & 0x80000000) == 0 then
- return (a >> b) & 0xFFFFFFFF
- else
- return ((a >> b) | ~(0xFFFFFFFF >> b)) & 0xFFFFFFFF
- end
- end,
- lrotate = function (a ,b)
- b = b & 31
- a = a & 0xFFFFFFFF
- a = (a << b) | (a >> (32 - b))
- return a & 0xFFFFFFFF
- end,
- rrotate = function (a, b)
- b = -b & 31
- a = a & 0xFFFFFFFF
- a = (a << b) | (a >> (32 - b))
- return a & 0xFFFFFFFF
- end,
- extract = function (a, f, w)
- return (a >> f) & ~(-1 << (w or 1))
- end,
- replace = function (a, v, f, w)
- local mask = ~(-1 << (w or 1))
- return ((a & ~(mask << f)) | ((v & mask) << f)) & 0xFFFFFFFF
- end,
-}
- ]] ) ()
-elseif bit then
- load ([[
-local band, bnot, rshift, lshift = bit.band, bit.bnot, bit.rshift, bit.lshift
-bit32 = {
- arshift = bit.arshift,
- band = band,
- bnot = bnot,
- bor = bit.bor,
- bxor = bit.bxor,
- btest = function(...)
- return band(...) ~= 0
- end,
- extract = function(a,f,w)
- return band(rshift(a,f),2^(w or 1)-1)
- end,
- lrotate = bit.rol,
- lshift = lshift,
- replace = function(a,v,f,w)
- local mask = 2^(w or 1)-1
- return band(a,bnot(lshift(mask,f)))+lshift(band(v,mask),f)
- end,
- rrotate = bit.ror,
- rshift = rshift,
-}
- ]] ) ()
-else
- xpcall(function() local _,t=require("bit32") if t then bit32=t end return end,function() end)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-lua"] = package.loaded["l-lua"] or true
-
--- original size: 6405, stripped down to: 2865
-
-if not modules then modules={} end modules ['l-lua']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local next,type,tonumber=next,type,tonumber
-LUAMAJORVERSION,LUAMINORVERSION=string.match(_VERSION,"^[^%d]+(%d+)%.(%d+).*$")
-LUAMAJORVERSION=tonumber(LUAMAJORVERSION) or 5
-LUAMINORVERSION=tonumber(LUAMINORVERSION) or 1
-LUAVERSION=LUAMAJORVERSION+LUAMINORVERSION/10
-if LUAVERSION<5.2 and jit then
- MINORVERSION=2
- LUAVERSION=5.2
-end
-if not lpeg then
- lpeg=require("lpeg")
-end
-if loadstring then
- local loadnormal=load
- function load(first,...)
- if type(first)=="string" then
- return loadstring(first,...)
- else
- return loadnormal(first,...)
- end
- end
-else
- loadstring=load
-end
-if not ipairs then
- local function iterate(a,i)
- i=i+1
- local v=a[i]
- if v~=nil then
- return i,v
- end
- end
- function ipairs(a)
- return iterate,a,0
- end
-end
-if not pairs then
- function pairs(t)
- return next,t
- end
-end
-if not table.unpack then
- table.unpack=_G.unpack
-elseif not unpack then
- _G.unpack=table.unpack
-end
-if not package.loaders then
- package.loaders=package.searchers
-end
-local print,select,tostring=print,select,tostring
-local inspectors={}
-function setinspector(kind,inspector)
- inspectors[kind]=inspector
-end
-function inspect(...)
- for s=1,select("#",...) do
- local value=select(s,...)
- if value==nil then
- print("nil")
- else
- local done=false
- local kind=type(value)
- local inspector=inspectors[kind]
- if inspector then
- done=inspector(value)
- if done then
- break
- end
- end
- for kind,inspector in next,inspectors do
- done=inspector(value)
- if done then
- break
- end
- end
- if not done then
- print(tostring(value))
- end
- end
- end
-end
-local dummy=function() end
-function optionalrequire(...)
- local ok,result=xpcall(require,dummy,...)
- if ok then
- return result
- end
-end
-local flush=io.flush
-if flush then
- local execute=os.execute if execute then function os.execute(...) flush() return execute(...) end end
- local exec=os.exec if exec then function os.exec (...) flush() return exec (...) end end
- local spawn=os.spawn if spawn then function os.spawn (...) flush() return spawn (...) end end
- local popen=io.popen if popen then function io.popen (...) flush() return popen (...) end end
-end
-FFISUPPORTED=type(ffi)=="table" and ffi.os~="" and ffi.arch~="" and ffi.load
-if not FFISUPPORTED then
- local okay;okay,ffi=pcall(require,"ffi")
- FFISUPPORTED=type(ffi)=="table" and ffi.os~="" and ffi.arch~="" and ffi.load
-end
-if not FFISUPPORTED then
- ffi=nil
-elseif not ffi.number then
- ffi.number=tonumber
-end
-if LUAVERSION>5.3 then
-end
-if status and os.setenv then
- os.setenv("engine",string.lower(status.luatex_engine or "unknown"))
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-macro"] = package.loaded["l-macro"] or true
-
--- original size: 10130, stripped down to: 5990
-
-if not modules then modules={} end modules ['l-macros']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local S,P,R,V,C,Cs,Cc,Ct,Carg=lpeg.S,lpeg.P,lpeg.R,lpeg.V,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Ct,lpeg.Carg
-local lpegmatch=lpeg.match
-local concat=table.concat
-local format,sub,match=string.format,string.sub,string.match
-local next,load,type=next,load,type
-local newline=S("\n\r")^1
-local continue=P("\\")*newline
-local whitespace=S(" \t\n\r")
-local spaces=S(" \t")+continue
-local nametoken=R("az","AZ","__","09")
-local name=nametoken^1
-local body=((continue/""+1)-newline)^1
-local lparent=P("(")
-local rparent=P(")")
-local noparent=1-(lparent+rparent)
-local nested=P { lparent*(noparent+V(1))^0*rparent }
-local escaped=P("\\")*P(1)
-local squote=P("'")
-local dquote=P('"')
-local quoted=dquote*(escaped+(1-dquote))^0*dquote+squote*(escaped+(1-squote))^0*squote
-local arguments=lparent*Ct((Cs((nested+(quoted+1-S("),")))^1)+S(", "))^0)*rparent
-local macros=lua.macros or {}
-lua.macros=macros
-local patterns={}
-local definitions={}
-local resolve
-local subparser
-local report_lua=function(...)
- if logs and logs.reporter then
- report_lua=logs.reporter("system","lua")
- report_lua(...)
- else
- print(format(...))
- end
-end
-local safeguard=P("local")*whitespace^1*name*(whitespace+P("="))
-resolve=safeguard+C(C(name)*(arguments^-1))/function(raw,s,a)
- local d=definitions[s]
- if d then
- if a then
- local n=#a
- local p=patterns[s][n]
- if p then
- local d=d[n]
- for i=1,n do
- a[i]=lpegmatch(subparser,a[i]) or a[i]
- end
- return lpegmatch(p,d,1,a) or d
- else
- return raw
- end
- else
- return d[0] or raw
- end
- elseif a then
- for i=1,#a do
- a[i]=lpegmatch(subparser,a[i]) or a[i]
- end
- return s.."("..concat(a,",")..")"
- else
- return raw
- end
-end
-subparser=Cs((resolve+P(1))^1)
-local enddefine=P("#enddefine")/""
-local beginregister=(C(name)*(arguments+Cc(false))*C((1-enddefine)^1)*enddefine)/function(k,a,v)
- local n=0
- if a then
- n=#a
- local pattern=P(false)
- for i=1,n do
- pattern=pattern+(P(a[i])*Carg(1))/function(t) return t[i] end
- end
- pattern=Cs((pattern+P(1))^1)
- local p=patterns[k]
- if not p then
- p={ [0]=false,false,false,false,false,false,false,false,false }
- patterns[k]=p
- end
- p[n]=pattern
- end
- local d=definitions[k]
- if not d then
- d={ a=a,[0]=false,false,false,false,false,false,false,false,false }
- definitions[k]=d
- end
- d[n]=lpegmatch(subparser,v) or v
- return ""
-end
-local register=(Cs(name)*(arguments+Cc(false))*spaces^0*Cs(body))/function(k,a,v)
- local n=0
- if a then
- n=#a
- local pattern=P(false)
- for i=1,n do
- pattern=pattern+(P(a[i])*Carg(1))/function(t) return t[i] end
- end
- pattern=Cs((pattern+P(1))^1)
- local p=patterns[k]
- if not p then
- p={ [0]=false,false,false,false,false,false,false,false,false }
- patterns[k]=p
- end
- p[n]=pattern
- end
- local d=definitions[k]
- if not d then
- d={ a=a,[0]=false,false,false,false,false,false,false,false,false }
- definitions[k]=d
- end
- d[n]=lpegmatch(subparser,v) or v
- return ""
-end
-local unregister=(C(name)*spaces^0*(arguments+Cc(false)))/function(k,a)
- local n=0
- if a then
- n=#a
- local p=patterns[k]
- if p then
- p[n]=false
- end
- end
- local d=definitions[k]
- if d then
- d[n]=false
- end
- return ""
-end
-local begindefine=(P("begindefine")*spaces^0/"")*beginregister
-local define=(P("define" )*spaces^0/"")*register
-local undefine=(P("undefine" )*spaces^0/"")*unregister
-local parser=Cs((((P("#")/"")*(define+begindefine+undefine)*(newline^0/"") )+resolve+P(1) )^0 )
-function macros.reset()
- definitions={}
- patterns={}
-end
-function macros.showdefinitions()
- for name,list in table.sortedhash(definitions) do
- local arguments=list.a
- if arguments then
- arguments="("..concat(arguments,",")..")"
- else
- arguments=""
- end
- print("macro: "..name..arguments)
- for i=0,#list do
- local l=list[i]
- if l then
- print(" "..l)
- end
- end
- end
-end
-function macros.resolvestring(str)
- return lpegmatch(parser,str) or str
-end
-function macros.resolving()
- return next(patterns)
-end
-local function reload(path,name,data)
- local only=match(name,".-([^/]+)%.lua")
- if only and only~="" then
- local name=path.."/"..only
- local f=io.open(name,"wb")
- f:write(data)
- f:close()
- local f=loadfile(name)
- os.remove(name)
- return f
- end
-end
-local function reload(path,name,data)
- if path and path~="" then
- local only=string.match(name,".-([^/]+)%.lua")
- if only and only~="" then
- local name=path.."/"..only.."-macro.lua"
- local f=io.open(name,"wb")
- if f then
- f:write(data)
- f:close()
- local l=loadfile(name)
- os.remove(name)
- return l
- end
- end
- end
- return load(data,name)
-end
-local function loaded(name,trace,detail)
- local f=io.open(name,"rb")
- if not f then
- return false,format("file '%s' not found",name)
- end
- local c=f:read("*a")
- if not c then
- return false,format("file '%s' is invalid",name)
- end
- f:close()
- local n=lpegmatch(parser,c)
- if trace then
- if #n~=#c then
- report_lua("macros expanded in '%s' (%i => %i bytes)",name,#c,#n)
- if detail then
- report_lua()
- report_lua(n)
- report_lua()
- end
- elseif detail then
- report_lua("no macros expanded in '%s'",name)
- end
- end
- return reload(lfs and lfs.currentdir(),name,n)
-end
-macros.loaded=loaded
-function required(name,trace)
- local filename=file.addsuffix(name,"lua")
- local fullname=resolvers and resolvers.findfile(filename) or filename
- if not fullname or fullname=="" then
- return false
- end
- local codeblob=package.loaded[fullname]
- if codeblob then
- return codeblob
- end
- local code,message=loaded(fullname,macros,trace,trace)
- if type(code)=="function" then
- code=code()
- else
- report_lua("error when loading '%s'",fullname)
- return false,message
- end
- if code==nil then
- code=false
- end
- package.loaded[fullname]=code
- return code
-end
-macros.required=required
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-sandbox"] = package.loaded["l-sandbox"] or true
-
--- original size: 9604, stripped down to: 6394
-
-if not modules then modules={} end modules ['l-sandbox']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local global=_G
-local next=next
-local unpack=unpack or table.unpack
-local type=type
-local tprint=texio and texio.write_nl or print
-local tostring=tostring
-local format=string.format
-local concat=table.concat
-local sort=table.sort
-local gmatch=string.gmatch
-local gsub=string.gsub
-local requiem=require
-sandbox={}
-local sandboxed=false
-local overloads={}
-local skiploads={}
-local initializers={}
-local finalizers={}
-local originals={}
-local comments={}
-local trace=false
-local logger=false
-local blocked={}
-local function report(...)
- tprint("sandbox ! "..format(...))
-end
-sandbox.report=report
-function sandbox.setreporter(r)
- report=r
- sandbox.report=r
-end
-function sandbox.settrace(v)
- trace=v
-end
-function sandbox.setlogger(l)
- logger=type(l)=="function" and l or false
-end
-local function register(func,overload,comment)
- if type(func)=="function" then
- if type(overload)=="string" then
- comment=overload
- overload=nil
- end
- local function f(...)
- if sandboxed then
- local overload=overloads[f]
- if overload then
- if logger then
- local result={ overload(func,...) }
- logger {
- comment=comments[f] or tostring(f),
- arguments={... },
- result=result[1] and true or false,
- }
- return unpack(result)
- else
- return overload(func,...)
- end
- else
- end
- else
- return func(...)
- end
- end
- if comment then
- comments[f]=comment
- if trace then
- report("registering function: %s",comment)
- end
- end
- overloads[f]=overload or false
- originals[f]=func
- return f
- end
-end
-local function redefine(func,comment)
- if type(func)=="function" then
- skiploads[func]=comment or comments[func] or "unknown"
- if overloads[func]==false then
- overloads[func]=nil
- end
- end
-end
-sandbox.register=register
-sandbox.redefine=redefine
-function sandbox.original(func)
- return originals and originals[func] or func
-end
-function sandbox.overload(func,overload,comment)
- comment=comment or comments[func] or "?"
- if type(func)~="function" then
- if trace then
- report("overloading unknown function: %s",comment)
- end
- elseif type(overload)~="function" then
- if trace then
- report("overloading function with bad overload: %s",comment)
- end
- elseif overloads[func]==nil then
- if trace then
- report("function is not registered: %s",comment)
- end
- elseif skiploads[func] then
- if trace then
- report("function is not skipped: %s",comment)
- end
- else
- if trace then
- report("overloading function: %s",comment)
- end
- overloads[func]=overload
- end
- return func
-end
-local function whatever(specification,what,target)
- if type(specification)~="table" then
- report("%s needs a specification",what)
- elseif type(specification.category)~="string" or type(specification.action)~="function" then
- report("%s needs a category and action",what)
- elseif not sandboxed then
- target[#target+1]=specification
- elseif trace then
- report("already enabled, discarding %s",what)
- end
-end
-function sandbox.initializer(specification)
- whatever(specification,"initializer",initializers)
-end
-function sandbox.finalizer(specification)
- whatever(specification,"finalizer",finalizers)
-end
-function require(name)
- local n=gsub(name,"^.*[\\/]","")
- local n=gsub(n,"[%.].*$","")
- local b=blocked[n]
- if b==false then
- return nil
- elseif b then
- if trace then
- report("using blocked: %s",n)
- end
- return b
- else
- if trace then
- report("requiring: %s",name)
- end
- return requiem(name)
- end
-end
-function blockrequire(name,lib)
- if trace then
- report("preventing reload of: %s",name)
- end
- blocked[name]=lib or _G[name] or false
-end
-function sandbox.enable()
- if not sandboxed then
- debug={
- traceback=debug.traceback,
- }
- for i=1,#initializers do
- initializers[i].action()
- end
- for i=1,#finalizers do
- finalizers[i].action()
- end
- local nnot=0
- local nyes=0
- local cnot={}
- local cyes={}
- local skip={}
- for k,v in next,overloads do
- local c=comments[k]
- if v then
- if c then
- cyes[#cyes+1]=c
- else
- nyes=nyes+1
- end
- else
- if c then
- cnot[#cnot+1]=c
- else
- nnot=nnot+1
- end
- end
- end
- for k,v in next,skiploads do
- skip[#skip+1]=v
- end
- if #cyes>0 then
- sort(cyes)
- report("overloaded known: %s",concat(cyes," | "))
- end
- if nyes>0 then
- report("overloaded unknown: %s",nyes)
- end
- if #cnot>0 then
- sort(cnot)
- report("not overloaded known: %s",concat(cnot," | "))
- end
- if nnot>0 then
- report("not overloaded unknown: %s",nnot)
- end
- if #skip>0 then
- sort(skip)
- report("not overloaded redefined: %s",concat(skip," | "))
- end
- initializers=nil
- finalizers=nil
- originals=nil
- sandboxed=true
- end
-end
-blockrequire("lfs",lfs)
-blockrequire("io",io)
-blockrequire("os",os)
-blockrequire("ffi",ffi)
-local function supported(library)
- local l=_G[library]
- return l
-end
-loadfile=register(loadfile,"loadfile")
-if supported("lua") then
- lua.openfile=register(lua.openfile,"lua.openfile")
-end
-if supported("io") then
- io.open=register(io.open,"io.open")
- io.popen=register(io.popen,"io.popen")
- io.lines=register(io.lines,"io.lines")
- io.output=register(io.output,"io.output")
- io.input=register(io.input,"io.input")
-end
-if supported("os") then
- os.execute=register(os.execute,"os.execute")
- os.spawn=register(os.spawn,"os.spawn")
- os.exec=register(os.exec,"os.exec")
- os.rename=register(os.rename,"os.rename")
- os.remove=register(os.remove,"os.remove")
-end
-if supported("lfs") then
- lfs.chdir=register(lfs.chdir,"lfs.chdir")
- lfs.mkdir=register(lfs.mkdir,"lfs.mkdir")
- lfs.rmdir=register(lfs.rmdir,"lfs.rmdir")
- lfs.isfile=register(lfs.isfile,"lfs.isfile")
- lfs.isdir=register(lfs.isdir,"lfs.isdir")
- lfs.attributes=register(lfs.attributes,"lfs.attributes")
- lfs.dir=register(lfs.dir,"lfs.dir")
- lfs.lock_dir=register(lfs.lock_dir,"lfs.lock_dir")
- lfs.touch=register(lfs.touch,"lfs.touch")
- lfs.link=register(lfs.link,"lfs.link")
- lfs.setmode=register(lfs.setmode,"lfs.setmode")
- lfs.readlink=register(lfs.readlink,"lfs.readlink")
- lfs.shortname=register(lfs.shortname,"lfs.shortname")
- lfs.symlinkattributes=register(lfs.symlinkattributes,"lfs.symlinkattributes")
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-package"] = package.loaded["l-package"] or true
-
--- original size: 12566, stripped down to: 8937
-
-if not modules then modules={} end modules ['l-package']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,unpack=type,unpack
-local gsub,format,find=string.gsub,string.format,string.find
-local insert,remove=table.insert,table.remove
-local P,S,Cs,lpegmatch=lpeg.P,lpeg.S,lpeg.Cs,lpeg.match
-local package=package
-local searchers=package.searchers or package.loaders
-local filejoin=file and file.join or function(path,name) return path.."/"..name end
-local isreadable=file and file.is_readable or function(name) local f=io.open(name) if f then f:close() return true end end
-local addsuffix=file and file.addsuffix or function(name,suffix) return name.."."..suffix end
-local function cleanpath(path)
- return path
-end
-local pattern=Cs((((1-S("\\/"))^0*(S("\\/")^1/"/"))^0*(P(".")^1/"/"+P(1))^1)*-1)
-local function lualibfile(name)
- return lpegmatch(pattern,name) or name
-end
-local offset=luarocks and 1 or 0
-local helpers=package.helpers or {
- cleanpath=cleanpath,
- lualibfile=lualibfile,
- trace=false,
- report=function(...) print(format(...)) end,
- builtin={
- ["preload table"]=searchers[1+offset],
- ["path specification"]=searchers[2+offset],
- ["cpath specification"]=searchers[3+offset],
- ["all in one fallback"]=searchers[4+offset],
- },
- methods={},
- sequence={
- "reset loaded",
- "already loaded",
- "preload table",
- "qualified path",
- "lua extra list",
- "lib extra list",
- "path specification",
- "cpath specification",
- "all in one fallback",
- "not loaded",
- }
-}
-package.helpers=helpers
-local methods=helpers.methods
-local builtin=helpers.builtin
-local extraluapaths={}
-local extralibpaths={}
-local checkedfiles={}
-local luapaths=nil
-local libpaths=nil
-local oldluapath=nil
-local oldlibpath=nil
-local nofextralua=-1
-local nofextralib=-1
-local nofpathlua=-1
-local nofpathlib=-1
-local function listpaths(what,paths)
- local nofpaths=#paths
- if nofpaths>0 then
- for i=1,nofpaths do
- helpers.report("using %s path %i: %s",what,i,paths[i])
- end
- else
- helpers.report("no %s paths defined",what)
- end
- return nofpaths
-end
-local function getextraluapaths()
- if helpers.trace and #extraluapaths~=nofextralua then
- nofextralua=listpaths("extra lua",extraluapaths)
- end
- return extraluapaths
-end
-local function getextralibpaths()
- if helpers.trace and #extralibpaths~=nofextralib then
- nofextralib=listpaths("extra lib",extralibpaths)
- end
- return extralibpaths
-end
-local function getluapaths()
- local luapath=package.path or ""
- if oldluapath~=luapath then
- luapaths=file.splitpath(luapath,";")
- oldluapath=luapath
- nofpathlua=-1
- end
- if helpers.trace and #luapaths~=nofpathlua then
- nofpathlua=listpaths("builtin lua",luapaths)
- end
- return luapaths
-end
-local function getlibpaths()
- local libpath=package.cpath or ""
- if oldlibpath~=libpath then
- libpaths=file.splitpath(libpath,";")
- oldlibpath=libpath
- nofpathlib=-1
- end
- if helpers.trace and #libpaths~=nofpathlib then
- nofpathlib=listpaths("builtin lib",libpaths)
- end
- return libpaths
-end
-package.luapaths=getluapaths
-package.libpaths=getlibpaths
-package.extraluapaths=getextraluapaths
-package.extralibpaths=getextralibpaths
-local hashes={
- lua={},
- lib={},
-}
-local function registerpath(tag,what,target,...)
- local pathlist={... }
- local cleanpath=helpers.cleanpath
- local trace=helpers.trace
- local report=helpers.report
- local hash=hashes[what]
- local function add(path)
- local path=cleanpath(path)
- if not hash[path] then
- target[#target+1]=path
- hash[path]=true
- if trace then
- report("registered %s path %s: %s",tag,#target,path)
- end
- else
- if trace then
- report("duplicate %s path: %s",tag,path)
- end
- end
- end
- for p=1,#pathlist do
- local path=pathlist[p]
- if type(path)=="table" then
- for i=1,#path do
- add(path[i])
- end
- else
- add(path)
- end
- end
-end
-local function pushpath(tag,what,target,path)
- local path=helpers.cleanpath(path)
- insert(target,1,path)
- if helpers.trace then
- helpers.report("pushing %s path in front: %s",tag,path)
- end
-end
-local function poppath(tag,what,target)
- local path=remove(target,1)
- if helpers.trace then
- if path then
- helpers.report("popping %s path from front: %s",tag,path)
- else
- helpers.report("no %s path to pop",tag)
- end
- end
-end
-helpers.registerpath=registerpath
-function package.extraluapath(...)
- registerpath("extra lua","lua",extraluapaths,...)
-end
-function package.pushluapath(path)
- pushpath("extra lua","lua",extraluapaths,path)
-end
-function package.popluapath()
- poppath("extra lua","lua",extraluapaths)
-end
-function package.extralibpath(...)
- registerpath("extra lib","lib",extralibpaths,...)
-end
-function package.pushlibpath(path)
- pushpath("extra lib","lib",extralibpaths,path)
-end
-function package.poplibpath()
- poppath("extra lib","lua",extralibpaths)
-end
-local function loadedaslib(resolved,rawname)
- local base=gsub(rawname,"%.","_")
- local init="luaopen_"..gsub(base,"%.","_")
- local data={ resolved,init,"" }
- checkedfiles[#checkedfiles+1]=data
- if helpers.trace then
- helpers.report("calling loadlib with '%s' with init '%s'",resolved,init)
- end
- local a,b,c=package.loadlib(resolved,init)
- if not a and type(b)=="string" then
- data[3]=string.fullstrip(b or "unknown error")
- end
- return a,b,c
-end
-helpers.loadedaslib=loadedaslib
-local function loadedbypath(name,rawname,paths,islib,what)
- local trace=helpers.trace
- for p=1,#paths do
- local path=paths[p]
- local resolved=filejoin(path,name)
- if trace then
- helpers.report("%s path, identifying '%s' on '%s'",what,name,path)
- end
- if isreadable(resolved) then
- if trace then
- helpers.report("%s path, '%s' found on '%s'",what,name,resolved)
- end
- if islib then
- return loadedaslib(resolved,rawname)
- else
- return loadfile(resolved)
- end
- end
- end
-end
-helpers.loadedbypath=loadedbypath
-local function loadedbyname(name,rawname)
- if find(name,"^/") or find(name,"^[a-zA-Z]:/") then
- local trace=helpers.trace
- if trace then
- helpers.report("qualified name, identifying '%s'",what,name)
- end
- if isreadable(name) then
- if trace then
- helpers.report("qualified name, '%s' found",what,name)
- end
- return loadfile(name)
- end
- end
-end
-helpers.loadedbyname=loadedbyname
-methods["reset loaded"]=function(name)
- checkedfiles={}
- return false
-end
-methods["already loaded"]=function(name)
- return package.loaded[name]
-end
-methods["preload table"]=function(name)
- local f=builtin["preload table"]
- if f then
- return f(name)
- end
-end
-methods["qualified path"]=function(name)
- return loadedbyname(addsuffix(lualibfile(name),"lua"),name)
-end
-methods["lua extra list"]=function(name)
- return loadedbypath(addsuffix(lualibfile(name),"lua"),name,getextraluapaths(),false,"lua")
-end
-methods["lib extra list"]=function(name)
- return loadedbypath(addsuffix(lualibfile(name),os.libsuffix),name,getextralibpaths(),true,"lib")
-end
-methods["path specification"]=function(name)
- local f=builtin["path specification"]
- if f then
- getluapaths()
- return f(name)
- end
-end
-methods["cpath specification"]=function(name)
- local f=builtin["cpath specification"]
- if f then
- getlibpaths()
- return f(name)
- end
-end
-methods["all in one fallback"]=function(name)
- local f=builtin["all in one fallback"]
- if f then
- return f(name)
- end
-end
-methods["not loaded"]=function(name)
- if helpers.trace then
- helpers.report("unable to locate '%s'",name or "?")
- for i=1,#checkedfiles do
- helpers.report("checked file '%s', initializer '%s', message '%s'",unpack(checkedfiles[i]))
- end
- end
- return nil
-end
-local level=0
-local used={}
-helpers.traceused=false
-function helpers.loaded(name)
- local sequence=helpers.sequence
- level=level+1
- for i=1,#sequence do
- local method=sequence[i]
- local lookup=method and methods[method]
- if type(lookup)=="function" then
- if helpers.trace then
- helpers.report("%s, level '%s', method '%s', name '%s'","locating",level,method,name)
- end
- local result,rest=lookup(name)
- if type(result)=="function" then
- if helpers.trace then
- helpers.report("%s, level '%s', method '%s', name '%s'","found",level,method,name)
- end
- if helpers.traceused then
- used[#used+1]={ level=level,name=name }
- end
- level=level-1
- return result,rest
- end
- end
- end
- level=level-1
- return nil
-end
-function helpers.showused()
- local n=#used
- if n>0 then
- helpers.report("%s libraries loaded:",n)
- helpers.report()
- for i=1,n do
- local u=used[i]
- helpers.report("%i %a",u.level,u.name)
- end
- helpers.report()
- end
-end
-function helpers.unload(name)
- if helpers.trace then
- if package.loaded[name] then
- helpers.report("unloading, name '%s', %s",name,"done")
- else
- helpers.report("unloading, name '%s', %s",name,"not loaded")
- end
- end
- package.loaded[name]=nil
-end
-table.insert(searchers,1,helpers.loaded)
-if context then
- package.path=""
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-lpeg"] = package.loaded["l-lpeg"] or true
-
--- original size: 38703, stripped down to: 19489
-
-if not modules then modules={} end modules ['l-lpeg']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-lpeg=require("lpeg")
-local lpeg=lpeg
-if not lpeg.print then function lpeg.print(...) print(lpeg.pcode(...)) end end
-local type,next,tostring=type,next,tostring
-local byte,char,gmatch,format=string.byte,string.char,string.gmatch,string.format
-local floor=math.floor
-local P,R,S,V,Ct,C,Cs,Cc,Cp,Cmt=lpeg.P,lpeg.R,lpeg.S,lpeg.V,lpeg.Ct,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Cp,lpeg.Cmt
-local lpegtype,lpegmatch,lpegprint=lpeg.type,lpeg.match,lpeg.print
-if setinspector then
- setinspector("lpeg",function(v) if lpegtype(v) then lpegprint(v) return true end end)
-end
-lpeg.patterns=lpeg.patterns or {}
-local patterns=lpeg.patterns
-local anything=P(1)
-local endofstring=P(-1)
-local alwaysmatched=P(true)
-patterns.anything=anything
-patterns.endofstring=endofstring
-patterns.beginofstring=alwaysmatched
-patterns.alwaysmatched=alwaysmatched
-local sign=S('+-')
-local zero=P('0')
-local digit=R('09')
-local digits=digit^1
-local octdigit=R("07")
-local octdigits=octdigit^1
-local lowercase=R("az")
-local uppercase=R("AZ")
-local underscore=P("_")
-local hexdigit=digit+lowercase+uppercase
-local hexdigits=hexdigit^1
-local cr,lf,crlf=P("\r"),P("\n"),P("\r\n")
-local newline=P("\r")*(P("\n")+P(true))+P("\n")
-local escaped=P("\\")*anything
-local squote=P("'")
-local dquote=P('"')
-local space=P(" ")
-local period=P(".")
-local comma=P(",")
-local utfbom_32_be=P('\000\000\254\255')
-local utfbom_32_le=P('\255\254\000\000')
-local utfbom_16_be=P('\254\255')
-local utfbom_16_le=P('\255\254')
-local utfbom_8=P('\239\187\191')
-local utfbom=utfbom_32_be+utfbom_32_le+utfbom_16_be+utfbom_16_le+utfbom_8
-local utftype=utfbom_32_be*Cc("utf-32-be")+utfbom_32_le*Cc("utf-32-le")+utfbom_16_be*Cc("utf-16-be")+utfbom_16_le*Cc("utf-16-le")+utfbom_8*Cc("utf-8")+alwaysmatched*Cc("utf-8")
-local utfstricttype=utfbom_32_be*Cc("utf-32-be")+utfbom_32_le*Cc("utf-32-le")+utfbom_16_be*Cc("utf-16-be")+utfbom_16_le*Cc("utf-16-le")+utfbom_8*Cc("utf-8")
-local utfoffset=utfbom_32_be*Cc(4)+utfbom_32_le*Cc(4)+utfbom_16_be*Cc(2)+utfbom_16_le*Cc(2)+utfbom_8*Cc(3)+Cc(0)
-local utf8next=R("\128\191")
-patterns.utfbom_32_be=utfbom_32_be
-patterns.utfbom_32_le=utfbom_32_le
-patterns.utfbom_16_be=utfbom_16_be
-patterns.utfbom_16_le=utfbom_16_le
-patterns.utfbom_8=utfbom_8
-patterns.utf_16_be_nl=P("\000\r\000\n")+P("\000\r")+P("\000\n")
-patterns.utf_16_le_nl=P("\r\000\n\000")+P("\r\000")+P("\n\000")
-patterns.utf_32_be_nl=P("\000\000\000\r\000\000\000\n")+P("\000\000\000\r")+P("\000\000\000\n")
-patterns.utf_32_le_nl=P("\r\000\000\000\n\000\000\000")+P("\r\000\000\000")+P("\n\000\000\000")
-patterns.utf8one=R("\000\127")
-patterns.utf8two=R("\194\223")*utf8next
-patterns.utf8three=R("\224\239")*utf8next*utf8next
-patterns.utf8four=R("\240\244")*utf8next*utf8next*utf8next
-patterns.utfbom=utfbom
-patterns.utftype=utftype
-patterns.utfstricttype=utfstricttype
-patterns.utfoffset=utfoffset
-local utf8char=patterns.utf8one+patterns.utf8two+patterns.utf8three+patterns.utf8four
-local validutf8char=utf8char^0*endofstring*Cc(true)+Cc(false)
-local utf8character=P(1)*R("\128\191")^0
-patterns.utf8=utf8char
-patterns.utf8char=utf8char
-patterns.utf8character=utf8character
-patterns.validutf8=validutf8char
-patterns.validutf8char=validutf8char
-local eol=S("\n\r")
-local spacer=S(" \t\f\v")
-local whitespace=eol+spacer
-local nonspacer=1-spacer
-local nonwhitespace=1-whitespace
-patterns.eol=eol
-patterns.spacer=spacer
-patterns.whitespace=whitespace
-patterns.nonspacer=nonspacer
-patterns.nonwhitespace=nonwhitespace
-local stripper=spacer^0*C((spacer^0*nonspacer^1)^0)
-local fullstripper=whitespace^0*C((whitespace^0*nonwhitespace^1)^0)
-local collapser=Cs(spacer^0/""*nonspacer^0*((spacer^0/" "*nonspacer^1)^0))
-local nospacer=Cs((whitespace^1/""+nonwhitespace^1)^0)
-local b_collapser=Cs(whitespace^0/""*(nonwhitespace^1+whitespace^1/" ")^0)
-local m_collapser=Cs((nonwhitespace^1+whitespace^1/" ")^0)
-local e_collapser=Cs((whitespace^1*endofstring/""+nonwhitespace^1+whitespace^1/" ")^0)
-local x_collapser=Cs((nonwhitespace^1+whitespace^1/"" )^0)
-local b_stripper=Cs(spacer^0/""*(nonspacer^1+spacer^1/" ")^0)
-local m_stripper=Cs((nonspacer^1+spacer^1/" ")^0)
-local e_stripper=Cs((spacer^1*endofstring/""+nonspacer^1+spacer^1/" ")^0)
-local x_stripper=Cs((nonspacer^1+spacer^1/"" )^0)
-patterns.stripper=stripper
-patterns.fullstripper=fullstripper
-patterns.collapser=collapser
-patterns.nospacer=nospacer
-patterns.b_collapser=b_collapser
-patterns.m_collapser=m_collapser
-patterns.e_collapser=e_collapser
-patterns.x_collapser=x_collapser
-patterns.b_stripper=b_stripper
-patterns.m_stripper=m_stripper
-patterns.e_stripper=e_stripper
-patterns.x_stripper=x_stripper
-patterns.lowercase=lowercase
-patterns.uppercase=uppercase
-patterns.letter=patterns.lowercase+patterns.uppercase
-patterns.space=space
-patterns.tab=P("\t")
-patterns.spaceortab=patterns.space+patterns.tab
-patterns.newline=newline
-patterns.emptyline=newline^1
-patterns.equal=P("=")
-patterns.comma=comma
-patterns.commaspacer=comma*spacer^0
-patterns.period=period
-patterns.colon=P(":")
-patterns.semicolon=P(";")
-patterns.underscore=underscore
-patterns.escaped=escaped
-patterns.squote=squote
-patterns.dquote=dquote
-patterns.nosquote=(escaped+(1-squote))^0
-patterns.nodquote=(escaped+(1-dquote))^0
-patterns.unsingle=(squote/"")*patterns.nosquote*(squote/"")
-patterns.undouble=(dquote/"")*patterns.nodquote*(dquote/"")
-patterns.unquoted=patterns.undouble+patterns.unsingle
-patterns.unspacer=((patterns.spacer^1)/"")^0
-patterns.singlequoted=squote*patterns.nosquote*squote
-patterns.doublequoted=dquote*patterns.nodquote*dquote
-patterns.quoted=patterns.doublequoted+patterns.singlequoted
-patterns.digit=digit
-patterns.digits=digits
-patterns.octdigit=octdigit
-patterns.octdigits=octdigits
-patterns.hexdigit=hexdigit
-patterns.hexdigits=hexdigits
-patterns.sign=sign
-patterns.cardinal=digits
-patterns.integer=sign^-1*digits
-patterns.unsigned=digit^0*period*digits
-patterns.float=sign^-1*patterns.unsigned
-patterns.cunsigned=digit^0*comma*digits
-patterns.cpunsigned=digit^0*(period+comma)*digits
-patterns.cfloat=sign^-1*patterns.cunsigned
-patterns.cpfloat=sign^-1*patterns.cpunsigned
-patterns.number=patterns.float+patterns.integer
-patterns.cnumber=patterns.cfloat+patterns.integer
-patterns.cpnumber=patterns.cpfloat+patterns.integer
-patterns.oct=zero*octdigits
-patterns.octal=patterns.oct
-patterns.HEX=zero*P("X")*(digit+uppercase)^1
-patterns.hex=zero*P("x")*(digit+lowercase)^1
-patterns.hexadecimal=zero*S("xX")*hexdigits
-patterns.hexafloat=sign^-1*zero*S("xX")*(hexdigit^0*period*hexdigits+hexdigits*period*hexdigit^0+hexdigits)*(S("pP")*sign^-1*hexdigits)^-1
-patterns.decafloat=sign^-1*(digit^0*period*digits+digits*period*digit^0+digits)*S("eE")*sign^-1*digits
-patterns.propername=(uppercase+lowercase+underscore)*(uppercase+lowercase+underscore+digit)^0*endofstring
-patterns.somecontent=(anything-newline-space)^1
-patterns.beginline=#(1-newline)
-patterns.longtostring=Cs(whitespace^0/""*((patterns.quoted+nonwhitespace^1+whitespace^1/""*(endofstring+Cc(" ")))^0))
-local function anywhere(pattern)
- return (1-P(pattern))^0*P(pattern)
-end
-lpeg.anywhere=anywhere
-function lpeg.instringchecker(p)
- p=anywhere(p)
- return function(str)
- return lpegmatch(p,str) and true or false
- end
-end
-function lpeg.splitter(pattern,action)
- if action then
- return (((1-P(pattern))^1)/action+1)^0
- else
- return (Cs((1-P(pattern))^1)+1)^0
- end
-end
-function lpeg.tsplitter(pattern,action)
- if action then
- return Ct((((1-P(pattern))^1)/action+1)^0)
- else
- return Ct((Cs((1-P(pattern))^1)+1)^0)
- end
-end
-local splitters_s,splitters_m,splitters_t={},{},{}
-local function splitat(separator,single)
- local splitter=(single and splitters_s[separator]) or splitters_m[separator]
- if not splitter then
- separator=P(separator)
- local other=C((1-separator)^0)
- if single then
- local any=anything
- splitter=other*(separator*C(any^0)+"")
- splitters_s[separator]=splitter
- else
- splitter=other*(separator*other)^0
- splitters_m[separator]=splitter
- end
- end
- return splitter
-end
-local function tsplitat(separator)
- local splitter=splitters_t[separator]
- if not splitter then
- splitter=Ct(splitat(separator))
- splitters_t[separator]=splitter
- end
- return splitter
-end
-lpeg.splitat=splitat
-lpeg.tsplitat=tsplitat
-function string.splitup(str,separator)
- if not separator then
- separator=","
- end
- return lpegmatch(splitters_m[separator] or splitat(separator),str)
-end
-local cache={}
-function lpeg.split(separator,str)
- local c=cache[separator]
- if not c then
- c=tsplitat(separator)
- cache[separator]=c
- end
- return lpegmatch(c,str)
-end
-function string.split(str,separator)
- if separator then
- local c=cache[separator]
- if not c then
- c=tsplitat(separator)
- cache[separator]=c
- end
- return lpegmatch(c,str)
- else
- return { str }
- end
-end
-local spacing=patterns.spacer^0*newline
-local empty=spacing*Cc("")
-local nonempty=Cs((1-spacing)^1)*spacing^-1
-local content=(empty+nonempty)^1
-patterns.textline=content
-local linesplitter=tsplitat(newline)
-patterns.linesplitter=linesplitter
-function string.splitlines(str)
- return lpegmatch(linesplitter,str)
-end
-local cache={}
-function lpeg.checkedsplit(separator,str)
- local c=cache[separator]
- if not c then
- separator=P(separator)
- local other=C((1-separator)^1)
- c=Ct(separator^0*other*(separator^1*other)^0)
- cache[separator]=c
- end
- return lpegmatch(c,str)
-end
-function string.checkedsplit(str,separator)
- local c=cache[separator]
- if not c then
- separator=P(separator)
- local other=C((1-separator)^1)
- c=Ct(separator^0*other*(separator^1*other)^0)
- cache[separator]=c
- end
- return lpegmatch(c,str)
-end
-local function f2(s) local c1,c2=byte(s,1,2) return c1*64+c2-12416 end
-local function f3(s) local c1,c2,c3=byte(s,1,3) return (c1*64+c2)*64+c3-925824 end
-local function f4(s) local c1,c2,c3,c4=byte(s,1,4) return ((c1*64+c2)*64+c3)*64+c4-63447168 end
-local utf8byte=patterns.utf8one/byte+patterns.utf8two/f2+patterns.utf8three/f3+patterns.utf8four/f4
-patterns.utf8byte=utf8byte
-local cache={}
-function lpeg.stripper(str)
- if type(str)=="string" then
- local s=cache[str]
- if not s then
- s=Cs(((S(str)^1)/""+1)^0)
- cache[str]=s
- end
- return s
- else
- return Cs(((str^1)/""+1)^0)
- end
-end
-local cache={}
-function lpeg.keeper(str)
- if type(str)=="string" then
- local s=cache[str]
- if not s then
- s=Cs((((1-S(str))^1)/""+1)^0)
- cache[str]=s
- end
- return s
- else
- return Cs((((1-str)^1)/""+1)^0)
- end
-end
-function lpeg.frontstripper(str)
- return (P(str)+P(true))*Cs(anything^0)
-end
-function lpeg.endstripper(str)
- return Cs((1-P(str)*endofstring)^0)
-end
-function lpeg.replacer(one,two,makefunction,isutf)
- local pattern
- local u=isutf and utf8char or 1
- if type(one)=="table" then
- local no=#one
- local p=P(false)
- if no==0 then
- for k,v in next,one do
- p=p+P(k)/v
- end
- pattern=Cs((p+u)^0)
- elseif no==1 then
- local o=one[1]
- one,two=P(o[1]),o[2]
- pattern=Cs((one/two+u)^0)
- else
- for i=1,no do
- local o=one[i]
- p=p+P(o[1])/o[2]
- end
- pattern=Cs((p+u)^0)
- end
- else
- pattern=Cs((P(one)/(two or "")+u)^0)
- end
- if makefunction then
- return function(str)
- return lpegmatch(pattern,str)
- end
- else
- return pattern
- end
-end
-function lpeg.finder(lst,makefunction,isutf)
- local pattern
- if type(lst)=="table" then
- pattern=P(false)
- if #lst==0 then
- for k,v in next,lst do
- pattern=pattern+P(k)
- end
- else
- for i=1,#lst do
- pattern=pattern+P(lst[i])
- end
- end
- else
- pattern=P(lst)
- end
- if isutf then
- pattern=((utf8char or 1)-pattern)^0*pattern
- else
- pattern=(1-pattern)^0*pattern
- end
- if makefunction then
- return function(str)
- return lpegmatch(pattern,str)
- end
- else
- return pattern
- end
-end
-local splitters_f,splitters_s={},{}
-function lpeg.firstofsplit(separator)
- local splitter=splitters_f[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=C((1-pattern)^0)
- splitters_f[separator]=splitter
- end
- return splitter
-end
-function lpeg.secondofsplit(separator)
- local splitter=splitters_s[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=(1-pattern)^0*pattern*C(anything^0)
- splitters_s[separator]=splitter
- end
- return splitter
-end
-local splitters_s,splitters_p={},{}
-function lpeg.beforesuffix(separator)
- local splitter=splitters_s[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=C((1-pattern)^0)*pattern*endofstring
- splitters_s[separator]=splitter
- end
- return splitter
-end
-function lpeg.afterprefix(separator)
- local splitter=splitters_p[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=pattern*C(anything^0)
- splitters_p[separator]=splitter
- end
- return splitter
-end
-function lpeg.balancer(left,right)
- left,right=P(left),P(right)
- return P { left*((1-left-right)+V(1))^0*right }
-end
-function lpeg.counter(pattern,action)
- local n=0
- local pattern=(P(pattern)/function() n=n+1 end+anything)^0
- if action then
- return function(str) n=0;lpegmatch(pattern,str);action(n) end
- else
- return function(str) n=0;lpegmatch(pattern,str);return n end
- end
-end
-function lpeg.is_lpeg(p)
- return p and lpegtype(p)=="pattern"
-end
-function lpeg.oneof(list,...)
- if type(list)~="table" then
- list={ list,... }
- end
- local p=P(list[1])
- for l=2,#list do
- p=p+P(list[l])
- end
- return p
-end
-local sort=table.sort
-local function copyindexed(old)
- local new={}
- for i=1,#old do
- new[i]=old
- end
- return new
-end
-local function sortedkeys(tab)
- local keys,s={},0
- for key,_ in next,tab do
- s=s+1
- keys[s]=key
- end
- sort(keys)
- return keys
-end
-function lpeg.append(list,pp,delayed,checked)
- local p=pp
- if #list>0 then
- local keys=copyindexed(list)
- sort(keys)
- for i=#keys,1,-1 do
- local k=keys[i]
- if p then
- p=P(k)+p
- else
- p=P(k)
- end
- end
- elseif delayed then
- local keys=sortedkeys(list)
- if p then
- for i=1,#keys,1 do
- local k=keys[i]
- local v=list[k]
- p=P(k)/list+p
- end
- else
- for i=1,#keys do
- local k=keys[i]
- local v=list[k]
- if p then
- p=P(k)+p
- else
- p=P(k)
- end
- end
- if p then
- p=p/list
- end
- end
- elseif checked then
- local keys=sortedkeys(list)
- for i=1,#keys do
- local k=keys[i]
- local v=list[k]
- if p then
- if k==v then
- p=P(k)+p
- else
- p=P(k)/v+p
- end
- else
- if k==v then
- p=P(k)
- else
- p=P(k)/v
- end
- end
- end
- else
- local keys=sortedkeys(list)
- for i=1,#keys do
- local k=keys[i]
- local v=list[k]
- if p then
- p=P(k)/v+p
- else
- p=P(k)/v
- end
- end
- end
- return p
-end
-local p_false=P(false)
-local p_true=P(true)
-local lower=utf and utf.lower or string.lower
-local upper=utf and utf.upper or string.upper
-function lpeg.setutfcasers(l,u)
- lower=l or lower
- upper=u or upper
-end
-local function make1(t,rest)
- local p=p_false
- local keys=sortedkeys(t)
- for i=1,#keys do
- local k=keys[i]
- if k~="" then
- local v=t[k]
- if v==true then
- p=p+P(k)*p_true
- elseif v==false then
- else
- p=p+P(k)*make1(v,v[""])
- end
- end
- end
- if rest then
- p=p+p_true
- end
- return p
-end
-local function make2(t,rest)
- local p=p_false
- local keys=sortedkeys(t)
- for i=1,#keys do
- local k=keys[i]
- if k~="" then
- local v=t[k]
- if v==true then
- p=p+(P(lower(k))+P(upper(k)))*p_true
- elseif v==false then
- else
- p=p+(P(lower(k))+P(upper(k)))*make2(v,v[""])
- end
- end
- end
- if rest then
- p=p+p_true
- end
- return p
-end
-local function utfchartabletopattern(list,insensitive)
- local tree={}
- local n=#list
- if n==0 then
- for s in next,list do
- local t=tree
- local p,pk
- for c in gmatch(s,".") do
- if t==true then
- t={ [c]=true,[""]=true }
- p[pk]=t
- p=t
- t=false
- elseif t==false then
- t={ [c]=false }
- p[pk]=t
- p=t
- t=false
- else
- local tc=t[c]
- if not tc then
- tc=false
- t[c]=false
- end
- p=t
- t=tc
- end
- pk=c
- end
- if t==false then
- p[pk]=true
- elseif t==true then
- else
- t[""]=true
- end
- end
- else
- for i=1,n do
- local s=list[i]
- local t=tree
- local p,pk
- for c in gmatch(s,".") do
- if t==true then
- t={ [c]=true,[""]=true }
- p[pk]=t
- p=t
- t=false
- elseif t==false then
- t={ [c]=false }
- p[pk]=t
- p=t
- t=false
- else
- local tc=t[c]
- if not tc then
- tc=false
- t[c]=false
- end
- p=t
- t=tc
- end
- pk=c
- end
- if t==false then
- p[pk]=true
- elseif t==true then
- else
- t[""]=true
- end
- end
- end
- return (insensitive and make2 or make1)(tree)
-end
-lpeg.utfchartabletopattern=utfchartabletopattern
-function lpeg.utfreplacer(list,insensitive)
- local pattern=Cs((utfchartabletopattern(list,insensitive)/list+utf8character)^0)
- return function(str)
- return lpegmatch(pattern,str) or str
- end
-end
-patterns.containseol=lpeg.finder(eol)
-local function nextstep(n,step,result)
- local m=n%step
- local d=floor(n/step)
- if d>0 then
- local v=V(tostring(step))
- local s=result.start
- for i=1,d do
- if s then
- s=v*s
- else
- s=v
- end
- end
- result.start=s
- end
- if step>1 and result.start then
- local v=V(tostring(step/2))
- result[tostring(step)]=v*v
- end
- if step>0 then
- return nextstep(m,step/2,result)
- else
- return result
- end
-end
-function lpeg.times(pattern,n)
- return P(nextstep(n,2^16,{ "start",["1"]=pattern }))
-end
-do
- local trailingzeros=zero^0*-digit
- local stripper=Cs((
- digits*(
- period*trailingzeros/""+period*(digit-trailingzeros)^1*(trailingzeros/"")
- )+1
- )^0)
- lpeg.patterns.stripzeros=stripper
- local nonzero=digit-zero
- local trailingzeros=zero^1*endofstring
- local stripper=Cs((1-period)^0*(
- period*trailingzeros/""+period*(nonzero^1+(trailingzeros/"")+zero^1)^0+endofstring
- ))
- lpeg.patterns.stripzero=stripper
-end
-local byte_to_HEX={}
-local byte_to_hex={}
-local byte_to_dec={}
-local hex_to_byte={}
-for i=0,255 do
- local H=format("%02X",i)
- local h=format("%02x",i)
- local d=format("%03i",i)
- local c=char(i)
- byte_to_HEX[c]=H
- byte_to_hex[c]=h
- byte_to_dec[c]=d
- hex_to_byte[h]=c
- hex_to_byte[H]=c
-end
-local hextobyte=P(2)/hex_to_byte
-local bytetoHEX=P(1)/byte_to_HEX
-local bytetohex=P(1)/byte_to_hex
-local bytetodec=P(1)/byte_to_dec
-local hextobytes=Cs(hextobyte^0)
-local bytestoHEX=Cs(bytetoHEX^0)
-local bytestohex=Cs(bytetohex^0)
-local bytestodec=Cs(bytetodec^0)
-patterns.hextobyte=hextobyte
-patterns.bytetoHEX=bytetoHEX
-patterns.bytetohex=bytetohex
-patterns.bytetodec=bytetodec
-patterns.hextobytes=hextobytes
-patterns.bytestoHEX=bytestoHEX
-patterns.bytestohex=bytestohex
-patterns.bytestodec=bytestodec
-function string.toHEX(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(bytestoHEX,s)
- end
-end
-function string.tohex(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(bytestohex,s)
- end
-end
-function string.todec(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(bytestodec,s)
- end
-end
-function string.tobytes(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(hextobytes,s)
- end
-end
-local patterns={}
-local function containsws(what)
- local p=patterns[what]
- if not p then
- local p1=P(what)*(whitespace+endofstring)*Cc(true)
- local p2=whitespace*P(p1)
- p=P(p1)+P(1-p2)^0*p2+Cc(false)
- patterns[what]=p
- end
- return p
-end
-lpeg.containsws=containsws
-function string.containsws(str,what)
- return lpegmatch(patterns[what] or containsws(what),str)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-function"] = package.loaded["l-function"] or true
-
--- original size: 361, stripped down to: 317
-
-if not modules then modules={} end modules ['l-functions']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-functions=functions or {}
-function functions.dummy() end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-string"] = package.loaded["l-string"] or true
-
--- original size: 6644, stripped down to: 3410
-
-if not modules then modules={} end modules ['l-string']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local string=string
-local sub,gmatch,format,char,byte,rep,lower=string.sub,string.gmatch,string.format,string.char,string.byte,string.rep,string.lower
-local lpegmatch,patterns=lpeg.match,lpeg.patterns
-local P,S,C,Ct,Cc,Cs=lpeg.P,lpeg.S,lpeg.C,lpeg.Ct,lpeg.Cc,lpeg.Cs
-local unquoted=patterns.squote*C(patterns.nosquote)*patterns.squote+patterns.dquote*C(patterns.nodquote)*patterns.dquote
-function string.unquoted(str)
- return lpegmatch(unquoted,str) or str
-end
-function string.quoted(str)
- return format("%q",str)
-end
-function string.count(str,pattern)
- local n=0
- for _ in gmatch(str,pattern) do
- n=n+1
- end
- return n
-end
-function string.limit(str,n,sentinel)
- if #str>n then
- sentinel=sentinel or "..."
- return sub(str,1,(n-#sentinel))..sentinel
- else
- return str
- end
-end
-local stripper=patterns.stripper
-local fullstripper=patterns.fullstripper
-local collapser=patterns.collapser
-local nospacer=patterns.nospacer
-local longtostring=patterns.longtostring
-function string.strip(str)
- return str and lpegmatch(stripper,str) or ""
-end
-function string.fullstrip(str)
- return str and lpegmatch(fullstripper,str) or ""
-end
-function string.collapsespaces(str)
- return str and lpegmatch(collapser,str) or ""
-end
-function string.nospaces(str)
- return str and lpegmatch(nospacer,str) or ""
-end
-function string.longtostring(str)
- return str and lpegmatch(longtostring,str) or ""
-end
-local pattern=P(" ")^0*P(-1)
-function string.is_empty(str)
- if not str or str=="" then
- return true
- else
- return lpegmatch(pattern,str) and true or false
- end
-end
-local anything=patterns.anything
-local moreescapes=Cc("%")*S(".-+%?()[]*$^{}")
-local allescapes=Cc("%")*S(".-+%?()[]*")
-local someescapes=Cc("%")*S(".-+%()[]")
-local matchescapes=Cc(".")*S("*?")
-local pattern_m=Cs ((moreescapes+anything )^0 )
-local pattern_a=Cs ((allescapes+anything )^0 )
-local pattern_b=Cs ((someescapes+matchescapes+anything )^0 )
-local pattern_c=Cs (Cc("^")*(someescapes+matchescapes+anything )^0*Cc("$") )
-function string.escapedpattern(str,simple)
- return lpegmatch(simple and pattern_b or pattern_a,str)
-end
-function string.topattern(str,lowercase,strict)
- if str=="" or type(str)~="string" then
- return ".*"
- elseif strict=="all" then
- str=lpegmatch(pattern_m,str)
- elseif strict then
- str=lpegmatch(pattern_c,str)
- else
- str=lpegmatch(pattern_b,str)
- end
- if lowercase then
- return lower(str)
- else
- return str
- end
-end
-function string.valid(str,default)
- return (type(str)=="string" and str~="" and str) or default or nil
-end
-string.itself=function(s) return s end
-local pattern_c=Ct(C(1)^0)
-local pattern_b=Ct((C(1)/byte)^0)
-function string.totable(str,bytes)
- return lpegmatch(bytes and pattern_b or pattern_c,str)
-end
-local replacer=lpeg.replacer("@","%%")
-function string.tformat(fmt,...)
- return format(lpegmatch(replacer,fmt),...)
-end
-string.quote=string.quoted
-string.unquote=string.unquoted
-if not string.bytetable then
- local limit=5000
- function string.bytetable(str)
- local n=#str
- if n>limit then
- local t={ byte(str,1,limit) }
- for i=limit+1,n do
- t[i]=byte(str,i)
- end
- return t
- else
- return { byte(str,1,n) }
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-table"] = package.loaded["l-table"] or true
-
--- original size: 41758, stripped down to: 22643
-
-if not modules then modules={} end modules ['l-table']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,next,tostring,tonumber,select,rawget=type,next,tostring,tonumber,select,rawget
-local table,string=table,string
-local concat,sort=table.concat,table.sort
-local format,lower,dump=string.format,string.lower,string.dump
-local getmetatable,setmetatable=getmetatable,setmetatable
-local lpegmatch,patterns=lpeg.match,lpeg.patterns
-local floor=math.floor
-local stripper=patterns.stripper
-function table.getn(t)
- return t and #t
-end
-function table.strip(tab)
- local lst={}
- local l=0
- for i=1,#tab do
- local s=lpegmatch(stripper,tab[i]) or ""
- if s=="" then
- else
- l=l+1
- lst[l]=s
- end
- end
- return lst
-end
-function table.keys(t)
- if t then
- local keys={}
- local k=0
- for key in next,t do
- k=k+1
- keys[k]=key
- end
- return keys
- else
- return {}
- end
-end
-local function compare(a,b)
- local ta=type(a)
- if ta=="number" then
- local tb=type(b)
- if ta==tb then
- return a<b
- elseif tb=="string" then
- return tostring(a)<b
- end
- elseif ta=="string" then
- local tb=type(b)
- if ta==tb then
- return a<b
- else
- return a<tostring(b)
- end
- end
- return tostring(a)<tostring(b)
-end
-local function sortedkeys(tab)
- if tab then
- local srt={}
- local category=0
- local s=0
- for key in next,tab do
- s=s+1
- srt[s]=key
- if category~=3 then
- local tkey=type(key)
- if category==1 then
- if tkey~="string" then
- category=3
- end
- elseif category==2 then
- if tkey~="number" then
- category=3
- end
- else
- if tkey=="string" then
- category=1
- elseif tkey=="number" then
- category=2
- else
- category=3
- end
- end
- end
- end
- if s<2 then
- elseif category==3 then
- sort(srt,compare)
- else
- sort(srt)
- end
- return srt
- else
- return {}
- end
-end
-local function sortedhashonly(tab)
- if tab then
- local srt={}
- local s=0
- for key in next,tab do
- if type(key)=="string" then
- s=s+1
- srt[s]=key
- end
- end
- if s>1 then
- sort(srt)
- end
- return srt
- else
- return {}
- end
-end
-local function sortedindexonly(tab)
- if tab then
- local srt={}
- local s=0
- for key in next,tab do
- if type(key)=="number" then
- s=s+1
- srt[s]=key
- end
- end
- if s>1 then
- sort(srt)
- end
- return srt
- else
- return {}
- end
-end
-local function sortedhashkeys(tab,cmp)
- if tab then
- local srt={}
- local s=0
- for key in next,tab do
- if key then
- s=s+1
- srt[s]=key
- end
- end
- if s>1 then
- sort(srt,cmp)
- end
- return srt
- else
- return {}
- end
-end
-function table.allkeys(t)
- local keys={}
- for k,v in next,t do
- for k in next,v do
- keys[k]=true
- end
- end
- return sortedkeys(keys)
-end
-table.sortedkeys=sortedkeys
-table.sortedhashonly=sortedhashonly
-table.sortedindexonly=sortedindexonly
-table.sortedhashkeys=sortedhashkeys
-local function nothing() end
-local function sortedhash(t,cmp)
- if t then
- local s
- if cmp then
- s=sortedhashkeys(t,function(a,b) return cmp(t,a,b) end)
- else
- s=sortedkeys(t)
- end
- local m=#s
- if m==1 then
- return next,t
- elseif m>0 then
- local n=0
- return function()
- if n<m then
- n=n+1
- local k=s[n]
- return k,t[k]
- end
- end
- end
- end
- return nothing
-end
-table.sortedhash=sortedhash
-table.sortedpairs=sortedhash
-function table.append(t,list)
- local n=#t
- for i=1,#list do
- n=n+1
- t[n]=list[i]
- end
- return t
-end
-function table.prepend(t,list)
- local nl=#list
- local nt=nl+#t
- for i=#t,1,-1 do
- t[nt]=t[i]
- nt=nt-1
- end
- for i=1,#list do
- t[i]=list[i]
- end
- return t
-end
-function table.merge(t,...)
- if not t then
- t={}
- end
- for i=1,select("#",...) do
- for k,v in next,(select(i,...)) do
- t[k]=v
- end
- end
- return t
-end
-function table.merged(...)
- local t={}
- for i=1,select("#",...) do
- for k,v in next,(select(i,...)) do
- t[k]=v
- end
- end
- return t
-end
-function table.imerge(t,...)
- local nt=#t
- for i=1,select("#",...) do
- local nst=select(i,...)
- for j=1,#nst do
- nt=nt+1
- t[nt]=nst[j]
- end
- end
- return t
-end
-function table.imerged(...)
- local tmp={}
- local ntmp=0
- for i=1,select("#",...) do
- local nst=select(i,...)
- for j=1,#nst do
- ntmp=ntmp+1
- tmp[ntmp]=nst[j]
- end
- end
- return tmp
-end
-local function fastcopy(old,metatabletoo)
- if old then
- local new={}
- for k,v in next,old do
- if type(v)=="table" then
- new[k]=fastcopy(v,metatabletoo)
- else
- new[k]=v
- end
- end
- if metatabletoo then
- local mt=getmetatable(old)
- if mt then
- setmetatable(new,mt)
- end
- end
- return new
- else
- return {}
- end
-end
-local function copy(t,tables)
- if not tables then
- tables={}
- end
- local tcopy={}
- if not tables[t] then
- tables[t]=tcopy
- end
- for i,v in next,t do
- if type(i)=="table" then
- if tables[i] then
- i=tables[i]
- else
- i=copy(i,tables)
- end
- end
- if type(v)~="table" then
- tcopy[i]=v
- elseif tables[v] then
- tcopy[i]=tables[v]
- else
- tcopy[i]=copy(v,tables)
- end
- end
- local mt=getmetatable(t)
- if mt then
- setmetatable(tcopy,mt)
- end
- return tcopy
-end
-table.fastcopy=fastcopy
-table.copy=copy
-function table.derive(parent)
- local child={}
- if parent then
- setmetatable(child,{ __index=parent })
- end
- return child
-end
-function table.tohash(t,value)
- local h={}
- if t then
- if value==nil then value=true end
- for _,v in next,t do
- h[v]=value
- end
- end
- return h
-end
-function table.fromhash(t)
- local hsh={}
- local h=0
- for k,v in next,t do
- if v then
- h=h+1
- hsh[h]=k
- end
- end
- return hsh
-end
-local noquotes,hexify,handle,compact,inline,functions,metacheck,accurate
-local reserved=table.tohash {
- 'and','break','do','else','elseif','end','false','for','function','if',
- 'in','local','nil','not','or','repeat','return','then','true','until','while',
- 'NaN','goto','const',
-}
-local function is_simple_table(t,hexify,accurate)
- local nt=#t
- if nt>0 then
- local n=0
- for _,v in next,t do
- n=n+1
- if type(v)=="table" then
- return nil
- end
- end
- local haszero=rawget(t,0)
- if n==nt then
- local tt={}
- for i=1,nt do
- local v=t[i]
- local tv=type(v)
- if tv=="number" then
- if hexify then
- tt[i]=format("0x%X",v)
- elseif accurate then
- tt[i]=format("%q",v)
- else
- tt[i]=v
- end
- elseif tv=="string" then
- tt[i]=format("%q",v)
- elseif tv=="boolean" then
- tt[i]=v and "true" or "false"
- else
- return nil
- end
- end
- return tt
- elseif haszero and (n==nt+1) then
- local tt={}
- for i=0,nt do
- local v=t[i]
- local tv=type(v)
- if tv=="number" then
- if hexify then
- tt[i+1]=format("0x%X",v)
- elseif accurate then
- tt[i+1]=format("%q",v)
- else
- tt[i+1]=v
- end
- elseif tv=="string" then
- tt[i+1]=format("%q",v)
- elseif tv=="boolean" then
- tt[i+1]=v and "true" or "false"
- else
- return nil
- end
- end
- tt[1]="[0] = "..tt[1]
- return tt
- end
- end
- return nil
-end
-table.is_simple_table=is_simple_table
-local propername=patterns.propername
-local function dummy() end
-local function do_serialize(root,name,depth,level,indexed)
- if level>0 then
- depth=depth.." "
- if indexed then
- handle(format("%s{",depth))
- else
- local tn=type(name)
- if tn=="number" then
- if hexify then
- handle(format("%s[0x%X]={",depth,name))
- else
- handle(format("%s[%s]={",depth,name))
- end
- elseif tn=="string" then
- if noquotes and not reserved[name] and lpegmatch(propername,name) then
- handle(format("%s%s={",depth,name))
- else
- handle(format("%s[%q]={",depth,name))
- end
- elseif tn=="boolean" then
- handle(format("%s[%s]={",depth,name and "true" or "false"))
- else
- handle(format("%s{",depth))
- end
- end
- end
- if root and next(root)~=nil then
- local first=nil
- local last=0
- if compact then
- last=#root
- for k=1,last do
- if rawget(root,k)==nil then
- last=k-1
- break
- end
- end
- if last>0 then
- first=1
- end
- end
- local sk=sortedkeys(root)
- for i=1,#sk do
- local k=sk[i]
- local v=root[k]
- local tv=type(v)
- local tk=type(k)
- if compact and first and tk=="number" and k>=first and k<=last then
- if tv=="number" then
- if hexify then
- handle(format("%s 0x%X,",depth,v))
- elseif accurate then
- handle(format("%s %q,",depth,v))
- else
- handle(format("%s %s,",depth,v))
- end
- elseif tv=="string" then
- handle(format("%s %q,",depth,v))
- elseif tv=="table" then
- if next(v)==nil then
- handle(format("%s {},",depth))
- elseif inline then
- local st=is_simple_table(v,hexify,accurate)
- if st then
- handle(format("%s { %s },",depth,concat(st,", ")))
- else
- do_serialize(v,k,depth,level+1,true)
- end
- else
- do_serialize(v,k,depth,level+1,true)
- end
- elseif tv=="boolean" then
- handle(format("%s %s,",depth,v and "true" or "false"))
- elseif tv=="function" then
- if functions then
- handle(format('%s load(%q),',depth,dump(v)))
- else
- handle(format('%s "function",',depth))
- end
- else
- handle(format("%s %q,",depth,tostring(v)))
- end
- elseif k=="__p__" then
- if false then
- handle(format("%s __p__=nil,",depth))
- end
- elseif tv=="number" then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=0x%X,",depth,k,v))
- elseif accurate then
- handle(format("%s [%s]=%q,",depth,k,v))
- else
- handle(format("%s [%s]=%s,",depth,k,v))
- end
- elseif tk=="boolean" then
- if hexify then
- handle(format("%s [%s]=0x%X,",depth,k and "true" or "false",v))
- elseif accurate then
- handle(format("%s [%s]=%q,",depth,k and "true" or "false",v))
- else
- handle(format("%s [%s]=%s,",depth,k and "true" or "false",v))
- end
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- if hexify then
- handle(format("%s %s=0x%X,",depth,k,v))
- elseif accurate then
- handle(format("%s %s=%q,",depth,k,v))
- else
- handle(format("%s %s=%s,",depth,k,v))
- end
- else
- if hexify then
- handle(format("%s [%q]=0x%X,",depth,k,v))
- elseif accurate then
- handle(format("%s [%q]=%q,",depth,k,v))
- else
- handle(format("%s [%q]=%s,",depth,k,v))
- end
- end
- elseif tv=="string" then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=%q,",depth,k,v))
- elseif accurate then
- handle(format("%s [%q]=%q,",depth,k,v))
- else
- handle(format("%s [%s]=%q,",depth,k,v))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=%q,",depth,k and "true" or "false",v))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=%q,",depth,k,v))
- else
- handle(format("%s [%q]=%q,",depth,k,v))
- end
- elseif tv=="table" then
- if next(v)==nil then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]={},",depth,k))
- elseif accurate then
- handle(format("%s [%q]={},",depth,k))
- else
- handle(format("%s [%s]={},",depth,k))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]={},",depth,k and "true" or "false"))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s={},",depth,k))
- else
- handle(format("%s [%q]={},",depth,k))
- end
- elseif inline then
- local st=is_simple_table(v,hexify,accurate)
- if st then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]={ %s },",depth,k,concat(st,", ")))
- elseif accurate then
- handle(format("%s [%q]={ %s },",depth,k,concat(st,", ")))
- else
- handle(format("%s [%s]={ %s },",depth,k,concat(st,", ")))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]={ %s },",depth,k and "true" or "false",concat(st,", ")))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s={ %s },",depth,k,concat(st,", ")))
- else
- handle(format("%s [%q]={ %s },",depth,k,concat(st,", ")))
- end
- else
- do_serialize(v,k,depth,level+1)
- end
- else
- do_serialize(v,k,depth,level+1)
- end
- elseif tv=="boolean" then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=%s,",depth,k,v and "true" or "false"))
- elseif accurate then
- handle(format("%s [%q]=%s,",depth,k,v and "true" or "false"))
- else
- handle(format("%s [%s]=%s,",depth,k,v and "true" or "false"))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=%s,",depth,tostring(k),v and "true" or "false"))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=%s,",depth,k,v and "true" or "false"))
- else
- handle(format("%s [%q]=%s,",depth,k,v and "true" or "false"))
- end
- elseif tv=="function" then
- if functions then
- local getinfo=debug and debug.getinfo
- if getinfo then
- local f=getinfo(v).what=="C" and dump(dummy) or dump(v)
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=load(%q),",depth,k,f))
- elseif accurate then
- handle(format("%s [%q]=load(%q),",depth,k,f))
- else
- handle(format("%s [%s]=load(%q),",depth,k,f))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=load(%q),",depth,k and "true" or "false",f))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=load(%q),",depth,k,f))
- else
- handle(format("%s [%q]=load(%q),",depth,k,f))
- end
- end
- end
- else
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=%q,",depth,k,tostring(v)))
- elseif accurate then
- handle(format("%s [%q]=%q,",depth,k,tostring(v)))
- else
- handle(format("%s [%s]=%q,",depth,k,tostring(v)))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=%q,",depth,k and "true" or "false",tostring(v)))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=%q,",depth,k,tostring(v)))
- else
- handle(format("%s [%q]=%q,",depth,k,tostring(v)))
- end
- end
- end
- end
- if level>0 then
- handle(format("%s},",depth))
- end
-end
-local function serialize(_handle,root,name,specification)
- local tname=type(name)
- if type(specification)=="table" then
- noquotes=specification.noquotes
- hexify=specification.hexify
- accurate=specification.accurate
- handle=_handle or specification.handle or print
- functions=specification.functions
- compact=specification.compact
- inline=specification.inline and compact
- metacheck=specification.metacheck
- if functions==nil then
- functions=true
- end
- if compact==nil then
- compact=true
- end
- if inline==nil then
- inline=compact
- end
- if metacheck==nil then
- metacheck=true
- end
- else
- noquotes=false
- hexify=false
- handle=_handle or print
- compact=true
- inline=true
- functions=true
- metacheck=true
- end
- if tname=="string" then
- if name=="return" then
- handle("return {")
- else
- handle(name.."={")
- end
- elseif tname=="number" then
- if hexify then
- handle(format("[0x%X]={",name))
- else
- handle("["..name.."]={")
- end
- elseif tname=="boolean" then
- if name then
- handle("return {")
- else
- handle("{")
- end
- else
- handle("t={")
- end
- if root then
- if metacheck and getmetatable(root) then
- local dummy=root._w_h_a_t_e_v_e_r_
- root._w_h_a_t_e_v_e_r_=nil
- end
- if next(root)~=nil then
- do_serialize(root,name,"",0)
- end
- end
- handle("}")
-end
-function table.serialize(root,name,specification)
- local t={}
- local n=0
- local function flush(s)
- n=n+1
- t[n]=s
- end
- serialize(flush,root,name,specification)
- return concat(t,"\n")
-end
-table.tohandle=serialize
-local maxtab=2*1024
-function table.tofile(filename,root,name,specification)
- local f=io.open(filename,'w')
- if f then
- if maxtab>1 then
- local t={}
- local n=0
- local function flush(s)
- n=n+1
- t[n]=s
- if n>maxtab then
- f:write(concat(t,"\n"),"\n")
- t={}
- n=0
- end
- end
- serialize(flush,root,name,specification)
- f:write(concat(t,"\n"),"\n")
- else
- local function flush(s)
- f:write(s,"\n")
- end
- serialize(flush,root,name,specification)
- end
- f:close()
- io.flush()
- end
-end
-local function flattened(t,f,depth)
- if f==nil then
- f={}
- depth=0xFFFF
- elseif tonumber(f) then
- depth=f
- f={}
- elseif not depth then
- depth=0xFFFF
- end
- for k,v in next,t do
- if type(k)~="number" then
- if depth>0 and type(v)=="table" then
- flattened(v,f,depth-1)
- else
- f[#f+1]=v
- end
- end
- end
- for k=1,#t do
- local v=t[k]
- if depth>0 and type(v)=="table" then
- flattened(v,f,depth-1)
- else
- f[#f+1]=v
- end
- end
- return f
-end
-table.flattened=flattened
-local function collapsed(t,f,h)
- if f==nil then
- f={}
- h={}
- end
- for k=1,#t do
- local v=t[k]
- if type(v)=="table" then
- collapsed(v,f,h)
- elseif not h[v] then
- f[#f+1]=v
- h[v]=true
- end
- end
- return f
-end
-local function collapsedhash(t,h)
- if h==nil then
- h={}
- end
- for k=1,#t do
- local v=t[k]
- if type(v)=="table" then
- collapsedhash(v,h)
- else
- h[v]=true
- end
- end
- return h
-end
-table.collapsed=collapsed
-table.collapsedhash=collapsedhash
-local function unnest(t,f)
- if not f then
- f={}
- end
- for i=1,#t do
- local v=t[i]
- if type(v)=="table" then
- if type(v[1])=="table" then
- unnest(v,f)
- else
- f[#f+1]=v
- end
- else
- f[#f+1]=v
- end
- end
- return f
-end
-function table.unnest(t)
- return unnest(t)
-end
-local function are_equal(a,b,n,m)
- if a==b then
- return true
- elseif a and b and #a==#b then
- if not n then
- n=1
- end
- if not m then
- m=#a
- end
- for i=n,m do
- local ai,bi=a[i],b[i]
- if ai==bi then
- elseif type(ai)=="table" and type(bi)=="table" then
- if not are_equal(ai,bi) then
- return false
- end
- else
- return false
- end
- end
- return true
- else
- return false
- end
-end
-local function identical(a,b)
- if a~=b then
- for ka,va in next,a do
- local vb=b[ka]
- if va==vb then
- elseif type(va)=="table" and type(vb)=="table" then
- if not identical(va,vb) then
- return false
- end
- else
- return false
- end
- end
- end
- return true
-end
-table.identical=identical
-table.are_equal=are_equal
-local function sparse(old,nest,keeptables)
- local new={}
- for k,v in next,old do
- if not (v=="" or v==false) then
- if nest and type(v)=="table" then
- v=sparse(v,nest)
- if keeptables or next(v)~=nil then
- new[k]=v
- end
- else
- new[k]=v
- end
- end
- end
- return new
-end
-table.sparse=sparse
-function table.compact(t)
- return sparse(t,true,true)
-end
-function table.contains(t,v)
- if t then
- for i=1,#t do
- if t[i]==v then
- return i
- end
- end
- end
- return false
-end
-function table.count(t)
- local n=0
- for k,v in next,t do
- n=n+1
- end
- return n
-end
-function table.swapped(t,s)
- local n={}
- if s then
- for k,v in next,s do
- n[k]=v
- end
- end
- for k,v in next,t do
- n[v]=k
- end
- return n
-end
-function table.hashed(t)
- for i=1,#t do
- t[t[i]]=i
- end
- return t
-end
-function table.mirrored(t)
- local n={}
- for k,v in next,t do
- n[v]=k
- n[k]=v
- end
- return n
-end
-function table.reversed(t)
- if t then
- local tt={}
- local tn=#t
- if tn>0 then
- local ttn=0
- for i=tn,1,-1 do
- ttn=ttn+1
- tt[ttn]=t[i]
- end
- end
- return tt
- end
-end
-function table.reverse(t)
- if t then
- local n=#t
- local m=n+1
- for i=1,floor(n/2) do
- local j=m-i
- t[i],t[j]=t[j],t[i]
- end
- return t
- end
-end
-local function sequenced(t,sep,simple)
- if not t then
- return ""
- elseif type(t)~="table" then
- return t
- end
- local n=#t
- local s={}
- if n>0 then
- for i=1,n do
- local v=t[i]
- if type(v)=="table" then
- s[i]="{"..sequenced(v,sep,simple).."}"
- else
- s[i]=tostring(t[i])
- end
- end
- else
- n=0
- for k,v in sortedhash(t) do
- if simple then
- if v==true then
- n=n+1
- s[n]=k
- elseif v and v~="" then
- n=n+1
- if type(v)=="table" then
- s[n]=k.."={"..sequenced(v,sep,simple).."}"
- else
- s[n]=k.."="..tostring(v)
- end
- end
- else
- n=n+1
- if type(v)=="table" then
- s[n]=k.."={"..sequenced(v,sep,simple).."}"
- else
- s[n]=k.."="..tostring(v)
- end
- end
- end
- end
- if sep==true then
- return "{ "..concat(s,", ").." }"
- else
- return concat(s,sep or " | ")
- end
-end
-table.sequenced=sequenced
-function table.print(t,...)
- if type(t)~="table" then
- print(tostring(t))
- else
- serialize(print,t,...)
- end
-end
-if setinspector then
- setinspector("table",function(v) if type(v)=="table" then serialize(print,v,"table") return true end end)
-end
-function table.sub(t,i,j)
- return { unpack(t,i,j) }
-end
-function table.is_empty(t)
- return not t or next(t)==nil
-end
-function table.has_one_entry(t)
- return t and next(t,next(t))==nil
-end
-function table.loweredkeys(t)
- local l={}
- for k,v in next,t do
- l[lower(k)]=v
- end
- return l
-end
-function table.unique(old)
- local hash={}
- local new={}
- local n=0
- for i=1,#old do
- local oi=old[i]
- if not hash[oi] then
- n=n+1
- new[n]=oi
- hash[oi]=true
- end
- end
- return new
-end
-function table.sorted(t,...)
- sort(t,...)
- return t
-end
-function table.values(t,s)
- if t then
- local values={}
- local keys={}
- local v=0
- for key,value in next,t do
- if not keys[value] then
- v=v+1
- values[v]=value
- keys[k]=key
- end
- end
- if s then
- sort(values)
- end
- return values
- else
- return {}
- end
-end
-function table.filtered(t,pattern,sort,cmp)
- if t and type(pattern)=="string" then
- if sort then
- local s
- if cmp then
- s=sortedhashkeys(t,function(a,b) return cmp(t,a,b) end)
- else
- s=sortedkeys(t)
- end
- local n=0
- local m=#s
- local function kv(s)
- while n<m do
- n=n+1
- local k=s[n]
- if find(k,pattern) then
- return k,t[k]
- end
- end
- end
- return kv,s
- else
- local n=next(t)
- local function iterator()
- while n~=nil do
- local k=n
- n=next(t,k)
- if find(k,pattern) then
- return k,t[k]
- end
- end
- end
- return iterator,t
- end
- else
- return nothing
- end
-end
-if not table.move then
- function table.move(a1,f,e,t,a2)
- if a2 and a1~=a2 then
- for i=f,e do
- a2[t]=a1[i]
- t=t+1
- end
- return a2
- else
- t=t+e-f
- for i=e,f,-1 do
- a1[t]=a1[i]
- t=t-1
- end
- return a1
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-io"] = package.loaded["l-io"] or true
-
--- original size: 11829, stripped down to: 6331
-
-if not modules then modules={} end modules ['l-io']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local io=io
-local open,flush,write,read=io.open,io.flush,io.write,io.read
-local byte,find,gsub,format=string.byte,string.find,string.gsub,string.format
-local concat=table.concat
-local type=type
-if string.find(os.getenv("PATH") or "",";",1,true) then
- io.fileseparator,io.pathseparator="\\",";"
-else
- io.fileseparator,io.pathseparator="/",":"
-end
-local large=0x01000000
-local medium=0x00100000
-local small=0x00020000
-local function readall(f)
- local size=f:seek("end")
- if size>0 then
- f:seek("set",0)
- return f:read(size)
- else
- return ""
- end
-end
-io.readall=readall
-function io.loaddata(filename,textmode)
- local f=open(filename,(textmode and 'r') or 'rb')
- if f then
- local size=f:seek("end")
- local data=nil
- if size>0 then
- f:seek("set",0)
- data=f:read(size)
- end
- f:close()
- return data
- end
-end
-function io.copydata(source,target,action)
- local f=open(source,"rb")
- if f then
- local g=open(target,"wb")
- if g then
- local size=f:seek("end")
- if size>0 then
- f:seek("set",0)
- local data=f:read(size)
- if action then
- data=action(data)
- end
- if data then
- g:write(data)
- end
- end
- g:close()
- end
- f:close()
- flush()
- end
-end
-function io.savedata(filename,data,joiner)
- local f=open(filename,"wb")
- if f then
- if type(data)=="table" then
- f:write(concat(data,joiner or ""))
- elseif type(data)=="function" then
- data(f)
- else
- f:write(data or "")
- end
- f:close()
- flush()
- return true
- else
- return false
- end
-end
-if fio and fio.readline then
- local readline=fio.readline
- function io.loadlines(filename,n)
- local f=open(filename,'r')
- if not f then
- elseif n then
- local lines={}
- for i=1,n do
- local line=readline(f)
- if line then
- lines[i]=line
- else
- break
- end
- end
- f:close()
- lines=concat(lines,"\n")
- if #lines>0 then
- return lines
- end
- else
- local line=readline(f)
- f:close()
- if line and #line>0 then
- return line
- end
- end
- end
-else
- function io.loadlines(filename,n)
- local f=open(filename,'r')
- if not f then
- elseif n then
- local lines={}
- for i=1,n do
- local line=f:read("*lines")
- if line then
- lines[i]=line
- else
- break
- end
- end
- f:close()
- lines=concat(lines,"\n")
- if #lines>0 then
- return lines
- end
- else
- local line=f:read("*line") or ""
- f:close()
- if #line>0 then
- return line
- end
- end
- end
-end
-function io.loadchunk(filename,n)
- local f=open(filename,'rb')
- if f then
- local data=f:read(n or 1024)
- f:close()
- if #data>0 then
- return data
- end
- end
-end
-function io.exists(filename)
- local f=open(filename)
- if f==nil then
- return false
- else
- f:close()
- return true
- end
-end
-function io.size(filename)
- local f=open(filename)
- if f==nil then
- return 0
- else
- local s=f:seek("end")
- f:close()
- return s
- end
-end
-local function noflines(f)
- if type(f)=="string" then
- local f=open(filename)
- if f then
- local n=f and noflines(f) or 0
- f:close()
- return n
- else
- return 0
- end
- else
- local n=0
- for _ in f:lines() do
- n=n+1
- end
- f:seek('set',0)
- return n
- end
-end
-io.noflines=noflines
-local nextchar={
- [ 4]=function(f)
- return f:read(1,1,1,1)
- end,
- [ 2]=function(f)
- return f:read(1,1)
- end,
- [ 1]=function(f)
- return f:read(1)
- end,
- [-2]=function(f)
- local a,b=f:read(1,1)
- return b,a
- end,
- [-4]=function(f)
- local a,b,c,d=f:read(1,1,1,1)
- return d,c,b,a
- end
-}
-function io.characters(f,n)
- if f then
- return nextchar[n or 1],f
- end
-end
-local nextbyte={
- [4]=function(f)
- local a,b,c,d=f:read(1,1,1,1)
- if d then
- return byte(a),byte(b),byte(c),byte(d)
- end
- end,
- [3]=function(f)
- local a,b,c=f:read(1,1,1)
- if b then
- return byte(a),byte(b),byte(c)
- end
- end,
- [2]=function(f)
- local a,b=f:read(1,1)
- if b then
- return byte(a),byte(b)
- end
- end,
- [1]=function (f)
- local a=f:read(1)
- if a then
- return byte(a)
- end
- end,
- [-2]=function (f)
- local a,b=f:read(1,1)
- if b then
- return byte(b),byte(a)
- end
- end,
- [-3]=function(f)
- local a,b,c=f:read(1,1,1)
- if b then
- return byte(c),byte(b),byte(a)
- end
- end,
- [-4]=function(f)
- local a,b,c,d=f:read(1,1,1,1)
- if d then
- return byte(d),byte(c),byte(b),byte(a)
- end
- end
-}
-function io.bytes(f,n)
- if f then
- return nextbyte[n or 1],f
- else
- return nil,nil
- end
-end
-function io.ask(question,default,options)
- while true do
- write(question)
- if options then
- write(format(" [%s]",concat(options,"|")))
- end
- if default then
- write(format(" [%s]",default))
- end
- write(format(" "))
- flush()
- local answer=read()
- answer=gsub(answer,"^%s*(.*)%s*$","%1")
- if answer=="" and default then
- return default
- elseif not options then
- return answer
- else
- for k=1,#options do
- if options[k]==answer then
- return answer
- end
- end
- local pattern="^"..answer
- for k=1,#options do
- local v=options[k]
- if find(v,pattern) then
- return v
- end
- end
- end
- end
-end
-local function readnumber(f,n,m)
- if m then
- f:seek("set",n)
- n=m
- end
- if n==1 then
- return byte(f:read(1))
- elseif n==2 then
- local a,b=byte(f:read(2),1,2)
- return 0x100*a+b
- elseif n==3 then
- local a,b,c=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
- elseif n==4 then
- local a,b,c,d=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
- elseif n==8 then
- local a,b=readnumber(f,4),readnumber(f,4)
- return 0x100*a+b
- elseif n==12 then
- local a,b,c=readnumber(f,4),readnumber(f,4),readnumber(f,4)
- return 0x10000*a+0x100*b+c
- elseif n==-2 then
- local b,a=byte(f:read(2),1,2)
- return 0x100*a+b
- elseif n==-3 then
- local c,b,a=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
- elseif n==-4 then
- local d,c,b,a=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
- elseif n==-8 then
- local h,g,f,e,d,c,b,a=byte(f:read(8),1,8)
- return 0x100000000000000*a+0x1000000000000*b+0x10000000000*c+0x100000000*d+0x1000000*e+0x10000*f+0x100*g+h
- else
- return 0
- end
-end
-io.readnumber=readnumber
-function io.readstring(f,n,m)
- if m then
- f:seek("set",n)
- n=m
- end
- local str=gsub(f:read(n),"\000","")
- return str
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-number"] = package.loaded["l-number"] or true
-
--- original size: 5720, stripped down to: 2176
-
-if not modules then modules={} end modules ['l-number']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local tostring,tonumber=tostring,tonumber
-local format,floor,match,rep=string.format,math.floor,string.match,string.rep
-local concat,insert=table.concat,table.insert
-local lpegmatch=lpeg.match
-local floor=math.floor
-number=number or {}
-local number=number
-if bit32 then
- local bextract=bit32.extract
- local t={
- "0","0","0","0","0","0","0","0",
- "0","0","0","0","0","0","0","0",
- "0","0","0","0","0","0","0","0",
- "0","0","0","0","0","0","0","0",
- }
- function number.tobitstring(b,m,w)
- if not w then
- w=32
- end
- local n=w
- for i=0,w-1 do
- local v=bextract(b,i)
- local k=w-i
- if v==1 then
- n=k
- t[k]="1"
- else
- t[k]="0"
- end
- end
- if w then
- return concat(t,"",1,w)
- elseif m then
- m=33-m*8
- if m<1 then
- m=1
- end
- return concat(t,"",1,m)
- elseif n<8 then
- return concat(t)
- elseif n<16 then
- return concat(t,"",9)
- elseif n<24 then
- return concat(t,"",17)
- else
- return concat(t,"",25)
- end
- end
-else
- function number.tobitstring(n,m)
- if n>0 then
- local t={}
- while n>0 do
- insert(t,1,n%2>0 and 1 or 0)
- n=floor(n/2)
- end
- local nn=8-#t%8
- if nn>0 and nn<8 then
- for i=1,nn do
- insert(t,1,0)
- end
- end
- if m then
- m=m*8-#t
- if m>0 then
- insert(t,1,rep("0",m))
- end
- end
- return concat(t)
- elseif m then
- rep("00000000",m)
- else
- return "00000000"
- end
- end
-end
-function number.valid(str,default)
- return tonumber(str) or default or nil
-end
-function number.toevenhex(n)
- local s=format("%X",n)
- if #s%2==0 then
- return s
- else
- return "0"..s
- end
-end
-function number.bytetodecimal(b)
- local d=floor(b*100/255+0.5)
- if d>100 then
- return 100
- elseif d<-100 then
- return -100
- else
- return d
- end
-end
-function number.decimaltobyte(d)
- local b=floor(d*255/100+0.5)
- if b>255 then
- return 255
- elseif b<-255 then
- return -255
- else
- return b
- end
-end
-function number.idiv(i,d)
- return floor(i/d)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-set"] = package.loaded["l-set"] or true
-
--- original size: 1923, stripped down to: 1044
-
-if not modules then modules={} end modules ['l-set']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-set=set or {}
-local nums={}
-local tabs={}
-local concat=table.concat
-local next,type=next,type
-set.create=table.tohash
-function set.tonumber(t)
- if next(t) then
- local s=""
- for k,v in next,t do
- if v then
- s=s.." "..k
- end
- end
- local n=nums[s]
- if not n then
- n=#tabs+1
- tabs[n]=t
- nums[s]=n
- end
- return n
- else
- return 0
- end
-end
-function set.totable(n)
- if n==0 then
- return {}
- else
- return tabs[n] or {}
- end
-end
-function set.tolist(n)
- if n==0 or not tabs[n] then
- return ""
- else
- local t,n={},0
- for k,v in next,tabs[n] do
- if v then
- n=n+1
- t[n]=k
- end
- end
- return concat(t," ")
- end
-end
-function set.contains(n,s)
- if type(n)=="table" then
- return n[s]
- elseif n==0 then
- return false
- else
- local t=tabs[n]
- return t and t[s]
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-os"] = package.loaded["l-os"] or true
-
--- original size: 19409, stripped down to: 10419
-
-if not modules then modules={} end modules ['l-os']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local os=os
-local date,time=os.date,os.time
-local find,format,gsub,upper,gmatch=string.find,string.format,string.gsub,string.upper,string.gmatch
-local concat=table.concat
-local random,ceil,randomseed=math.random,math.ceil,math.randomseed
-local type,setmetatable,tonumber,tostring=type,setmetatable,tonumber,tostring
-do
- local selfdir=os.selfdir
- if selfdir=="" then
- selfdir=nil
- end
- if not selfdir then
- if arg then
- for i=1,#arg do
- local a=arg[i]
- if find(a,"^%-%-[c:]*texmfbinpath=") then
- selfdir=gsub(a,"^.-=","")
- break
- end
- end
- end
- if not selfdir then
- selfdir=os.selfbin or "luatex"
- if find(selfdir,"[/\\]") then
- selfdir=gsub(selfdir,"[/\\][^/\\]*$","")
- elseif os.getenv then
- local path=os.getenv("PATH")
- local name=gsub(selfdir,"^.*[/\\][^/\\]","")
- local patt="[^:]+"
- if os.type=="windows" then
- patt="[^;]+"
- name=name..".exe"
- end
- local isfile
- if lfs then
- local attributes=lfs.attributes
- isfile=function(name)
- local a=attributes(name,"mode")
- return a=="file" or a=="link" or nil
- end
- else
- local open=io.open
- isfile=function(name)
- local f=open(name)
- if f then
- f:close()
- return true
- end
- end
- end
- for p in gmatch(path,patt) do
- if isfile(p.."/"..name) then
- selfdir=p
- break
- end
- end
- end
- end
- os.selfdir=selfdir or "."
- end
-end
-math.initialseed=tonumber(string.sub(string.reverse(tostring(ceil(socket and socket.gettime()*10000 or time()))),1,6))
-randomseed(math.initialseed)
-if not os.__getenv__ then
- os.__getenv__=os.getenv
- os.__setenv__=os.setenv
- if os.env then
- local osgetenv=os.getenv
- local ossetenv=os.setenv
- local osenv=os.env local _=osenv.PATH
- function os.setenv(k,v)
- if v==nil then
- v=""
- end
- local K=upper(k)
- osenv[K]=v
- if type(v)=="table" then
- v=concat(v,";")
- end
- ossetenv(K,v)
- end
- function os.getenv(k)
- local K=upper(k)
- local v=osenv[K] or osenv[k] or osgetenv(K) or osgetenv(k)
- if v=="" then
- return nil
- else
- return v
- end
- end
- else
- local ossetenv=os.setenv
- local osgetenv=os.getenv
- local osenv={}
- function os.setenv(k,v)
- if v==nil then
- v=""
- end
- local K=upper(k)
- osenv[K]=v
- end
- function os.getenv(k)
- local K=upper(k)
- local v=osenv[K] or osgetenv(K) or osgetenv(k)
- if v=="" then
- return nil
- else
- return v
- end
- end
- local function __index(t,k)
- return os.getenv(k)
- end
- local function __newindex(t,k,v)
- os.setenv(k,v)
- end
- os.env={}
- setmetatable(os.env,{ __index=__index,__newindex=__newindex } )
- end
-end
-local execute=os.execute
-local iopopen=io.popen
-local function resultof(command)
- local handle=iopopen(command,"r")
- if handle then
- local result=handle:read("*all") or ""
- handle:close()
- return result
- else
- return ""
- end
-end
-os.resultof=resultof
-function os.pipeto(command)
- return iopopen(command,"w")
-end
-if not io.fileseparator then
- if find(os.getenv("PATH"),";",1,true) then
- io.fileseparator,io.pathseparator,os.type="\\",";",os.type or "windows"
- else
- io.fileseparator,io.pathseparator,os.type="/",":",os.type or "unix"
- end
-end
-os.type=os.type or (io.pathseparator==";" and "windows") or "unix"
-os.name=os.name or (os.type=="windows" and "mswin" ) or "linux"
-if os.type=="windows" then
- os.libsuffix,os.binsuffix,os.binsuffixes='dll','exe',{ 'exe','cmd','bat' }
-else
- os.libsuffix,os.binsuffix,os.binsuffixes='so','',{ '' }
-end
-local launchers={
- windows="start %s",
- macosx="open %s",
- unix="xdg-open %s &> /dev/null &",
-}
-function os.launch(str)
- local command=format(launchers[os.name] or launchers.unix,str)
- execute(command)
-end
-local gettimeofday=os.gettimeofday or os.clock
-os.gettimeofday=gettimeofday
-local startuptime=gettimeofday()
-function os.runtime()
- return gettimeofday()-startuptime
-end
-local resolvers=os.resolvers or {}
-os.resolvers=resolvers
-setmetatable(os,{ __index=function(t,k)
- local r=resolvers[k]
- return r and r(t,k) or nil
-end })
-local name,platform=os.name or "linux",os.getenv("MTX_PLATFORM") or ""
-if platform~="" then
- os.platform=platform
-elseif os.type=="windows" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("PROCESSOR_ARCHITECTURE") or ""
- local platform=""
- if find(architecture,"AMD64",1,true) then
- platform="win64"
- else
- platform="mswin"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="linux" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("HOSTTYPE") or resultof("uname -m") or ""
- local platform=os.getenv("MTX_PLATFORM") or ""
- local musl=find(os.selfdir or "","linuxmusl")
- if platform~="" then
- elseif find(architecture,"x86_64",1,true) then
- platform=musl and "linuxmusl" or "linux-64"
- elseif find(architecture,"ppc",1,true) then
- platform="linux-ppc"
- else
- platform=musl and "linuxmusl" or "linux"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="macosx" then
- function resolvers.platform(t,k)
- local architecture=resultof("echo $HOSTTYPE") or ""
- local platform=""
- if architecture=="" then
- platform="osx-intel"
- elseif find(architecture,"i386",1,true) then
- platform="osx-intel"
- elseif find(architecture,"x86_64",1,true) then
- platform="osx-64"
- elseif find(architecture,"arm64",1,true) then
- platform="osx-64"
- else
- platform="osx-ppc"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="sunos" then
- function resolvers.platform(t,k)
- local architecture=resultof("uname -m") or ""
- local platform=""
- if find(architecture,"sparc",1,true) then
- platform="solaris-sparc"
- else
- platform="solaris-intel"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="freebsd" then
- function resolvers.platform(t,k)
- local architecture=resultof("uname -m") or ""
- local platform=""
- if find(architecture,"amd64",1,true) then
- platform="freebsd-amd64"
- else
- platform="freebsd"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="kfreebsd" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("HOSTTYPE") or resultof("uname -m") or ""
- local platform=""
- if find(architecture,"x86_64",1,true) then
- platform="kfreebsd-amd64"
- else
- platform="kfreebsd-i386"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-else
- function resolvers.platform(t,k)
- local platform="linux"
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-end
-os.newline=name=="windows" and "\013\010" or "\010"
-function resolvers.bits(t,k)
- local bits=find(os.platform,"64",1,true) and 64 or 32
- os.bits=bits
- return bits
-end
-local t={ 8,9,"a","b" }
-function os.uuid()
- return format("%04x%04x-4%03x-%s%03x-%04x-%04x%04x%04x",
- random(0xFFFF),random(0xFFFF),
- random(0x0FFF),
- t[ceil(random(4))] or 8,random(0x0FFF),
- random(0xFFFF),
- random(0xFFFF),random(0xFFFF),random(0xFFFF)
- )
-end
-local d
-function os.timezone(delta)
- d=d or ((tonumber(date("%H")) or 0)-(tonumber(date("!%H")) or 0))
- if delta then
- if d>0 then
- return format("+%02i:00",d)
- else
- return format("-%02i:00",-d)
- end
- else
- return 1
- end
-end
-local timeformat=format("%%s%s",os.timezone(true))
-local dateformat="!%Y-%m-%d %H:%M:%S"
-local lasttime=nil
-local lastdate=nil
-function os.fulltime(t,default)
- t=t and tonumber(t) or 0
- if t>0 then
- elseif default then
- return default
- else
- t=time()
- end
- if t~=lasttime then
- lasttime=t
- lastdate=format(timeformat,date(dateformat))
- end
- return lastdate
-end
-local dateformat="%Y-%m-%d %H:%M:%S"
-local lasttime=nil
-local lastdate=nil
-function os.localtime(t,default)
- t=t and tonumber(t) or 0
- if t>0 then
- elseif default then
- return default
- else
- t=time()
- end
- if t~=lasttime then
- lasttime=t
- lastdate=date(dateformat,t)
- end
- return lastdate
-end
-function os.converttime(t,default)
- local t=tonumber(t)
- if t and t>0 then
- return date(dateformat,t)
- else
- return default or "-"
- end
-end
-local memory={}
-local function which(filename)
- local fullname=memory[filename]
- if fullname==nil then
- local suffix=file.suffix(filename)
- local suffixes=suffix=="" and os.binsuffixes or { suffix }
- for directory in gmatch(os.getenv("PATH"),"[^"..io.pathseparator.."]+") do
- local df=file.join(directory,filename)
- for i=1,#suffixes do
- local dfs=file.addsuffix(df,suffixes[i])
- if io.exists(dfs) then
- fullname=dfs
- break
- end
- end
- end
- if not fullname then
- fullname=false
- end
- memory[filename]=fullname
- end
- return fullname
-end
-os.which=which
-os.where=which
-function os.today()
- return date("!*t")
-end
-function os.now()
- return date("!%Y-%m-%d %H:%M:%S")
-end
-if not os.sleep then
- local socket=socket
- function os.sleep(n)
- if not socket then
- socket=require("socket")
- end
- socket.sleep(n)
- end
-end
-local function isleapyear(year)
- return (year%4==0) and (year%100~=0 or year%400==0)
-end
-os.isleapyear=isleapyear
-local days={ 31,28,31,30,31,30,31,31,30,31,30,31 }
-local function nofdays(year,month,day)
- if not month then
- return isleapyear(year) and 365 or 364
- elseif not day then
- return month==2 and isleapyear(year) and 29 or days[month]
- else
- for i=1,month-1 do
- day=day+days[i]
- end
- if month>2 and isleapyear(year) then
- day=day+1
- end
- return day
- end
-end
-os.nofdays=nofdays
-function os.weekday(day,month,year)
- return date("%w",time { year=year,month=month,day=day })+1
-end
-function os.validdate(year,month,day)
- if month<1 then
- month=1
- elseif month>12 then
- month=12
- end
- if day<1 then
- day=1
- else
- local max=nofdays(year,month)
- if day>max then
- day=max
- end
- end
- return year,month,day
-end
-function os.date(fmt,...)
- if not fmt then
- fmt="%Y-%m-%d %H:%M"
- end
- return date(fmt,...)
-end
-local osexit=os.exit
-local exitcode=nil
-function os.setexitcode(code)
- exitcode=code
-end
-function os.exit(c)
- if exitcode~=nil then
- return osexit(exitcode)
- end
- if c~=nil then
- return osexit(c)
- end
- return osexit()
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-file"] = package.loaded["l-file"] or true
-
--- original size: 22175, stripped down to: 10302
-
-if not modules then modules={} end modules ['l-file']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-file=file or {}
-local file=file
-if not lfs then
- lfs=optionalrequire("lfs")
-end
-local insert,concat=table.insert,table.concat
-local match,find,gmatch=string.match,string.find,string.gmatch
-local lpegmatch=lpeg.match
-local getcurrentdir,attributes=lfs.currentdir,lfs.attributes
-local checkedsplit=string.checkedsplit
-local P,R,S,C,Cs,Cp,Cc,Ct=lpeg.P,lpeg.R,lpeg.S,lpeg.C,lpeg.Cs,lpeg.Cp,lpeg.Cc,lpeg.Ct
-local attributes=lfs.attributes
-function lfs.isdir(name)
- if name then
- return attributes(name,"mode")=="directory"
- end
-end
-function lfs.isfile(name)
- if name then
- local a=attributes(name,"mode")
- return a=="file" or a=="link" or nil
- end
-end
-function lfs.isfound(name)
- if name then
- local a=attributes(name,"mode")
- return (a=="file" or a=="link") and name or nil
- end
-end
-function lfs.modification(name)
- return name and attributes(name,"modification") or nil
-end
-if sandbox then
- sandbox.redefine(lfs.isfile,"lfs.isfile")
- sandbox.redefine(lfs.isdir,"lfs.isdir")
- sandbox.redefine(lfs.isfound,"lfs.isfound")
-end
-local colon=P(":")
-local period=P(".")
-local periods=P("..")
-local fwslash=P("/")
-local bwslash=P("\\")
-local slashes=S("\\/")
-local noperiod=1-period
-local noslashes=1-slashes
-local name=noperiod^1
-local suffix=period/""*(1-period-slashes)^1*-1
-local pattern=C((1-(slashes^1*noslashes^1*-1))^1)*P(1)
-local function pathpart(name,default)
- return name and lpegmatch(pattern,name) or default or ""
-end
-local pattern=(noslashes^0*slashes)^1*C(noslashes^1)*-1
-local function basename(name)
- return name and lpegmatch(pattern,name) or name
-end
-local pattern=(noslashes^0*slashes^1)^0*Cs((1-suffix)^1)*suffix^0
-local function nameonly(name)
- return name and lpegmatch(pattern,name) or name
-end
-local pattern=(noslashes^0*slashes)^0*(noperiod^1*period)^1*C(noperiod^1)*-1
-local function suffixonly(name)
- return name and lpegmatch(pattern,name) or ""
-end
-local pattern=(noslashes^0*slashes)^0*noperiod^1*((period*C(noperiod^1))^1)*-1+Cc("")
-local function suffixesonly(name)
- if name then
- return lpegmatch(pattern,name)
- else
- return ""
- end
-end
-file.pathpart=pathpart
-file.basename=basename
-file.nameonly=nameonly
-file.suffixonly=suffixonly
-file.suffix=suffixonly
-file.suffixesonly=suffixesonly
-file.suffixes=suffixesonly
-file.dirname=pathpart
-file.extname=suffixonly
-local drive=C(R("az","AZ"))*colon
-local path=C((noslashes^0*slashes)^0)
-local suffix=period*C(P(1-period)^0*P(-1))
-local base=C((1-suffix)^0)
-local rest=C(P(1)^0)
-drive=drive+Cc("")
-path=path+Cc("")
-base=base+Cc("")
-suffix=suffix+Cc("")
-local pattern_a=drive*path*base*suffix
-local pattern_b=path*base*suffix
-local pattern_c=C(drive*path)*C(base*suffix)
-local pattern_d=path*rest
-function file.splitname(str,splitdrive)
- if not str then
- elseif splitdrive then
- return lpegmatch(pattern_a,str)
- else
- return lpegmatch(pattern_b,str)
- end
-end
-function file.splitbase(str)
- if str then
- return lpegmatch(pattern_d,str)
- else
- return "",str
- end
-end
-function file.nametotable(str,splitdrive)
- if str then
- local path,drive,subpath,name,base,suffix=lpegmatch(pattern_c,str)
- if splitdrive then
- return {
- path=path,
- drive=drive,
- subpath=subpath,
- name=name,
- base=base,
- suffix=suffix,
- }
- else
- return {
- path=path,
- name=name,
- base=base,
- suffix=suffix,
- }
- end
- end
-end
-local pattern=Cs(((period*(1-period-slashes)^1*-1)/""+1)^1)
-function file.removesuffix(name)
- return name and lpegmatch(pattern,name)
-end
-local suffix=period/""*(1-period-slashes)^1*-1
-local pattern=Cs((noslashes^0*slashes^1)^0*((1-suffix)^1))*Cs(suffix)
-function file.addsuffix(filename,suffix,criterium)
- if not filename or not suffix or suffix=="" then
- return filename
- elseif criterium==true then
- return filename.."."..suffix
- elseif not criterium then
- local n,s=lpegmatch(pattern,filename)
- if not s or s=="" then
- return filename.."."..suffix
- else
- return filename
- end
- else
- local n,s=lpegmatch(pattern,filename)
- if s and s~="" then
- local t=type(criterium)
- if t=="table" then
- for i=1,#criterium do
- if s==criterium[i] then
- return filename
- end
- end
- elseif t=="string" then
- if s==criterium then
- return filename
- end
- end
- end
- return (n or filename).."."..suffix
- end
-end
-local suffix=period*(1-period-slashes)^1*-1
-local pattern=Cs((1-suffix)^0)
-function file.replacesuffix(name,suffix)
- if name and suffix and suffix~="" then
- return lpegmatch(pattern,name).."."..suffix
- else
- return name
- end
-end
-local reslasher=lpeg.replacer(P("\\"),"/")
-function file.reslash(str)
- return str and lpegmatch(reslasher,str)
-end
-if lfs.isreadablefile and lfs.iswritablefile then
- file.is_readable=lfs.isreadablefile
- file.is_writable=lfs.iswritablefile
-else
- function file.is_writable(name)
- if not name then
- elseif lfs.isdir(name) then
- name=name.."/m_t_x_t_e_s_t.tmp"
- local f=io.open(name,"wb")
- if f then
- f:close()
- os.remove(name)
- return true
- end
- elseif lfs.isfile(name) then
- local f=io.open(name,"ab")
- if f then
- f:close()
- return true
- end
- else
- local f=io.open(name,"ab")
- if f then
- f:close()
- os.remove(name)
- return true
- end
- end
- return false
- end
- local readable=P("r")*Cc(true)
- function file.is_readable(name)
- if name then
- local a=attributes(name)
- return a and lpegmatch(readable,a.permissions) or false
- else
- return false
- end
- end
-end
-file.isreadable=file.is_readable
-file.iswritable=file.is_writable
-function file.size(name)
- if name then
- local a=attributes(name)
- return a and a.size or 0
- else
- return 0
- end
-end
-function file.splitpath(str,separator)
- return str and checkedsplit(lpegmatch(reslasher,str),separator or io.pathseparator)
-end
-function file.joinpath(tab,separator)
- return tab and concat(tab,separator or io.pathseparator)
-end
-local someslash=S("\\/")
-local stripper=Cs(P(fwslash)^0/""*reslasher)
-local isnetwork=someslash*someslash*(1-someslash)+(1-fwslash-colon)^1*colon
-local isroot=fwslash^1*-1
-local hasroot=fwslash^1
-local reslasher=lpeg.replacer(S("\\/"),"/")
-local deslasher=lpeg.replacer(S("\\/")^1,"/")
-function file.join(one,two,three,...)
- if not two then
- return one=="" and one or lpegmatch(reslasher,one)
- end
- if one=="" then
- return lpegmatch(stripper,three and concat({ two,three,... },"/") or two)
- end
- if lpegmatch(isnetwork,one) then
- local one=lpegmatch(reslasher,one)
- local two=lpegmatch(deslasher,three and concat({ two,three,... },"/") or two)
- if lpegmatch(hasroot,two) then
- return one..two
- else
- return one.."/"..two
- end
- elseif lpegmatch(isroot,one) then
- local two=lpegmatch(deslasher,three and concat({ two,three,... },"/") or two)
- if lpegmatch(hasroot,two) then
- return two
- else
- return "/"..two
- end
- else
- return lpegmatch(deslasher,concat({ one,two,three,... },"/"))
- end
-end
-local drivespec=R("az","AZ")^1*colon
-local anchors=fwslash+drivespec
-local untouched=periods+(1-period)^1*P(-1)
-local mswindrive=Cs(drivespec*(bwslash/"/"+fwslash)^0)
-local mswinuncpath=(bwslash+fwslash)*(bwslash+fwslash)*Cc("//")
-local splitstarter=(mswindrive+mswinuncpath+Cc(false))*Ct(lpeg.splitat(S("/\\")^1))
-local absolute=fwslash
-function file.collapsepath(str,anchor)
- if not str then
- return
- end
- if anchor==true and not lpegmatch(anchors,str) then
- str=getcurrentdir().."/"..str
- end
- if str=="" or str=="." then
- return "."
- elseif lpegmatch(untouched,str) then
- return lpegmatch(reslasher,str)
- end
- local starter,oldelements=lpegmatch(splitstarter,str)
- local newelements={}
- local i=#oldelements
- while i>0 do
- local element=oldelements[i]
- if element=='.' then
- elseif element=='..' then
- local n=i-1
- while n>0 do
- local element=oldelements[n]
- if element~='..' and element~='.' then
- oldelements[n]='.'
- break
- else
- n=n-1
- end
- end
- if n<1 then
- insert(newelements,1,'..')
- end
- elseif element~="" then
- insert(newelements,1,element)
- end
- i=i-1
- end
- if #newelements==0 then
- return starter or "."
- elseif starter then
- return starter..concat(newelements,'/')
- elseif lpegmatch(absolute,str) then
- return "/"..concat(newelements,'/')
- else
- newelements=concat(newelements,'/')
- if anchor=="." and find(str,"^%./") then
- return "./"..newelements
- else
- return newelements
- end
- end
-end
-local validchars=R("az","09","AZ","--","..")
-local pattern_a=lpeg.replacer(1-validchars)
-local pattern_a=Cs((validchars+P(1)/"-")^1)
-local whatever=P("-")^0/""
-local pattern_b=Cs(whatever*(1-whatever*-1)^1)
-function file.robustname(str,strict)
- if str then
- str=lpegmatch(pattern_a,str) or str
- if strict then
- return lpegmatch(pattern_b,str) or str
- else
- return str
- end
- end
-end
-local loaddata=io.loaddata
-local savedata=io.savedata
-file.readdata=loaddata
-file.savedata=savedata
-function file.copy(oldname,newname)
- if oldname and newname then
- local data=loaddata(oldname)
- if data and data~="" then
- savedata(newname,data)
- end
- end
-end
-local letter=R("az","AZ")+S("_-+")
-local separator=P("://")
-local qualified=period^0*fwslash+letter*colon+letter^1*separator+letter^1*fwslash
-local rootbased=fwslash+letter*colon
-lpeg.patterns.qualified=qualified
-lpeg.patterns.rootbased=rootbased
-function file.is_qualified_path(filename)
- return filename and lpegmatch(qualified,filename)~=nil
-end
-function file.is_rootbased_path(filename)
- return filename and lpegmatch(rootbased,filename)~=nil
-end
-function file.strip(name,dir)
- if name then
- local b,a=match(name,"^(.-)"..dir.."(.*)$")
- return a~="" and a or name
- end
-end
-function lfs.mkdirs(path)
- local full=""
- for sub in gmatch(path,"(/*[^\\/]+)") do
- full=full..sub
- lfs.mkdir(full)
- end
-end
-function file.withinbase(path)
- local l=0
- if not find(path,"^/") then
- path="/"..path
- end
- for dir in gmatch(path,"/([^/]+)") do
- if dir==".." then
- l=l-1
- elseif dir~="." then
- l=l+1
- end
- if l<0 then
- return false
- end
- end
- return true
-end
-local symlinkattributes=lfs.symlinkattributes
-function lfs.readlink(name)
- return symlinkattributes(name,"target") or nil
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-gzip"] = package.loaded["l-gzip"] or true
-
--- original size: 5115, stripped down to: 1699
-
-if not modules then modules={} end modules ['l-gzip']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-gzip=gzip or {}
-if not zlib then
- zlib=xzip
-elseif not xzip then
- xzip=zlib
-end
-if zlib then
- local suffix=file.suffix
- local suffixes=file.suffixes
- local find=string.find
- local openfile=io.open
- local gzipwindow=15+16
- local gziplevel=3
- local identifier="^\x1F\x8B\x08"
- local compress=zlib.compress
- local decompress=zlib.decompress
- function gzip.load(filename)
- local f=openfile(filename,"rb")
- if not f then
- else
- local data=f:read("*all")
- f:close()
- if data and data~="" then
- if suffix(filename)=="gz" then
- data=decompress(data,gzipwindow)
- end
- return data
- end
- end
- end
- function gzip.save(filename,data,level)
- if suffix(filename)~="gz" then
- filename=filename..".gz"
- end
- local f=openfile(filename,"wb")
- if f then
- data=compress(data or "",level or gziplevel,nil,gzipwindow)
- f:write(data)
- f:close()
- return #data
- end
- end
- function gzip.suffix(filename)
- local suffix,extra=suffixes(filename)
- local gzipped=extra=="gz"
- return suffix,gzipped
- end
- function gzip.compressed(s)
- return s and find(s,identifier)
- end
- function gzip.compress(s,level)
- if s and not find(s,identifier) then
- if not level then
- level=gziplevel
- elseif level<=0 then
- return s
- elseif level>9 then
- level=9
- end
- return compress(s,level or gziplevel,nil,gzipwindow) or s
- end
- end
- function gzip.decompress(s)
- if s and find(s,identifier) then
- return decompress(s,gzipwindow)
- else
- return s
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-md5"] = package.loaded["l-md5"] or true
-
--- original size: 3414, stripped down to: 2307
-
-if not modules then modules={} end modules ['l-md5']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if not md5 then
- md5=optionalrequire("md5")
-end
-if not md5 then
- md5={
- sum=function(str) print("error: md5 is not loaded (sum ignored)") return str end,
- sumhexa=function(str) print("error: md5 is not loaded (sumhexa ignored)") return str end,
- }
-end
-local md5,file=md5,file
-local gsub=string.gsub
-local modification,isfile,touch=lfs.modification,lfs.isfile,lfs.touch
-local loaddata,savedata=io.loaddata,io.savedata
-do
- local patterns=lpeg and lpeg.patterns
- if patterns then
- local bytestoHEX=patterns.bytestoHEX
- local bytestohex=patterns.bytestohex
- local bytestodec=patterns.bytestodec
- local lpegmatch=lpeg.match
- local md5sum=md5.sum
- if not md5.HEX then function md5.HEX(str) if str then return lpegmatch(bytestoHEX,md5sum(str)) end end end
- if not md5.hex then function md5.hex(str) if str then return lpegmatch(bytestohex,md5sum(str)) end end end
- if not md5.dec then function md5.dec(str) if str then return lpegmatch(bytestodec,md5sum(str)) end end end
- md5.sumhexa=md5.hex
- md5.sumHEXA=md5.HEX
- end
-end
-local md5HEX=md5.HEX
-function file.needsupdating(oldname,newname,threshold)
- local oldtime=modification(oldname)
- if oldtime then
- local newtime=modification(newname)
- if not newtime then
- return true
- elseif newtime>=oldtime then
- return false
- elseif oldtime-newtime<(threshold or 1) then
- return false
- else
- return true
- end
- else
- return false
- end
-end
-file.needs_updating=file.needsupdating
-function file.syncmtimes(oldname,newname)
- local oldtime=modification(oldname)
- if oldtime and isfile(newname) then
- touch(newname,oldtime,oldtime)
- end
-end
-local function checksum(name)
- if md5 then
- local data=loaddata(name)
- if data then
- return md5HEX(data)
- end
- end
- return nil
-end
-file.checksum=checksum
-function file.loadchecksum(name)
- if md5 then
- local data=loaddata(name..".md5")
- return data and (gsub(data,"%s",""))
- end
- return nil
-end
-function file.savechecksum(name,checksum)
- if not checksum then checksum=checksum(name) end
- if checksum then
- savedata(name..".md5",checksum)
- return checksum
- end
- return nil
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-sha"] = package.loaded["l-sha"] or true
-
--- original size: 1085, stripped down to: 969
-
-if not modules then modules={} end modules ['l-sha']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if sha2 then
- local lpegmatch=lpeg.match
- local lpegpatterns=lpeg.patterns
- local bytestohex=lpegpatterns.bytestohex
- local bytestoHEX=lpegpatterns.bytestoHEX
- local digest256=sha2.digest256
- local digest384=sha2.digest384
- local digest512=sha2.digest512
- sha2.hash256=function(str) return lpegmatch(bytestohex,digest256(str)) end
- sha2.hash384=function(str) return lpegmatch(bytestohex,digest384(str)) end
- sha2.hash512=function(str) return lpegmatch(bytestohex,digest512(str)) end
- sha2.HASH256=function(str) return lpegmatch(bytestoHEX,digest256(str)) end
- sha2.HASH384=function(str) return lpegmatch(bytestoHEX,digest384(str)) end
- sha2.HASH512=function(str) return lpegmatch(bytestoHEX,digest512(str)) end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-url"] = package.loaded["l-url"] or true
-
--- original size: 14755, stripped down to: 6981
-
-if not modules then modules={} end modules ['l-url']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local char,format,byte=string.char,string.format,string.byte
-local concat=table.concat
-local tonumber,type,next=tonumber,type,next
-local P,C,R,S,Cs,Cc,Ct,Cf,Cg,V=lpeg.P,lpeg.C,lpeg.R,lpeg.S,lpeg.Cs,lpeg.Cc,lpeg.Ct,lpeg.Cf,lpeg.Cg,lpeg.V
-local lpegmatch,lpegpatterns,replacer=lpeg.match,lpeg.patterns,lpeg.replacer
-local sortedhash=table.sortedhash
-url=url or {}
-local url=url
-local unescapes={}
-local escapes={}
-setmetatable(unescapes,{ __index=function(t,k)
- local v=char(tonumber(k,16))
- t[k]=v
- return v
-end })
-setmetatable(escapes,{ __index=function(t,k)
- local v=format("%%%02X",byte(k))
- t[k]=v
- return v
-end })
-local colon=P(":")
-local qmark=P("?")
-local hash=P("#")
-local slash=P("/")
-local atsign=P("@")
-local percent=P("%")
-local endofstring=P(-1)
-local hexdigit=R("09","AF","af")
-local plus=P("+")
-local nothing=Cc("")
-local okay=R("09","AZ","az")+S("-_.,:=+*~!'()@&$")
-local escapedchar=(percent*C(hexdigit*hexdigit))/unescapes
-local unescapedchar=P(1)/escapes
-local escaped=(plus/" ")+escapedchar
-local noslash=P("/")/""
-local plustospace=P("+")/" "
-local decoder=Cs((
- plustospace+escapedchar+P("\r\n")/"\n"+P(1)
- )^0 )
-local encoder=Cs((
- R("09","AZ","az")^1+S("-./_")^1+P(" ")/"+"+P("\n")/"\r\n"+unescapedchar
- )^0 )
-lpegpatterns.urldecoder=decoder
-lpegpatterns.urlencoder=encoder
-function url.decode (str) return str and lpegmatch(decoder,str) or str end
-function url.encode (str) return str and lpegmatch(encoder,str) or str end
-function url.unescape(str) return str and lpegmatch(unescaper,str) or str end
-local schemestr=Cs((escaped+(1-colon-slash-qmark-hash))^2)
-local authoritystr=Cs((escaped+(1- slash-qmark-hash))^0)
-local pathstr=Cs((escaped+(1- qmark-hash))^0)
-local querystr=Cs(((1- hash))^0)
-local fragmentstr=Cs((escaped+(1- endofstring))^0)
-local scheme=schemestr*colon+nothing
-local authority=slash*slash*authoritystr+nothing
-local path=slash*pathstr+nothing
-local query=qmark*querystr+nothing
-local fragment=hash*fragmentstr+nothing
-local validurl=scheme*authority*path*query*fragment
-local parser=Ct(validurl)
-lpegpatterns.url=validurl
-lpegpatterns.urlsplitter=parser
-local escaper=Cs((R("09","AZ","az")^1+P(" ")/"%%20"+S("-./_:")^1+P(1)/escapes)^0)
-local unescaper=Cs((escapedchar+1)^0)
-local getcleaner=Cs((P("+++")/"%%2B"+P("+")/"%%20"+P(1))^1)
-lpegpatterns.urlunescaped=escapedchar
-lpegpatterns.urlescaper=escaper
-lpegpatterns.urlunescaper=unescaper
-lpegpatterns.urlgetcleaner=getcleaner
-function url.unescapeget(str)
- return lpegmatch(getcleaner,str)
-end
-local function split(str)
- return (type(str)=="string" and lpegmatch(parser,str)) or str
-end
-local isscheme=schemestr*colon*slash*slash
-local function hasscheme(str)
- if str then
- local scheme=lpegmatch(isscheme,str)
- return scheme~="" and scheme or false
- else
- return false
- end
-end
-local rootletter=R("az","AZ")+S("_-+")
-local separator=P("://")
-local qualified=P(".")^0*P("/")+rootletter*P(":")+rootletter^1*separator+rootletter^1*P("/")
-local rootbased=P("/")+rootletter*P(":")
-local barswapper=replacer("|",":")
-local backslashswapper=replacer("\\","/")
-local equal=P("=")
-local amp=P("&")
-local key=Cs(((plustospace+escapedchar+1)-equal )^0)
-local value=Cs(((plustospace+escapedchar+1)-amp-endofstring)^0)
-local splitquery=Cf (Ct("")*P { "sequence",
- sequence=V("pair")*(amp*V("pair"))^0,
- pair=Cg(key*equal*value),
-},rawset)
-local userpart=(1-atsign-colon)^1
-local serverpart=(1-colon)^1
-local splitauthority=((Cs(userpart)*colon*Cs(userpart)+Cs(userpart)*Cc(nil))*atsign+Cc(nil)*Cc(nil))*Cs(serverpart)*(colon*(serverpart/tonumber)+Cc(nil))
-local function hashed(str)
- if not str or str=="" then
- return {
- scheme="invalid",
- original=str,
- }
- end
- local detailed=split(str)
- local rawscheme=""
- local rawquery=""
- local somescheme=false
- local somequery=false
- if detailed then
- rawscheme=detailed[1]
- rawquery=detailed[4]
- somescheme=rawscheme~=""
- somequery=rawquery~=""
- end
- if not somescheme and not somequery then
- return {
- scheme="file",
- authority="",
- path=str,
- query="",
- fragment="",
- original=str,
- noscheme=true,
- filename=str,
- }
- end
- local authority=detailed[2]
- local path=detailed[3]
- local filename
- local username
- local password
- local host
- local port
- if authority~="" then
- username,password,host,port=lpegmatch(splitauthority,authority)
- end
- if authority=="" then
- filename=path
- elseif path=="" then
- filename=""
- else
- filename=authority.."/"..path
- end
- return {
- scheme=rawscheme,
- authority=authority,
- path=path,
- query=lpegmatch(unescaper,rawquery),
- queries=lpegmatch(splitquery,rawquery),
- fragment=detailed[5],
- original=str,
- noscheme=false,
- filename=filename,
- host=host,
- port=port,
- }
-end
-url.split=split
-url.hasscheme=hasscheme
-url.hashed=hashed
-function url.addscheme(str,scheme)
- if hasscheme(str) then
- return str
- elseif not scheme then
- return "file:///"..str
- else
- return scheme..":///"..str
- end
-end
-function url.construct(hash)
- local result,r={},0
- local scheme=hash.scheme
- local authority=hash.authority
- local path=hash.path
- local queries=hash.queries
- local fragment=hash.fragment
- if scheme and scheme~="" then
- r=r+1;result[r]=lpegmatch(escaper,scheme)
- r=r+1;result[r]="://"
- end
- if authority and authority~="" then
- r=r+1;result[r]=lpegmatch(escaper,authority)
- end
- if path and path~="" then
- r=r+1;result[r]="/"
- r=r+1;result[r]=lpegmatch(escaper,path)
- end
- if queries then
- local done=false
- for k,v in sortedhash(queries) do
- r=r+1;result[r]=done and "&" or "?"
- r=r+1;result[r]=lpegmatch(escaper,k)
- r=r+1;result[r]="="
- r=r+1;result[r]=lpegmatch(escaper,v)
- done=true
- end
- end
- if fragment and fragment~="" then
- r=r+1;result[r]="#"
- r=r+1;result[r]=lpegmatch(escaper,fragment)
- end
- return concat(result)
-end
-local pattern=Cs(slash^-1/""*R("az","AZ")*((S(":|")/":")+P(":"))*slash*P(1)^0)
-function url.filename(filename)
- local spec=hashed(filename)
- local path=spec.path
- return (spec.scheme=="file" and path and lpegmatch(pattern,path)) or filename
-end
-local function escapestring(str)
- return lpegmatch(escaper,str)
-end
-url.escape=escapestring
-function url.query(str)
- if type(str)=="string" then
- return lpegmatch(splitquery,str) or ""
- else
- return str
- end
-end
-function url.toquery(data)
- local td=type(data)
- if td=="string" then
- return #str and escape(data) or nil
- elseif td=="table" then
- if next(data) then
- local t={}
- for k,v in next,data do
- t[#t+1]=format("%s=%s",k,escapestring(v))
- end
- return concat(t,"&")
- end
- else
- end
-end
-local pattern=Cs(noslash^0*(1-noslash*P(-1))^0)
-function url.barepath(path)
- if not path or path=="" then
- return ""
- else
- return lpegmatch(pattern,path)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-dir"] = package.loaded["l-dir"] or true
-
--- original size: 18253, stripped down to: 10816
-
-if not modules then modules={} end modules ['l-dir']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,select=type,select
-local find,gmatch,match,gsub,sub=string.find,string.gmatch,string.match,string.gsub,string.sub
-local concat,insert,remove,unpack=table.concat,table.insert,table.remove,table.unpack
-local lpegmatch=lpeg.match
-local P,S,R,C,Cc,Cs,Ct,Cv,V=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.Cc,lpeg.Cs,lpeg.Ct,lpeg.Cv,lpeg.V
-dir=dir or {}
-local dir=dir
-local lfs=lfs
-local attributes=lfs.attributes
-local walkdir=lfs.dir
-local isdir=lfs.isdir
-local isfile=lfs.isfile
-local currentdir=lfs.currentdir
-local chdir=lfs.chdir
-local mkdir=lfs.mkdir
-local onwindows=os.type=="windows" or find(os.getenv("PATH"),";",1,true)
-if onwindows then
- local tricky=S("/\\")*P(-1)
- isdir=function(name)
- if lpegmatch(tricky,name) then
- return attributes(name,"mode")=="directory"
- else
- return attributes(name.."/.","mode")=="directory"
- end
- end
- isfile=function(name)
- return attributes(name,"mode")=="file"
- end
- lfs.isdir=isdir
- lfs.isfile=isfile
-else
- isdir=function(name)
- return attributes(name,"mode")=="directory"
- end
- isfile=function(name)
- return attributes(name,"mode")=="file"
- end
- lfs.isdir=isdir
- lfs.isfile=isfile
-end
-function dir.current()
- return (gsub(currentdir(),"\\","/"))
-end
-local function glob_pattern_function(path,patt,recurse,action)
- if isdir(path) then
- local usedpath
- if path=="/" then
- usedpath="/."
- elseif not find(path,"/$") then
- usedpath=path.."/."
- path=path.."/"
- else
- usedpath=path
- end
- local dirs
- local nofdirs=0
- for name,mode,size,time in walkdir(usedpath) do
- if name~="." and name~=".." then
- local full=path..name
- if mode==nil then
- mode=attributes(full,'mode')
- end
- if mode=='file' then
- if not patt or find(full,patt) then
- action(full,size,time)
- end
- elseif recurse and mode=="directory" then
- if dirs then
- nofdirs=nofdirs+1
- dirs[nofdirs]=full
- else
- nofdirs=1
- dirs={ full }
- end
- end
- end
- end
- if dirs then
- for i=1,nofdirs do
- glob_pattern_function(dirs[i],patt,recurse,action)
- end
- end
- end
-end
-local function glob_pattern_table(path,patt,recurse,result)
- if not result then
- result={}
- end
- local usedpath
- if path=="/" then
- usedpath="/."
- elseif not find(path,"/$") then
- usedpath=path.."/."
- path=path.."/"
- else
- usedpath=path
- end
- local dirs
- local nofdirs=0
- local noffiles=#result
- for name,mode in walkdir(usedpath) do
- if name~="." and name~=".." then
- local full=path..name
- if mode==nil then
- mode=attributes(full,'mode')
- end
- if mode=='file' then
- if not patt or find(full,patt) then
- noffiles=noffiles+1
- result[noffiles]=full
- end
- elseif recurse and mode=="directory" then
- if dirs then
- nofdirs=nofdirs+1
- dirs[nofdirs]=full
- else
- nofdirs=1
- dirs={ full }
- end
- end
- end
- end
- if dirs then
- for i=1,nofdirs do
- glob_pattern_table(dirs[i],patt,recurse,result)
- end
- end
- return result
-end
-local function globpattern(path,patt,recurse,method)
- local kind=type(method)
- if patt and sub(patt,1,-3)==path then
- patt=false
- end
- local okay=isdir(path)
- if kind=="function" then
- return okay and glob_pattern_function(path,patt,recurse,method) or {}
- elseif kind=="table" then
- return okay and glob_pattern_table(path,patt,recurse,method) or method
- else
- return okay and glob_pattern_table(path,patt,recurse,{}) or {}
- end
-end
-dir.globpattern=globpattern
-local function collectpattern(path,patt,recurse,result)
- local ok,scanner
- result=result or {}
- if path=="/" then
- ok,scanner,first=xpcall(function() return walkdir(path..".") end,function() end)
- else
- ok,scanner,first=xpcall(function() return walkdir(path) end,function() end)
- end
- if ok and type(scanner)=="function" then
- if not find(path,"/$") then
- path=path..'/'
- end
- for name in scanner,first do
- if name=="." then
- elseif name==".." then
- else
- local full=path..name
- local attr=attributes(full)
- local mode=attr.mode
- if mode=='file' then
- if find(full,patt) then
- result[name]=attr
- end
- elseif recurse and mode=="directory" then
- attr.list=collectpattern(full,patt,recurse)
- result[name]=attr
- end
- end
- end
- end
- return result
-end
-dir.collectpattern=collectpattern
-local separator,pattern
-if onwindows then
- local slash=S("/\\")/"/"
- pattern={
- [1]=(Cs(P(".")+slash^1)+Cs(R("az","AZ")*P(":")*slash^0)+Cc("./"))*V(2)*V(3),
- [2]=Cs(((1-S("*?/\\"))^0*slash)^0),
- [3]=Cs(P(1)^0)
- }
-else
- pattern={
- [1]=(C(P(".")+P("/")^1)+Cc("./"))*V(2)*V(3),
- [2]=C(((1-S("*?/"))^0*P("/"))^0),
- [3]=C(P(1)^0)
- }
-end
-local filter=Cs ((
- P("**")/".*"+P("*")/"[^/]*"+P("?")/"[^/]"+P(".")/"%%."+P("+")/"%%+"+P("-")/"%%-"+P(1)
-)^0 )
-local function glob(str,t)
- if type(t)=="function" then
- if type(str)=="table" then
- for s=1,#str do
- glob(str[s],t)
- end
- elseif isfile(str) then
- t(str)
- else
- local root,path,base=lpegmatch(pattern,str)
- if root and path and base then
- local recurse=find(base,"**",1,true)
- local start=root..path
- local result=lpegmatch(filter,start..base)
- globpattern(start,result,recurse,t)
- end
- end
- else
- if type(str)=="table" then
- local t=t or {}
- for s=1,#str do
- glob(str[s],t)
- end
- return t
- elseif isfile(str) then
- if t then
- t[#t+1]=str
- return t
- else
- return { str }
- end
- else
- local root,path,base=lpegmatch(pattern,str)
- if root and path and base then
- local recurse=find(base,"**",1,true)
- local start=root..path
- local result=lpegmatch(filter,start..base)
- return globpattern(start,result,recurse,t)
- else
- return {}
- end
- end
- end
-end
-dir.glob=glob
-local function globfiles(path,recurse,func,files)
- if type(func)=="string" then
- local s=func
- func=function(name) return find(name,s) end
- end
- files=files or {}
- local noffiles=#files
- for name,mode in walkdir(path) do
- if find(name,"^%.") then
- else
- if mode==nil then
- mode=attributes(name,'mode')
- end
- if mode=="directory" then
- if recurse then
- globfiles(path.."/"..name,recurse,func,files)
- end
- elseif mode=="file" then
- if not func or func(name) then
- noffiles=noffiles+1
- files[noffiles]=path.."/"..name
- end
- end
- end
- end
- return files
-end
-dir.globfiles=globfiles
-local function globdirs(path,recurse,func,files)
- if type(func)=="string" then
- local s=func
- func=function(name) return find(name,s) end
- end
- files=files or {}
- local noffiles=#files
- for name,mode in walkdir(path) do
- if find(name,"^%.") then
- else
- if mode==nil then
- mode=attributes(name,'mode')
- end
- if mode=="directory" then
- if not func or func(name) then
- noffiles=noffiles+1
- files[noffiles]=path.."/"..name
- if recurse then
- globdirs(path.."/"..name,recurse,func,files)
- end
- end
- end
- end
- end
- return files
-end
-dir.globdirs=globdirs
-function dir.ls(pattern)
- return concat(glob(pattern),"\n")
-end
-local make_indeed=true
-if onwindows then
- function dir.mkdirs(...)
- local n=select("#",...)
- local str
- if n==1 then
- str=select(1,...)
- if isdir(str) then
- return str,true
- end
- else
- str=""
- for i=1,n do
- local s=select(i,...)
- if s=="" then
- elseif str=="" then
- str=s
- else
- str=str.."/"..s
- end
- end
- end
- local pth=""
- local drive=false
- local first,middle,last=match(str,"^(//)(//*)(.*)$")
- if first then
- else
- first,last=match(str,"^(//)/*(.-)$")
- if first then
- middle,last=match(str,"([^/]+)/+(.-)$")
- if middle then
- pth="//"..middle
- else
- pth="//"..last
- last=""
- end
- else
- first,middle,last=match(str,"^([a-zA-Z]:)(/*)(.-)$")
- if first then
- pth,drive=first..middle,true
- else
- middle,last=match(str,"^(/*)(.-)$")
- if not middle then
- last=str
- end
- end
- end
- end
- for s in gmatch(last,"[^/]+") do
- if pth=="" then
- pth=s
- elseif drive then
- pth,drive=pth..s,false
- else
- pth=pth.."/"..s
- end
- if make_indeed and not isdir(pth) then
- mkdir(pth)
- end
- end
- return pth,(isdir(pth)==true)
- end
-else
- function dir.mkdirs(...)
- local n=select("#",...)
- local str,pth
- if n==1 then
- str=select(1,...)
- if isdir(str) then
- return str,true
- end
- else
- str=""
- for i=1,n do
- local s=select(i,...)
- if s and s~="" then
- if str~="" then
- str=str.."/"..s
- else
- str=s
- end
- end
- end
- end
- str=gsub(str,"/+","/")
- if find(str,"^/") then
- pth="/"
- for s in gmatch(str,"[^/]+") do
- local first=(pth=="/")
- if first then
- pth=pth..s
- else
- pth=pth.."/"..s
- end
- if make_indeed and not first and not isdir(pth) then
- mkdir(pth)
- end
- end
- else
- pth="."
- for s in gmatch(str,"[^/]+") do
- pth=pth.."/"..s
- if make_indeed and not isdir(pth) then
- mkdir(pth)
- end
- end
- end
- return pth,(isdir(pth)==true)
- end
-end
-dir.makedirs=dir.mkdirs
-do
- local chdir=sandbox and sandbox.original(chdir) or chdir
- if onwindows then
- local xcurrentdir=dir.current
- function dir.expandname(str)
- local first,nothing,last=match(str,"^(//)(//*)(.*)$")
- if first then
- first=xcurrentdir().."/"
- end
- if not first then
- first,last=match(str,"^(//)/*(.*)$")
- end
- if not first then
- first,last=match(str,"^([a-zA-Z]:)(.*)$")
- if first and not find(last,"^/") then
- local d=currentdir()
- if chdir(first) then
- first=xcurrentdir()
- end
- chdir(d)
- end
- end
- if not first then
- first,last=xcurrentdir(),str
- end
- last=gsub(last,"//","/")
- last=gsub(last,"/%./","/")
- last=gsub(last,"^/*","")
- first=gsub(first,"/*$","")
- if last=="" or last=="." then
- return first
- else
- return first.."/"..last
- end
- end
- else
- function dir.expandname(str)
- if not find(str,"^/") then
- str=currentdir().."/"..str
- end
- str=gsub(str,"//","/")
- str=gsub(str,"/%./","/")
- str=gsub(str,"(.)/%.$","%1")
- return str
- end
- end
-end
-file.expandname=dir.expandname
-local stack={}
-function dir.push(newdir)
- local curdir=currentdir()
- insert(stack,curdir)
- if newdir and newdir~="" and chdir(newdir) then
- return newdir
- else
- return curdir
- end
-end
-function dir.pop()
- local d=remove(stack)
- if d then
- chdir(d)
- end
- return d
-end
-local function found(...)
- for i=1,select("#",...) do
- local path=select(i,...)
- local kind=type(path)
- if kind=="string" then
- if isdir(path) then
- return path
- end
- elseif kind=="table" then
- local path=found(unpack(path))
- if path then
- return path
- end
- end
- end
-end
-dir.found=found
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-boolean"] = package.loaded["l-boolean"] or true
-
--- original size: 1850, stripped down to: 1498
-
-if not modules then modules={} end modules ['l-boolean']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,tonumber=type,tonumber
-boolean=boolean or {}
-local boolean=boolean
-function boolean.tonumber(b)
- if b then return 1 else return 0 end
-end
-function toboolean(str,tolerant)
- if str==nil then
- return false
- elseif str==false then
- return false
- elseif str==true then
- return true
- elseif str=="true" then
- return true
- elseif str=="false" then
- return false
- elseif not tolerant then
- return false
- elseif str==0 then
- return false
- elseif (tonumber(str) or 0)>0 then
- return true
- else
- return str=="yes" or str=="on" or str=="t"
- end
-end
-string.toboolean=toboolean
-function string.booleanstring(str)
- if str=="0" then
- return false
- elseif str=="1" then
- return true
- elseif str=="" then
- return false
- elseif str=="false" then
- return false
- elseif str=="true" then
- return true
- elseif (tonumber(str) or 0)>0 then
- return true
- else
- return str=="yes" or str=="on" or str=="t"
- end
-end
-function string.is_boolean(str,default,strict)
- if type(str)=="string" then
- if str=="true" or str=="yes" or str=="on" or str=="t" or (not strict and str=="1") then
- return true
- elseif str=="false" or str=="no" or str=="off" or str=="f" or (not strict and str=="0") then
- return false
- end
- end
- return default
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-unicode"] = package.loaded["l-unicode"] or true
-
--- original size: 41303, stripped down to: 17277
-
-if not modules then modules={} end modules ['l-unicode']={
- version=1.001,
- optimize=true,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utf=utf or {}
-unicode=nil
-if not string.utfcharacters then
- local gmatch=string.gmatch
- function string.characters(str)
- return gmatch(str,".[\128-\191]*")
- end
-end
-utf.characters=string.utfcharacters
-local type=type
-local char,byte,format,sub,gmatch=string.char,string.byte,string.format,string.sub,string.gmatch
-local concat=table.concat
-local P,C,R,Cs,Ct,Cmt,Cc,Carg,Cp=lpeg.P,lpeg.C,lpeg.R,lpeg.Cs,lpeg.Ct,lpeg.Cmt,lpeg.Cc,lpeg.Carg,lpeg.Cp
-local lpegmatch=lpeg.match
-local patterns=lpeg.patterns
-local tabletopattern=lpeg.utfchartabletopattern
-local bytepairs=string.bytepairs
-local finder=lpeg.finder
-local replacer=lpeg.replacer
-local p_utftype=patterns.utftype
-local p_utfstricttype=patterns.utfstricttype
-local p_utfoffset=patterns.utfoffset
-local p_utf8character=patterns.utf8character
-local p_utf8char=patterns.utf8char
-local p_utf8byte=patterns.utf8byte
-local p_utfbom=patterns.utfbom
-local p_newline=patterns.newline
-local p_whitespace=patterns.whitespace
-if not utf.char then
- utf.char=string.utfcharacter or (utf8 and utf8.char)
- if not utf.char then
- local char=string.char
- if bit32 then
- local rshift=bit32.rshift
- function utf.char(n)
- if n<0x80 then
- return char(n)
- elseif n<0x800 then
- return char(
- 0xC0+rshift(n,6),
- 0x80+(n%0x40)
- )
- elseif n<0x10000 then
- return char(
- 0xE0+rshift(n,12),
- 0x80+(rshift(n,6)%0x40),
- 0x80+(n%0x40)
- )
- elseif n<0x200000 then
- return char(
- 0xF0+rshift(n,18),
- 0x80+(rshift(n,12)%0x40),
- 0x80+(rshift(n,6)%0x40),
- 0x80+(n%0x40)
- )
- else
- return ""
- end
- end
- else
- local floor=math.floor
- function utf.char(n)
- if n<0x80 then
- return char(n)
- elseif n<0x800 then
- return char(
- 0xC0+floor(n/0x40),
- 0x80+(n%0x40)
- )
- elseif n<0x10000 then
- return char(
- 0xE0+floor(n/0x1000),
- 0x80+(floor(n/0x40)%0x40),
- 0x80+(n%0x40)
- )
- elseif n<0x200000 then
- return char(
- 0xF0+floor(n/0x40000),
- 0x80+(floor(n/0x1000)%0x40),
- 0x80+(floor(n/0x40)%0x40),
- 0x80+(n%0x40)
- )
- else
- return ""
- end
- end
- end
- end
-end
-if not utf.byte then
- utf.byte=string.utfvalue or (utf8 and utf8.codepoint)
- if not utf.byte then
- function utf.byte(c)
- return lpegmatch(p_utf8byte,c)
- end
- end
-end
-local utfchar,utfbyte=utf.char,utf.byte
-function utf.filetype(data)
- return data and lpegmatch(p_utftype,data) or "unknown"
-end
-local toentities=Cs (
- (
- patterns.utf8one+(
- patterns.utf8two+patterns.utf8three+patterns.utf8four
- )/function(s) local b=utfbyte(s) if b<127 then return s else return format("&#%X;",b) end end
- )^0
-)
-patterns.toentities=toentities
-function utf.toentities(str)
- return lpegmatch(toentities,str)
-end
-local one=P(1)
-local two=C(1)*C(1)
-local four=C(R(utfchar(0xD8),utfchar(0xFF)))*C(1)*C(1)*C(1)
-local pattern=P("\254\255")*Cs((
- four/function(a,b,c,d)
- local ab=0xFF*byte(a)+byte(b)
- local cd=0xFF*byte(c)+byte(d)
- return utfchar((ab-0xD800)*0x400+(cd-0xDC00)+0x10000)
- end+two/function(a,b)
- return utfchar(byte(a)*256+byte(b))
- end+one
- )^1 )+P("\255\254")*Cs((
- four/function(b,a,d,c)
- local ab=0xFF*byte(a)+byte(b)
- local cd=0xFF*byte(c)+byte(d)
- return utfchar((ab-0xD800)*0x400+(cd-0xDC00)+0x10000)
- end+two/function(b,a)
- return utfchar(byte(a)*256+byte(b))
- end+one
- )^1 )
-function string.toutf(s)
- return lpegmatch(pattern,s) or s
-end
-local validatedutf=Cs (
- (
- patterns.utf8one+patterns.utf8two+patterns.utf8three+patterns.utf8four+P(1)/"�"
- )^0
-)
-patterns.validatedutf=validatedutf
-function utf.is_valid(str)
- return type(str)=="string" and lpegmatch(validatedutf,str) or false
-end
-if not utf.len then
- utf.len=string.utflength or (utf8 and utf8.len)
- if not utf.len then
- local n,f=0,1
- local utfcharcounter=patterns.utfbom^-1*Cmt (
- Cc(1)*patterns.utf8one^1+Cc(2)*patterns.utf8two^1+Cc(3)*patterns.utf8three^1+Cc(4)*patterns.utf8four^1,
- function(_,t,d)
- n=n+(t-f)/d
- f=t
- return true
- end
- )^0
- function utf.len(str)
- n,f=0,1
- lpegmatch(utfcharcounter,str or "")
- return n
- end
- end
-end
-utf.length=utf.len
-if not utf.sub then
- local utflength=utf.length
- local b,e,n,first,last=0,0,0,0,0
- local function slide_zero(s,p)
- n=n+1
- if n>=last then
- e=p-1
- else
- return p
- end
- end
- local function slide_one(s,p)
- n=n+1
- if n==first then
- b=p
- end
- if n>=last then
- e=p-1
- else
- return p
- end
- end
- local function slide_two(s,p)
- n=n+1
- if n==first then
- b=p
- else
- return true
- end
- end
- local pattern_zero=Cmt(p_utf8character,slide_zero)^0
- local pattern_one=Cmt(p_utf8character,slide_one )^0
- local pattern_two=Cmt(p_utf8character,slide_two )^0
- local pattern_first=C(p_utf8character)
- function utf.sub(str,start,stop)
- if not start then
- return str
- end
- if start==0 then
- start=1
- end
- if not stop then
- if start<0 then
- local l=utflength(str)
- start=l+start
- else
- start=start-1
- end
- b,n,first=0,0,start
- lpegmatch(pattern_two,str)
- if n>=first then
- return sub(str,b)
- else
- return ""
- end
- end
- if start<0 or stop<0 then
- local l=utf.length(str)
- if start<0 then
- start=l+start
- if start<=0 then
- start=1
- else
- start=start+1
- end
- end
- if stop<0 then
- stop=l+stop
- if stop==0 then
- stop=1
- else
- stop=stop+1
- end
- end
- end
- if start==1 and stop==1 then
- return lpegmatch(pattern_first,str) or ""
- elseif start>stop then
- return ""
- elseif start>1 then
- b,e,n,first,last=0,0,0,start-1,stop
- lpegmatch(pattern_one,str)
- if n>=first and e==0 then
- e=#str
- end
- return sub(str,b,e)
- else
- b,e,n,last=1,0,0,stop
- lpegmatch(pattern_zero,str)
- if e==0 then
- e=#str
- end
- return sub(str,b,e)
- end
- end
-end
-function utf.remapper(mapping,option,action)
- local variant=type(mapping)
- if variant=="table" then
- action=action or mapping
- if option=="dynamic" then
- local pattern=false
- table.setmetatablenewindex(mapping,function(t,k,v) rawset(t,k,v) pattern=false end)
- return function(str)
- if not str or str=="" then
- return ""
- else
- if not pattern then
- pattern=Cs((tabletopattern(mapping)/action+p_utf8character)^0)
- end
- return lpegmatch(pattern,str)
- end
- end
- elseif option=="pattern" then
- return Cs((tabletopattern(mapping)/action+p_utf8character)^0)
- else
- local pattern=Cs((tabletopattern(mapping)/action+p_utf8character)^0)
- return function(str)
- if not str or str=="" then
- return ""
- else
- return lpegmatch(pattern,str)
- end
- end,pattern
- end
- elseif variant=="function" then
- if option=="pattern" then
- return Cs((p_utf8character/mapping+p_utf8character)^0)
- else
- local pattern=Cs((p_utf8character/mapping+p_utf8character)^0)
- return function(str)
- if not str or str=="" then
- return ""
- else
- return lpegmatch(pattern,str)
- end
- end,pattern
- end
- else
- return function(str)
- return str or ""
- end
- end
-end
-function utf.replacer(t)
- local r=replacer(t,false,false,true)
- return function(str)
- return lpegmatch(r,str)
- end
-end
-function utf.subtituter(t)
- local f=finder (t)
- local r=replacer(t,false,false,true)
- return function(str)
- local i=lpegmatch(f,str)
- if not i then
- return str
- elseif i>#str then
- return str
- else
- return lpegmatch(r,str)
- end
- end
-end
-local utflinesplitter=p_utfbom^-1*lpeg.tsplitat(p_newline)
-local utfcharsplitter_ows=p_utfbom^-1*Ct(C(p_utf8character)^0)
-local utfcharsplitter_iws=p_utfbom^-1*Ct((p_whitespace^1+C(p_utf8character))^0)
-local utfcharsplitter_raw=Ct(C(p_utf8character)^0)
-patterns.utflinesplitter=utflinesplitter
-function utf.splitlines(str)
- return lpegmatch(utflinesplitter,str or "")
-end
-function utf.split(str,ignorewhitespace)
- if ignorewhitespace then
- return lpegmatch(utfcharsplitter_iws,str or "")
- else
- return lpegmatch(utfcharsplitter_ows,str or "")
- end
-end
-function utf.totable(str)
- return lpegmatch(utfcharsplitter_raw,str)
-end
-function utf.magic(f)
- local str=f:read(4) or ""
- local off=lpegmatch(p_utfoffset,str)
- if off<4 then
- f:seek('set',off)
- end
- return lpegmatch(p_utftype,str)
-end
-local utf16_to_utf8_be,utf16_to_utf8_le
-local utf32_to_utf8_be,utf32_to_utf8_le
-local utf_16_be_getbom=patterns.utfbom_16_be^-1
-local utf_16_le_getbom=patterns.utfbom_16_le^-1
-local utf_32_be_getbom=patterns.utfbom_32_be^-1
-local utf_32_le_getbom=patterns.utfbom_32_le^-1
-local utf_16_be_linesplitter=utf_16_be_getbom*lpeg.tsplitat(patterns.utf_16_be_nl)
-local utf_16_le_linesplitter=utf_16_le_getbom*lpeg.tsplitat(patterns.utf_16_le_nl)
-local utf_32_be_linesplitter=utf_32_be_getbom*lpeg.tsplitat(patterns.utf_32_be_nl)
-local utf_32_le_linesplitter=utf_32_le_getbom*lpeg.tsplitat(patterns.utf_32_le_nl)
-local more=0
-local p_utf16_to_utf8_be=C(1)*C(1)/function(left,right)
- local now=256*byte(left)+byte(right)
- if more>0 then
- now=(more-0xD800)*0x400+(now-0xDC00)+0x10000
- more=0
- return utfchar(now)
- elseif now>=0xD800 and now<=0xDBFF then
- more=now
- return ""
- else
- return utfchar(now)
- end
-end
-local p_utf16_to_utf8_le=C(1)*C(1)/function(right,left)
- local now=256*byte(left)+byte(right)
- if more>0 then
- now=(more-0xD800)*0x400+(now-0xDC00)+0x10000
- more=0
- return utfchar(now)
- elseif now>=0xD800 and now<=0xDBFF then
- more=now
- return ""
- else
- return utfchar(now)
- end
-end
-local p_utf32_to_utf8_be=C(1)*C(1)*C(1)*C(1)/function(a,b,c,d)
- return utfchar(256*256*256*byte(a)+256*256*byte(b)+256*byte(c)+byte(d))
-end
-local p_utf32_to_utf8_le=C(1)*C(1)*C(1)*C(1)/function(a,b,c,d)
- return utfchar(256*256*256*byte(d)+256*256*byte(c)+256*byte(b)+byte(a))
-end
-p_utf16_to_utf8_be=P(true)/function() more=0 end*utf_16_be_getbom*Cs(p_utf16_to_utf8_be^0)
-p_utf16_to_utf8_le=P(true)/function() more=0 end*utf_16_le_getbom*Cs(p_utf16_to_utf8_le^0)
-p_utf32_to_utf8_be=P(true)/function() more=0 end*utf_32_be_getbom*Cs(p_utf32_to_utf8_be^0)
-p_utf32_to_utf8_le=P(true)/function() more=0 end*utf_32_le_getbom*Cs(p_utf32_to_utf8_le^0)
-patterns.utf16_to_utf8_be=p_utf16_to_utf8_be
-patterns.utf16_to_utf8_le=p_utf16_to_utf8_le
-patterns.utf32_to_utf8_be=p_utf32_to_utf8_be
-patterns.utf32_to_utf8_le=p_utf32_to_utf8_le
-utf16_to_utf8_be=function(s)
- if s and s~="" then
- return lpegmatch(p_utf16_to_utf8_be,s)
- else
- return s
- end
-end
-local utf16_to_utf8_be_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_16_be_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf16_to_utf8_be,s)
- end
- end
- return t
-end
-utf16_to_utf8_le=function(s)
- if s and s~="" then
- return lpegmatch(p_utf16_to_utf8_le,s)
- else
- return s
- end
-end
-local utf16_to_utf8_le_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_16_le_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf16_to_utf8_le,s)
- end
- end
- return t
-end
-utf32_to_utf8_be=function(s)
- if s and s~="" then
- return lpegmatch(p_utf32_to_utf8_be,s)
- else
- return s
- end
-end
-local utf32_to_utf8_be_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_32_be_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf32_to_utf8_be,s)
- end
- end
- return t
-end
-utf32_to_utf8_le=function(s)
- if s and s~="" then
- return lpegmatch(p_utf32_to_utf8_le,s)
- else
- return s
- end
-end
-local utf32_to_utf8_le_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_32_le_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf32_to_utf8_le,s)
- end
- end
- return t
-end
-utf.utf16_to_utf8_le_t=utf16_to_utf8_le_t
-utf.utf16_to_utf8_be_t=utf16_to_utf8_be_t
-utf.utf32_to_utf8_le_t=utf32_to_utf8_le_t
-utf.utf32_to_utf8_be_t=utf32_to_utf8_be_t
-utf.utf16_to_utf8_le=utf16_to_utf8_le
-utf.utf16_to_utf8_be=utf16_to_utf8_be
-utf.utf32_to_utf8_le=utf32_to_utf8_le
-utf.utf32_to_utf8_be=utf32_to_utf8_be
-function utf.utf8_to_utf8_t(t)
- return type(t)=="string" and lpegmatch(utflinesplitter,t) or t
-end
-function utf.utf16_to_utf8_t(t,endian)
- return endian and utf16_to_utf8_be_t(t) or utf16_to_utf8_le_t(t) or t
-end
-function utf.utf32_to_utf8_t(t,endian)
- return endian and utf32_to_utf8_be_t(t) or utf32_to_utf8_le_t(t) or t
-end
-if bit32 then
- local rshift=bit32.rshift
- local function little(b)
- if b<0x10000 then
- return char(b%256,rshift(b,8))
- else
- b=b-0x10000
- local b1=rshift(b,10)+0xD800
- local b2=b%1024+0xDC00
- return char(b1%256,rshift(b1,8),b2%256,rshift(b2,8))
- end
- end
- local function big(b)
- if b<0x10000 then
- return char(rshift(b,8),b%256)
- else
- b=b-0x10000
- local b1=rshift(b,10)+0xD800
- local b2=b%1024+0xDC00
- return char(rshift(b1,8),b1%256,rshift(b2,8),b2%256)
- end
- end
- local l_remap=Cs((p_utf8byte/little+P(1)/"")^0)
- local b_remap=Cs((p_utf8byte/big+P(1)/"")^0)
- local function utf8_to_utf16_be(str,nobom)
- if nobom then
- return lpegmatch(b_remap,str)
- else
- return char(254,255)..lpegmatch(b_remap,str)
- end
- end
- local function utf8_to_utf16_le(str,nobom)
- if nobom then
- return lpegmatch(l_remap,str)
- else
- return char(255,254)..lpegmatch(l_remap,str)
- end
- end
- utf.utf8_to_utf16_be=utf8_to_utf16_be
- utf.utf8_to_utf16_le=utf8_to_utf16_le
- function utf.utf8_to_utf16(str,littleendian,nobom)
- if littleendian then
- return utf8_to_utf16_le(str,nobom)
- else
- return utf8_to_utf16_be(str,nobom)
- end
- end
-end
-local pattern=Cs (
- (p_utf8byte/function(unicode ) return format("0x%04X",unicode) end)*(p_utf8byte*Carg(1)/function(unicode,separator) return format("%s0x%04X",separator,unicode) end)^0
-)
-function utf.tocodes(str,separator)
- return lpegmatch(pattern,str,1,separator or " ")
-end
-function utf.ustring(s)
- return format("U+%05X",type(s)=="number" and s or utfbyte(s))
-end
-function utf.xstring(s)
- return format("0x%05X",type(s)=="number" and s or utfbyte(s))
-end
-function utf.toeight(str)
- if not str or str=="" then
- return nil
- end
- local utftype=lpegmatch(p_utfstricttype,str)
- if utftype=="utf-8" then
- return sub(str,4)
- elseif utftype=="utf-16-be" then
- return utf16_to_utf8_be(str)
- elseif utftype=="utf-16-le" then
- return utf16_to_utf8_le(str)
- else
- return str
- end
-end
-do
- local p_nany=p_utf8character/""
- local cache={}
- function utf.count(str,what)
- if type(what)=="string" then
- local p=cache[what]
- if not p then
- p=Cs((P(what)/" "+p_nany)^0)
- cache[p]=p
- end
- return #lpegmatch(p,str)
- else
- return #lpegmatch(Cs((P(what)/" "+p_nany)^0),str)
- end
- end
-end
-if not string.utfvalues then
- local find=string.find
- local dummy=function()
- end
- function string.utfvalues(str)
- local n=#str
- if n==0 then
- return dummy
- elseif n==1 then
- return function() return utfbyte(str) end
- else
- local p=1
- return function()
- local b,e=find(str,".[\128-\191]*",p)
- if b then
- p=e+1
- return utfbyte(sub(str,b,e))
- end
- end
- end
- end
-end
-utf.values=string.utfvalues
-function utf.chrlen(u)
- return
- (u<0x80 and 1) or
- (u<0xE0 and 2) or
- (u<0xF0 and 3) or
- (u<0xF8 and 4) or
- (u<0xFC and 5) or
- (u<0xFE and 6) or 0
-end
-if bit32 then
- local extract=bit32.extract
- local char=string.char
- function utf.toutf32string(n)
- if n<=0xFF then
- return
- char(n).."\000\000\000"
- elseif n<=0xFFFF then
- return
- char(extract(n,0,8))..char(extract(n,8,8)).."\000\000"
- elseif n<=0xFFFFFF then
- return
- char(extract(n,0,8))..char(extract(n,8,8))..char(extract(n,16,8)).."\000"
- else
- return
- char(extract(n,0,8))..char(extract(n,8,8))..char(extract(n,16,8))..char(extract(n,24,8))
- end
- end
-end
-local len=utf.len
-local rep=rep
-function string.utfpadd(s,n)
- if n and n~=0 then
- local l=len(s)
- if n>0 then
- local d=n-l
- if d>0 then
- return rep(c or " ",d)..s
- end
- else
- local d=- n-l
- if d>0 then
- return s..rep(c or " ",d)
- end
- end
- end
- return s
-end
-do
- local utfcharacters=utf.characters or string.utfcharacters
- local utfchar=utf.char or string.utfcharacter
- lpeg.UP=P
- if utfcharacters then
- function lpeg.US(str)
- local p=P(false)
- for uc in utfcharacters(str) do
- p=p+P(uc)
- end
- return p
- end
- else
- function lpeg.US(str)
- local p=P(false)
- local f=function(uc)
- p=p+P(uc)
- end
- lpegmatch((p_utf8char/f)^0,str)
- return p
- end
- end
- local range=p_utf8byte*p_utf8byte+Cc(false)
- function lpeg.UR(str,more)
- local first,last
- if type(str)=="number" then
- first=str
- last=more or first
- else
- first,last=lpegmatch(range,str)
- if not last then
- return P(str)
- end
- end
- if first==last then
- return P(str)
- end
- if not utfchar then
- utfchar=utf.char
- end
- if utfchar and (last-first<8) then
- local p=P(false)
- for i=first,last do
- p=p+P(utfchar(i))
- end
- return p
- else
- local f=function(b)
- return b>=first and b<=last
- end
- return p_utf8byte/f
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-math"] = package.loaded["l-math"] or true
-
--- original size: 2555, stripped down to: 1831
-
-if not modules then modules={} end modules ['l-math']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if not math.ceiling then
- math.ceiling=math.ceil
-end
-if not math.round then
- local floor=math.floor
- function math.round(x) return floor(x+0.5) end
-end
-if not math.div then
- local floor=math.floor
- function math.div(n,m) return floor(n/m) end
-end
-if not math.mod then
- function math.mod(n,m) return n%m end
-end
-if not math.sind then
- local sin,cos,tan=math.sin,math.cos,math.tan
- local pipi=2*math.pi/360
- function math.sind(d) return sin(d*pipi) end
- function math.cosd(d) return cos(d*pipi) end
- function math.tand(d) return tan(d*pipi) end
-end
-if not math.odd then
- function math.odd (n) return n%2~=0 end
- function math.even(n) return n%2==0 end
-end
-if not math.cosh then
- local exp=math.exp
- function math.cosh(x)
- local xx=exp(x)
- return (xx+1/xx)/2
- end
- function math.sinh(x)
- local xx=exp(x)
- return (xx-1/xx)/2
- end
- function math.tanh(x)
- local xx=exp(x)
- return (xx-1/xx)/(xx+1/xx)
- end
-end
-if not math.pow then
- function math.pow(x,y)
- return x^y
- end
-end
-if not math.atan2 then
- math.atan2=math.atan
-end
-if not math.ldexp then
- function math.ldexp(x,e)
- return x*2.0^e
- end
-end
-if not math.log10 then
- local log=math.log
- function math.log10(x)
- return log(x,10)
- end
-end
-if not math.type then
- function math.type()
- return "float"
- end
-end
-if not math.tointeger then
- math.mininteger=-0x4FFFFFFFFFFF
- math.maxinteger=0x4FFFFFFFFFFF
- local floor=math.floor
- function math.tointeger(n)
- local f=floor(n)
- return f==n and f or nil
- end
-end
-if not math.ult then
- local floor=math.floor
- function math.tointeger(m,n)
- return floor(m)<floor(n)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-str"] = package.loaded["util-str"] or true
-
--- original size: 45129, stripped down to: 23525
-
-if not modules then modules={} end modules ['util-str']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities=utilities or {}
-utilities.strings=utilities.strings or {}
-local strings=utilities.strings
-local format,gsub,rep,sub,find=string.format,string.gsub,string.rep,string.sub,string.find
-local load,dump=load,string.dump
-local tonumber,type,tostring,next,setmetatable=tonumber,type,tostring,next,setmetatable
-local unpack,concat=table.unpack,table.concat
-local P,V,C,S,R,Ct,Cs,Cp,Carg,Cc=lpeg.P,lpeg.V,lpeg.C,lpeg.S,lpeg.R,lpeg.Ct,lpeg.Cs,lpeg.Cp,lpeg.Carg,lpeg.Cc
-local patterns,lpegmatch=lpeg.patterns,lpeg.match
-local utfchar,utfbyte,utflen=utf.char,utf.byte,utf.len
-local loadstripped=function(str,shortcuts)
- if shortcuts then
- return load(dump(load(str),true),nil,nil,shortcuts)
- else
- return load(dump(load(str),true))
- end
-end
-if not number then number={} end
-local stripzero=patterns.stripzero
-local stripzeros=patterns.stripzeros
-local newline=patterns.newline
-local endofstring=patterns.endofstring
-local anything=patterns.anything
-local whitespace=patterns.whitespace
-local space=patterns.space
-local spacer=patterns.spacer
-local spaceortab=patterns.spaceortab
-local digit=patterns.digit
-local sign=patterns.sign
-local period=patterns.period
-local ptf=1/65536
-local bpf=(7200/7227)/65536
-local function points(n)
- if n==0 then
- return "0pt"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0pt"
- end
- n=n*ptf
- if n%1==0 then
- return format("%ipt",n)
- else
- return lpegmatch(stripzeros,format("%.5fpt",n))
- end
-end
-local function nupoints(n)
- if n==0 then
- return "0"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0"
- end
- n=n*ptf
- if n%1==0 then
- return format("%i",n)
- else
- return format("%.5f",n)
- end
-end
-local function basepoints(n)
- if n==0 then
- return "0bp"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0bp"
- end
- n=n*bpf
- if n%1==0 then
- return format("%ibp",n)
- else
- return lpegmatch(stripzeros,format("%.5fbp",n))
- end
-end
-local function nubasepoints(n)
- if n==0 then
- return "0"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0"
- end
- n=n*bpf
- if n%1==0 then
- return format("%i",n)
- else
- return format("%.5f",n)
- end
-end
-number.points=points
-number.nupoints=nupoints
-number.basepoints=basepoints
-number.nubasepoints=nubasepoints
-local rubish=spaceortab^0*newline
-local anyrubish=spaceortab+newline
-local stripped=(spaceortab^1/"")*newline
-local leading=rubish^0/""
-local trailing=(anyrubish^1*endofstring)/""
-local redundant=rubish^3/"\n"
-local pattern=Cs(leading*(trailing+redundant+stripped+anything)^0)
-function strings.collapsecrlf(str)
- return lpegmatch(pattern,str)
-end
-local repeaters={}
-function strings.newrepeater(str,offset)
- offset=offset or 0
- local s=repeaters[str]
- if not s then
- s={}
- repeaters[str]=s
- end
- local t=s[offset]
- if t then
- return t
- end
- t={}
- setmetatable(t,{ __index=function(t,k)
- if not k then
- return ""
- end
- local n=k+offset
- local s=n>0 and rep(str,n) or ""
- t[k]=s
- return s
- end })
- s[offset]=t
- return t
-end
-local extra,tab,start=0,0,4,0
-local nspaces=strings.newrepeater(" ")
-string.nspaces=nspaces
-local pattern=Carg(1)/function(t)
- extra,tab,start=0,t or 7,1
- end*Cs((
- Cp()*patterns.tab/function(position)
- local current=(position-start+1)+extra
- local spaces=tab-(current-1)%tab
- if spaces>0 then
- extra=extra+spaces-1
- return nspaces[spaces]
- else
- return ""
- end
- end+newline*Cp()/function(position)
- extra,start=0,position
- end+anything
- )^1)
-function strings.tabtospace(str,tab)
- return lpegmatch(pattern,str,1,tab or 7)
-end
-function string.utfpadding(s,n)
- if not n or n==0 then
- return ""
- end
- local l=utflen(s)
- if n>0 then
- return nspaces[n-l]
- else
- return nspaces[-n-l]
- end
-end
-local optionalspace=spacer^0
-local nospace=optionalspace/""
-local endofline=nospace*newline
-local stripend=(whitespace^1*endofstring)/""
-local normalline=(nospace*((1-optionalspace*(newline+endofstring))^1)*nospace)
-local stripempty=endofline^1/""
-local normalempty=endofline^1
-local singleempty=endofline*(endofline^0/"")
-local doubleempty=endofline*endofline^-1*(endofline^0/"")
-local stripstart=stripempty^0
-local intospace=whitespace^1/" "
-local noleading=whitespace^1/""
-local notrailing=noleading*endofstring
-local p_prune_normal=Cs (stripstart*(stripend+normalline+normalempty )^0 )
-local p_prune_collapse=Cs (stripstart*(stripend+normalline+doubleempty )^0 )
-local p_prune_noempty=Cs (stripstart*(stripend+normalline+singleempty )^0 )
-local p_prune_intospace=Cs (noleading*(notrailing+intospace+1 )^0 )
-local p_retain_normal=Cs ((normalline+normalempty )^0 )
-local p_retain_collapse=Cs ((normalline+doubleempty )^0 )
-local p_retain_noempty=Cs ((normalline+singleempty )^0 )
-local striplinepatterns={
- ["prune"]=p_prune_normal,
- ["prune and collapse"]=p_prune_collapse,
- ["prune and no empty"]=p_prune_noempty,
- ["prune and to space"]=p_prune_intospace,
- ["retain"]=p_retain_normal,
- ["retain and collapse"]=p_retain_collapse,
- ["retain and no empty"]=p_retain_noempty,
- ["collapse"]=patterns.collapser,
-}
-setmetatable(striplinepatterns,{ __index=function(t,k) return p_prune_collapse end })
-strings.striplinepatterns=striplinepatterns
-function strings.striplines(str,how)
- return str and lpegmatch(striplinepatterns[how],str) or str
-end
-function strings.collapse(str)
- return str and lpegmatch(p_prune_intospace,str) or str
-end
-strings.striplong=strings.striplines
-function strings.nice(str)
- str=gsub(str,"[:%-+_]+"," ")
- return str
-end
-local n=0
-local sequenced=table.sequenced
-function string.autodouble(s,sep)
- if s==nil then
- return '""'
- end
- local t=type(s)
- if t=="number" then
- return tostring(s)
- end
- if t=="table" then
- return ('"'..sequenced(s,sep or ",")..'"')
- end
- return ('"'..tostring(s)..'"')
-end
-function string.autosingle(s,sep)
- if s==nil then
- return "''"
- end
- local t=type(s)
- if t=="number" then
- return tostring(s)
- end
- if t=="table" then
- return ("'"..sequenced(s,sep or ",").."'")
- end
- return ("'"..tostring(s).."'")
-end
-local tracedchars={ [0]=
- "[null]","[soh]","[stx]","[etx]","[eot]","[enq]","[ack]","[bel]",
- "[bs]","[ht]","[lf]","[vt]","[ff]","[cr]","[so]","[si]",
- "[dle]","[dc1]","[dc2]","[dc3]","[dc4]","[nak]","[syn]","[etb]",
- "[can]","[em]","[sub]","[esc]","[fs]","[gs]","[rs]","[us]",
- "[space]",
-}
-string.tracedchars=tracedchars
-strings.tracers=tracedchars
-function string.tracedchar(b)
- if type(b)=="number" then
- return tracedchars[b] or (utfchar(b).." (U+"..format("%05X",b)..")")
- else
- local c=utfbyte(b)
- return tracedchars[c] or (b.." (U+"..(c and format("%05X",c) or "?????")..")")
- end
-end
-function number.signed(i)
- if i>0 then
- return "+",i
- else
- return "-",-i
- end
-end
-local two=digit*digit
-local three=two*digit
-local prefix=(Carg(1)*three)^1
-local splitter=Cs (
- (((1-(three^1*period))^1+C(three))*prefix+C((1-period)^1))*(anything/""*Carg(2))*C(2)
-)
-local splitter3=Cs (
- three*prefix*endofstring+two*prefix*endofstring+digit*prefix*endofstring+three+two+digit
-)
-patterns.formattednumber=splitter
-function number.formatted(n,sep1,sep2)
- if sep1==false then
- if type(n)=="number" then
- n=tostring(n)
- end
- return lpegmatch(splitter3,n,1,sep2 or ".")
- else
- if type(n)=="number" then
- n=format("%0.2f",n)
- end
- if sep1==true then
- return lpegmatch(splitter,n,1,".",",")
- elseif sep1=="." then
- return lpegmatch(splitter,n,1,sep1,sep2 or ",")
- elseif sep1=="," then
- return lpegmatch(splitter,n,1,sep1,sep2 or ".")
- else
- return lpegmatch(splitter,n,1,sep1 or ",",sep2 or ".")
- end
- end
-end
-local p=Cs(
- P("-")^0*(P("0")^1/"")^0*(1-period)^0*(period*P("0")^1*endofstring/""+period^0)*P(1-P("0")^1*endofstring)^0
- )
-function number.compactfloat(n,fmt)
- if n==0 then
- return "0"
- elseif n==1 then
- return "1"
- end
- n=lpegmatch(p,format(fmt or "%0.3f",n))
- if n=="." or n=="" or n=="-" then
- return "0"
- end
- return n
-end
-local zero=P("0")^1/""
-local plus=P("+")/""
-local minus=P("-")
-local separator=period
-local trailing=zero^1*#S("eE")
-local exponent=(S("eE")*(plus+Cs((minus*zero^0*endofstring)/"")+minus)*zero^0*(endofstring*Cc("0")+anything^1))
-local pattern_a=Cs(minus^0*digit^1*(separator/""*trailing+separator*(trailing+digit)^0)*exponent)
-local pattern_b=Cs((exponent+anything)^0)
-function number.sparseexponent(f,n)
- if not n then
- n=f
- f="%e"
- end
- local tn=type(n)
- if tn=="string" then
- local m=tonumber(n)
- if m then
- return lpegmatch((f=="%e" or f=="%E") and pattern_a or pattern_b,format(f,m))
- end
- elseif tn=="number" then
- return lpegmatch((f=="%e" or f=="%E") and pattern_a or pattern_b,format(f,n))
- end
- return tostring(n)
-end
-local hf={}
-local hs={}
-setmetatable(hf,{ __index=function(t,k)
- local v="%."..k.."f"
- t[k]=v
- return v
-end } )
-setmetatable(hs,{ __index=function(t,k)
- local v="%"..k.."s"
- t[k]=v
- return v
-end } )
-function number.formattedfloat(n,b,a)
- local s=format(hf[a],n)
- local l=(b or 0)+(a or 0)+1
- if #s<l then
- return format(hs[l],s)
- else
- return s
- end
-end
-local template=[[
-%s
-%s
-return function(%s) return %s end
-]]
-local pattern=Cs(Cc('"')*(
- (1-S('"\\\n\r'))^1+P('"')/'\\"'+P('\\')/'\\\\'+P('\n')/'\\n'+P('\r')/'\\r'
-)^0*Cc('"'))
-patterns.escapedquotes=pattern
-function string.escapedquotes(s)
- return lpegmatch(pattern,s)
-end
-local preamble=""
-local environment={
- global=global or _G,
- lpeg=lpeg,
- type=type,
- tostring=tostring,
- tonumber=tonumber,
- format=string.format,
- concat=table.concat,
- signed=number.signed,
- points=number.points,
- nupoints=number.nupoints,
- basepoints=number.basepoints,
- nubasepoints=number.nubasepoints,
- utfchar=utf.char,
- utfbyte=utf.byte,
- lpegmatch=lpeg.match,
- nspaces=string.nspaces,
- utfpadding=string.utfpadding,
- tracedchar=string.tracedchar,
- autosingle=string.autosingle,
- autodouble=string.autodouble,
- sequenced=table.sequenced,
- formattednumber=number.formatted,
- sparseexponent=number.sparseexponent,
- formattedfloat=number.formattedfloat,
- stripzero=patterns.stripzero,
- stripzeros=patterns.stripzeros,
- escapedquotes=string.escapedquotes,
- FORMAT=string.f6,
-}
-local arguments={ "a1" }
-setmetatable(arguments,{ __index=function(t,k)
- local v=t[k-1]..",a"..k
- t[k]=v
- return v
- end
-})
-local prefix_any=C((sign+space+period+digit)^0)
-local prefix_sub=(C((sign+digit)^0)+Cc(0))*period*(C((sign+digit)^0)+Cc(0))
-local prefix_tab=P("{")*C((1-P("}"))^0)*P("}")+C((1-R("az","AZ","09","%%"))^0)
-local format_s=function(f)
- n=n+1
- if f and f~="" then
- return format("format('%%%ss',a%s)",f,n)
- else
- return format("(a%s or '')",n)
- end
-end
-local format_S=function(f)
- n=n+1
- if f and f~="" then
- return format("format('%%%ss',tostring(a%s))",f,n)
- else
- return format("tostring(a%s)",n)
- end
-end
-local format_right=function(f)
- n=n+1
- f=tonumber(f)
- if not f or f==0 then
- return format("(a%s or '')",n)
- elseif f>0 then
- return format("utfpadding(a%s,%i)..a%s",n,f,n)
- else
- return format("a%s..utfpadding(a%s,%i)",n,n,f)
- end
-end
-local format_left=function(f)
- n=n+1
- f=tonumber(f)
- if not f or f==0 then
- return format("(a%s or '')",n)
- end
- if f<0 then
- return format("utfpadding(a%s,%i)..a%s",n,-f,n)
- else
- return format("a%s..utfpadding(a%s,%i)",n,n,-f)
- end
-end
-local format_q=JITSUPPORTED and function()
- n=n+1
- return format("(a%s ~= nil and format('%%q',tostring(a%s)) or '')",n,n)
-end or function()
- n=n+1
- return format("(a%s ~= nil and format('%%q',a%s) or '')",n,n)
-end
-local format_Q=function()
- n=n+1
- return format("escapedquotes(tostring(a%s))",n)
-end
-local format_i=function(f)
- n=n+1
- if f and f~="" then
- return format("format('%%%si',a%s)",f,n)
- else
- return format("format('%%i',a%s)",n)
- end
-end
-local format_d=format_i
-local format_I=function(f)
- n=n+1
- return format("format('%%s%%%si',signed(a%s))",f,n)
-end
-local format_f=function(f)
- n=n+1
- return format("format('%%%sf',a%s)",f,n)
-end
-local format_F=function(f)
- n=n+1
- if not f or f=="" then
- return format("(((a%s > -0.0000000005 and a%s < 0.0000000005) and '0') or format((a%s %% 1 == 0) and '%%i' or '%%.9f',a%s))",n,n,n,n)
- else
- return format("format((a%s %% 1 == 0) and '%%i' or '%%%sf',a%s)",n,f,n)
- end
-end
-local format_k=function(b,a)
- n=n+1
- return format("formattedfloat(a%s,%s,%s)",n,b or 0,a or 0)
-end
-local format_g=function(f)
- n=n+1
- return format("format('%%%sg',a%s)",f,n)
-end
-local format_G=function(f)
- n=n+1
- return format("format('%%%sG',a%s)",f,n)
-end
-local format_e=function(f)
- n=n+1
- return format("format('%%%se',a%s)",f,n)
-end
-local format_E=function(f)
- n=n+1
- return format("format('%%%sE',a%s)",f,n)
-end
-local format_j=function(f)
- n=n+1
- return format("sparseexponent('%%%se',a%s)",f,n)
-end
-local format_J=function(f)
- n=n+1
- return format("sparseexponent('%%%sE',a%s)",f,n)
-end
-local format_x=function(f)
- n=n+1
- return format("format('%%%sx',a%s)",f,n)
-end
-local format_X=function(f)
- n=n+1
- return format("format('%%%sX',a%s)",f,n)
-end
-local format_o=function(f)
- n=n+1
- return format("format('%%%so',a%s)",f,n)
-end
-local format_c=function()
- n=n+1
- return format("utfchar(a%s)",n)
-end
-local format_C=function()
- n=n+1
- return format("tracedchar(a%s)",n)
-end
-local format_r=function(f)
- n=n+1
- return format("format('%%%s.0f',a%s)",f,n)
-end
-local format_h=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('0x%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_H=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('0x%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_u=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('u+%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_U=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('U+%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_p=function()
- n=n+1
- return format("points(a%s)",n)
-end
-local format_P=function()
- n=n+1
- return format("nupoints(a%s)",n)
-end
-local format_b=function()
- n=n+1
- return format("basepoints(a%s)",n)
-end
-local format_B=function()
- n=n+1
- return format("nubasepoints(a%s)",n)
-end
-local format_t=function(f)
- n=n+1
- if f and f~="" then
- return format("concat(a%s,%q)",n,f)
- else
- return format("concat(a%s)",n)
- end
-end
-local format_T=function(f)
- n=n+1
- if f and f~="" then
- return format("sequenced(a%s,%q)",n,f)
- else
- return format("sequenced(a%s)",n)
- end
-end
-local format_l=function()
- n=n+1
- return format("(a%s and 'true' or 'false')",n)
-end
-local format_L=function()
- n=n+1
- return format("(a%s and 'TRUE' or 'FALSE')",n)
-end
-local format_n=function()
- n=n+1
- return format("((a%s %% 1 == 0) and format('%%i',a%s) or tostring(a%s))",n,n,n)
-end
-local format_N if environment.FORMAT then
- format_N=function(f)
- n=n+1
- if not f or f=="" then
- return format("FORMAT(a%s,'%%.9f')",n)
- elseif f==".6" or f=="0.6" then
- return format("FORMAT(a%s)",n)
- else
- return format("FORMAT(a%s,'%%%sf')",n,f)
- end
- end
-else
- format_N=function(f)
- n=n+1
- if not f or f=="" then
- f=".9"
- end
- return format("(((a%s %% 1 == 0) and format('%%i',a%s)) or lpegmatch(stripzero,format('%%%sf',a%s)))",n,n,f,n)
- end
-end
-local format_a=function(f)
- n=n+1
- if f and f~="" then
- return format("autosingle(a%s,%q)",n,f)
- else
- return format("autosingle(a%s)",n)
- end
-end
-local format_A=function(f)
- n=n+1
- if f and f~="" then
- return format("autodouble(a%s,%q)",n,f)
- else
- return format("autodouble(a%s)",n)
- end
-end
-local format_w=function(f)
- n=n+1
- f=tonumber(f)
- if f then
- return format("nspaces[%s+a%s]",f,n)
- else
- return format("nspaces[a%s]",n)
- end
-end
-local format_W=function(f)
- return format("nspaces[%s]",tonumber(f) or 0)
-end
-local format_m=function(f)
- n=n+1
- if not f or f=="" then
- f=","
- end
- if f=="0" then
- return format([[formattednumber(a%s,false)]],n)
- else
- return format([[formattednumber(a%s,%q,".")]],n,f)
- end
-end
-local format_M=function(f)
- n=n+1
- if not f or f=="" then
- f="."
- end
- if f=="0" then
- return format([[formattednumber(a%s,false)]],n)
- else
- return format([[formattednumber(a%s,%q,",")]],n,f)
- end
-end
-local format_z=function(f)
- n=n+(tonumber(f) or 1)
- return "''"
-end
-local format_rest=function(s)
- return format("%q",s)
-end
-local format_extension=function(extensions,f,name)
- local extension=extensions[name] or "tostring(%s)"
- local f=tonumber(f) or 1
- local w=find(extension,"%.%.%.")
- if f==0 then
- if w then
- extension=gsub(extension,"%.%.%.","")
- end
- return extension
- elseif f==1 then
- if w then
- extension=gsub(extension,"%.%.%.","%%s")
- end
- n=n+1
- local a="a"..n
- return format(extension,a,a)
- elseif f<0 then
- if w then
- extension=gsub(extension,"%.%.%.","")
- return extension
- else
- local a="a"..(n+f+1)
- return format(extension,a,a)
- end
- else
- if w then
- extension=gsub(extension,"%.%.%.",rep("%%s,",f-1).."%%s")
- end
- local t={}
- for i=1,f do
- n=n+1
- t[i]="a"..n
- end
- return format(extension,unpack(t))
- end
-end
-local builder=Cs { "start",
- start=(
- (
- P("%")/""*(
- V("!")
-+V("s")+V("q")+V("i")+V("d")+V("f")+V("F")+V("g")+V("G")+V("e")+V("E")+V("x")+V("X")+V("o")
-+V("c")+V("C")+V("S")
-+V("Q")
-+V("n")
-+V("N")
-+V("k")
-+V("r")+V("h")+V("H")+V("u")+V("U")+V("p")+V("P")+V("b")+V("B")+V("t")+V("T")+V("l")+V("L")+V("I")+V("w")
-+V("W")
-+V("a")
-+V("A")
-+V("j")+V("J")
-+V("m")+V("M")
-+V("z")
-+V(">")
-+V("<")
- )+V("*")
- )*(endofstring+Carg(1))
- )^0,
- ["s"]=(prefix_any*P("s"))/format_s,
- ["q"]=(prefix_any*P("q"))/format_q,
- ["i"]=(prefix_any*P("i"))/format_i,
- ["d"]=(prefix_any*P("d"))/format_d,
- ["f"]=(prefix_any*P("f"))/format_f,
- ["F"]=(prefix_any*P("F"))/format_F,
- ["g"]=(prefix_any*P("g"))/format_g,
- ["G"]=(prefix_any*P("G"))/format_G,
- ["e"]=(prefix_any*P("e"))/format_e,
- ["E"]=(prefix_any*P("E"))/format_E,
- ["x"]=(prefix_any*P("x"))/format_x,
- ["X"]=(prefix_any*P("X"))/format_X,
- ["o"]=(prefix_any*P("o"))/format_o,
- ["S"]=(prefix_any*P("S"))/format_S,
- ["Q"]=(prefix_any*P("Q"))/format_Q,
- ["n"]=(prefix_any*P("n"))/format_n,
- ["N"]=(prefix_any*P("N"))/format_N,
- ["k"]=(prefix_sub*P("k"))/format_k,
- ["c"]=(prefix_any*P("c"))/format_c,
- ["C"]=(prefix_any*P("C"))/format_C,
- ["r"]=(prefix_any*P("r"))/format_r,
- ["h"]=(prefix_any*P("h"))/format_h,
- ["H"]=(prefix_any*P("H"))/format_H,
- ["u"]=(prefix_any*P("u"))/format_u,
- ["U"]=(prefix_any*P("U"))/format_U,
- ["p"]=(prefix_any*P("p"))/format_p,
- ["P"]=(prefix_any*P("P"))/format_P,
- ["b"]=(prefix_any*P("b"))/format_b,
- ["B"]=(prefix_any*P("B"))/format_B,
- ["t"]=(prefix_tab*P("t"))/format_t,
- ["T"]=(prefix_tab*P("T"))/format_T,
- ["l"]=(prefix_any*P("l"))/format_l,
- ["L"]=(prefix_any*P("L"))/format_L,
- ["I"]=(prefix_any*P("I"))/format_I,
- ["w"]=(prefix_any*P("w"))/format_w,
- ["W"]=(prefix_any*P("W"))/format_W,
- ["j"]=(prefix_any*P("j"))/format_j,
- ["J"]=(prefix_any*P("J"))/format_J,
- ["m"]=(prefix_any*P("m"))/format_m,
- ["M"]=(prefix_any*P("M"))/format_M,
- ["z"]=(prefix_any*P("z"))/format_z,
- ["a"]=(prefix_any*P("a"))/format_a,
- ["A"]=(prefix_any*P("A"))/format_A,
- ["<"]=(prefix_any*P("<"))/format_left,
- [">"]=(prefix_any*P(">"))/format_right,
- ["*"]=Cs(((1-P("%"))^1+P("%%")/"%%")^1)/format_rest,
- ["?"]=Cs(((1-P("%"))^1 )^1)/format_rest,
- ["!"]=Carg(2)*prefix_any*P("!")*C((1-P("!"))^1)*P("!")/format_extension,
-}
-local xx=setmetatable({},{ __index=function(t,k) local v=format("%02x",k) t[k]=v return v end })
-local XX=setmetatable({},{ __index=function(t,k) local v=format("%02X",k) t[k]=v return v end })
-local preset={
- ["%02x"]=function(n) return xx[n] end,
- ["%02X"]=function(n) return XX[n] end,
-}
-local direct=P("%")*(sign+space+period+digit)^0*S("sqidfgGeExXo")*endofstring/[[local format = string.format return function(str) return format("%0",str) end]]
-local function make(t,str)
- local f=preset[str]
- if f then
- return f
- end
- local p=lpegmatch(direct,str)
- if p then
- f=loadstripped(p)()
- else
- n=0
- p=lpegmatch(builder,str,1,t._connector_,t._extensions_)
- if n>0 then
- p=format(template,preamble,t._preamble_,arguments[n],p)
- f=loadstripped(p,t._environment_)()
- else
- f=function() return str end
- end
- end
- t[str]=f
- return f
-end
-local function use(t,fmt,...)
- return t[fmt](...)
-end
-strings.formatters={}
-function strings.formatters.new(noconcat)
- local e={}
- for k,v in next,environment do
- e[k]=v
- end
- local t={
- _type_="formatter",
- _connector_=noconcat and "," or "..",
- _extensions_={},
- _preamble_="",
- _environment_=e,
- }
- setmetatable(t,{ __index=make,__call=use })
- return t
-end
-local formatters=strings.formatters.new()
-string.formatters=formatters
-string.formatter=function(str,...) return formatters[str](...) end
-local function add(t,name,template,preamble)
- if type(t)=="table" and t._type_=="formatter" then
- t._extensions_[name]=template or "%s"
- if type(preamble)=="string" then
- t._preamble_=preamble.."\n"..t._preamble_
- elseif type(preamble)=="table" then
- for k,v in next,preamble do
- t._environment_[k]=v
- end
- end
- end
-end
-strings.formatters.add=add
-patterns.xmlescape=Cs((P("<")/"&lt;"+P(">")/"&gt;"+P("&")/"&amp;"+P('"')/"&quot;"+anything)^0)
-patterns.texescape=Cs((C(S("#$%\\{}"))/"\\%1"+anything)^0)
-patterns.luaescape=Cs(((1-S('"\n'))^1+P('"')/'\\"'+P('\n')/'\\n"')^0)
-patterns.luaquoted=Cs(Cc('"')*((1-S('"\n'))^1+P('"')/'\\"'+P('\n')/'\\n"')^0*Cc('"'))
-add(formatters,"xml",[[lpegmatch(xmlescape,%s)]],{ xmlescape=patterns.xmlescape })
-add(formatters,"tex",[[lpegmatch(texescape,%s)]],{ texescape=patterns.texescape })
-add(formatters,"lua",[[lpegmatch(luaescape,%s)]],{ luaescape=patterns.luaescape })
-local dquote=patterns.dquote
-local equote=patterns.escaped+dquote/'\\"'+1
-local cquote=Cc('"')
-local pattern=Cs(dquote*(equote-P(-2))^0*dquote)
-+Cs(cquote*(equote-space)^0*space*equote^0*cquote)
-function string.optionalquoted(str)
- return lpegmatch(pattern,str) or str
-end
-local pattern=Cs((newline/(os.newline or "\r")+1)^0)
-function string.replacenewlines(str)
- return lpegmatch(pattern,str)
-end
-function strings.newcollector()
- local result,r={},0
- return
- function(fmt,str,...)
- r=r+1
- result[r]=str==nil and fmt or formatters[fmt](str,...)
- end,
- function(connector)
- if result then
- local str=concat(result,connector)
- result,r={},0
- return str
- end
- end
-end
-local f_16_16=formatters["%0.5N"]
-function number.to16dot16(n)
- return f_16_16(n/65536.0)
-end
-if not string.explode then
- local tsplitat=lpeg.tsplitat
- local p_utf=patterns.utf8character
- local p_check=C(p_utf)*(P("+")*Cc(true))^0
- local p_split=Ct(C(p_utf)^0)
- local p_space=Ct((C(1-P(" ")^1)+P(" ")^1)^0)
- function string.explode(str,symbol)
- if symbol=="" then
- return lpegmatch(p_split,str)
- elseif symbol then
- local a,b=lpegmatch(p_check,symbol)
- if b then
- return lpegmatch(tsplitat(P(a)^1),str)
- else
- return lpegmatch(tsplitat(a),str)
- end
- else
- return lpegmatch(p_space,str)
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-tab"] = package.loaded["util-tab"] or true
-
--- original size: 32815, stripped down to: 18257
-
-if not modules then modules={} end modules ['util-tab']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities=utilities or {}
-utilities.tables=utilities.tables or {}
-local tables=utilities.tables
-local format,gmatch,gsub,sub=string.format,string.gmatch,string.gsub,string.sub
-local concat,insert,remove,sort=table.concat,table.insert,table.remove,table.sort
-local setmetatable,getmetatable,tonumber,tostring,rawget=setmetatable,getmetatable,tonumber,tostring,rawget
-local type,next,rawset,tonumber,tostring,load,select=type,next,rawset,tonumber,tostring,load,select
-local lpegmatch,P,Cs,Cc=lpeg.match,lpeg.P,lpeg.Cs,lpeg.Cc
-local sortedkeys,sortedpairs=table.sortedkeys,table.sortedpairs
-local formatters=string.formatters
-local utftoeight=utf.toeight
-local splitter=lpeg.tsplitat(".")
-function utilities.tables.definetable(target,nofirst,nolast)
- local composed=nil
- local t={}
- local snippets=lpegmatch(splitter,target)
- for i=1,#snippets-(nolast and 1 or 0) do
- local name=snippets[i]
- if composed then
- composed=composed.."."..name
- t[#t+1]=formatters["if not %s then %s = { } end"](composed,composed)
- else
- composed=name
- if not nofirst then
- t[#t+1]=formatters["%s = %s or { }"](composed,composed)
- end
- end
- end
- if composed then
- if nolast then
- composed=composed.."."..snippets[#snippets]
- end
- return concat(t,"\n"),composed
- else
- return "",target
- end
-end
-function tables.definedtable(...)
- local t=_G
- for i=1,select("#",...) do
- local li=select(i,...)
- local tl=t[li]
- if not tl then
- tl={}
- t[li]=tl
- end
- t=tl
- end
- return t
-end
-function tables.accesstable(target,root)
- local t=root or _G
- for name in gmatch(target,"([^%.]+)") do
- t=t[name]
- if not t then
- return
- end
- end
- return t
-end
-function tables.migratetable(target,v,root)
- local t=root or _G
- local names=lpegmatch(splitter,target)
- for i=1,#names-1 do
- local name=names[i]
- t[name]=t[name] or {}
- t=t[name]
- if not t then
- return
- end
- end
- t[names[#names]]=v
-end
-function tables.removevalue(t,value)
- if value then
- for i=1,#t do
- if t[i]==value then
- remove(t,i)
- end
- end
- end
-end
-function tables.replacevalue(t,oldvalue,newvalue)
- if oldvalue and newvalue then
- for i=1,#t do
- if t[i]==oldvalue then
- t[i]=newvalue
- end
- end
- end
-end
-function tables.insertbeforevalue(t,value,extra)
- for i=1,#t do
- if t[i]==extra then
- remove(t,i)
- end
- end
- for i=1,#t do
- if t[i]==value then
- insert(t,i,extra)
- return
- end
- end
- insert(t,1,extra)
-end
-function tables.insertaftervalue(t,value,extra)
- for i=1,#t do
- if t[i]==extra then
- remove(t,i)
- end
- end
- for i=1,#t do
- if t[i]==value then
- insert(t,i+1,extra)
- return
- end
- end
- insert(t,#t+1,extra)
-end
-local escape=Cs(Cc('"')*((P('"')/'""'+P(1))^0)*Cc('"'))
-function table.tocsv(t,specification)
- if t and #t>0 then
- local result={}
- local r={}
- specification=specification or {}
- local fields=specification.fields
- if type(fields)~="string" then
- fields=sortedkeys(t[1])
- end
- local separator=specification.separator or ","
- local noffields=#fields
- if specification.preamble==true then
- for f=1,noffields do
- r[f]=lpegmatch(escape,tostring(fields[f]))
- end
- result[1]=concat(r,separator)
- end
- for i=1,#t do
- local ti=t[i]
- for f=1,noffields do
- local field=ti[fields[f]]
- if type(field)=="string" then
- r[f]=lpegmatch(escape,field)
- else
- r[f]=tostring(field)
- end
- end
- result[i+1]=concat(r,separator)
- end
- return concat(result,"\n")
- else
- return ""
- end
-end
-local nspaces=utilities.strings.newrepeater(" ")
-local function toxml(t,d,result,step)
- local r=#result
- for k,v in sortedpairs(t) do
- local s=nspaces[d]
- local tk=type(k)
- local tv=type(v)
- if tv=="table" then
- if tk=="number" then
- r=r+1 result[r]=formatters["%s<entry n='%s'>"](s,k)
- toxml(v,d+step,result,step)
- r=r+1 result[r]=formatters["%s</entry>"](s,k)
- else
- r=r+1 result[r]=formatters["%s<%s>"](s,k)
- toxml(v,d+step,result,step)
- r=r+1 result[r]=formatters["%s</%s>"](s,k)
- end
- elseif tv=="string" then
- if tk=="number" then
- r=r+1 result[r]=formatters["%s<entry n='%s'>%!xml!</entry>"](s,k,v,k)
- else
- r=r+1 result[r]=formatters["%s<%s>%!xml!</%s>"](s,k,v,k)
- end
- elseif tk=="number" then
- r=r+1 result[r]=formatters["%s<entry n='%s'>%S</entry>"](s,k,v,k)
- else
- r=r+1 result[r]=formatters["%s<%s>%S</%s>"](s,k,v,k)
- end
- end
-end
-function table.toxml(t,specification)
- specification=specification or {}
- local name=specification.name
- local noroot=name==false
- local result=(specification.nobanner or noroot) and {} or { "<?xml version='1.0' standalone='yes' ?>" }
- local indent=specification.indent or 0
- local spaces=specification.spaces or 1
- if noroot then
- toxml(t,indent,result,spaces)
- else
- toxml({ [name or "data"]=t },indent,result,spaces)
- end
- return concat(result,"\n")
-end
-function tables.encapsulate(core,capsule,protect)
- if type(capsule)~="table" then
- protect=true
- capsule={}
- end
- for key,value in next,core do
- if capsule[key] then
- print(formatters["\ninvalid %s %a in %a"]("inheritance",key,core))
- os.exit()
- else
- capsule[key]=value
- end
- end
- if protect then
- for key,value in next,core do
- core[key]=nil
- end
- setmetatable(core,{
- __index=capsule,
- __newindex=function(t,key,value)
- if capsule[key] then
- print(formatters["\ninvalid %s %a' in %a"]("overload",key,core))
- os.exit()
- else
- rawset(t,key,value)
- end
- end
- } )
- end
-end
-if JITSUPPORTED then
- local f_hashed_string=formatters["[%Q]=%Q,"]
- local f_hashed_number=formatters["[%Q]=%s,"]
- local f_hashed_boolean=formatters["[%Q]=%l,"]
- local f_hashed_table=formatters["[%Q]="]
- local f_indexed_string=formatters["[%s]=%Q,"]
- local f_indexed_number=formatters["[%s]=%s,"]
- local f_indexed_boolean=formatters["[%s]=%l,"]
- local f_indexed_table=formatters["[%s]="]
- local f_ordered_string=formatters["%Q,"]
- local f_ordered_number=formatters["%s,"]
- local f_ordered_boolean=formatters["%l,"]
- function table.fastserialize(t,prefix)
- local r={ type(prefix)=="string" and prefix or "return" }
- local m=1
- local function fastserialize(t,outer)
- local n=#t
- m=m+1
- r[m]="{"
- if n>0 then
- local v=t[0]
- if v then
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_indexed_string(0,v)
- elseif tv=="number" then
- m=m+1 r[m]=f_indexed_number(0,v)
- elseif tv=="table" then
- m=m+1 r[m]=f_indexed_table(0)
- fastserialize(v)
- m=m+1 r[m]=f_indexed_table(0)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_indexed_boolean(0,v)
- end
- end
- for i=1,n do
- local v=t[i]
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_ordered_string(v)
- elseif tv=="number" then
- m=m+1 r[m]=f_ordered_number(v)
- elseif tv=="table" then
- fastserialize(v)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_ordered_boolean(v)
- end
- end
- end
- for k,v in next,t do
- local tk=type(k)
- if tk=="number" then
- if k>n or k<0 then
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_indexed_string(k,v)
- elseif tv=="number" then
- m=m+1 r[m]=f_indexed_number(k,v)
- elseif tv=="table" then
- m=m+1 r[m]=f_indexed_table(k)
- fastserialize(v)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_indexed_boolean(k,v)
- end
- end
- else
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_hashed_string(k,v)
- elseif tv=="number" then
- m=m+1 r[m]=f_hashed_number(k,v)
- elseif tv=="table" then
- m=m+1 r[m]=f_hashed_table(k)
- fastserialize(v)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_hashed_boolean(k,v)
- end
- end
- end
- m=m+1
- if outer then
- r[m]="}"
- else
- r[m]="},"
- end
- return r
- end
- return concat(fastserialize(t,true))
- end
-else
- local f_v=formatters["[%q]=%q,"]
- local f_t=formatters["[%q]="]
- local f_q=formatters["%q,"]
- function table.fastserialize(t,prefix)
- local r={ type(prefix)=="string" and prefix or "return" }
- local m=1
- local function fastserialize(t,outer)
- local n=#t
- m=m+1
- r[m]="{"
- if n>0 then
- local v=t[0]
- if v then
- m=m+1
- r[m]="[0]='"
- if type(v)=="table" then
- fastserialize(v)
- else
- r[m]=format("%q,",v)
- end
- end
- for i=1,n do
- local v=t[i]
- m=m+1
- if type(v)=="table" then
- r[m]=format("[%i]=",i)
- fastserialize(v)
- else
- r[m]=format("[%i]=%q,",i,v)
- end
- end
- end
- for k,v in next,t do
- local tk=type(k)
- if tk=="number" then
- if k>n or k<0 then
- m=m+1
- if type(v)=="table" then
- r[m]=format("[%i]=",k)
- fastserialize(v)
- else
- r[m]=format("[%i]=%q,",k,v)
- end
- end
- else
- m=m+1
- if type(v)=="table" then
- r[m]=format("[%q]=",k)
- fastserialize(v)
- else
- r[m]=format("[%q]=%q,",k,v)
- end
- end
- end
- m=m+1
- if outer then
- r[m]="}"
- else
- r[m]="},"
- end
- return r
- end
- return concat(fastserialize(t,true))
- end
-end
-function table.deserialize(str)
- if not str or str=="" then
- return
- end
- local code=load(str)
- if not code then
- return
- end
- code=code()
- if not code then
- return
- end
- return code
-end
-function table.load(filename,loader)
- if filename then
- local t=(loader or io.loaddata)(filename)
- if t and t~="" then
- local t=utftoeight(t)
- t=load(t)
- if type(t)=="function" then
- t=t()
- if type(t)=="table" then
- return t
- end
- end
- end
- end
-end
-function table.save(filename,t,n,...)
- io.savedata(filename,table.serialize(t,n==nil and true or n,...))
-end
-local f_key_value=formatters["%s=%q"]
-local f_add_table=formatters[" {%t},\n"]
-local f_return_table=formatters["return {\n%t}"]
-local function slowdrop(t)
- local r={}
- local l={}
- for i=1,#t do
- local ti=t[i]
- local j=0
- for k,v in next,ti do
- j=j+1
- l[j]=f_key_value(k,v)
- end
- r[i]=f_add_table(l)
- end
- return f_return_table(r)
-end
-local function fastdrop(t)
- local r={ "return {\n" }
- local m=1
- for i=1,#t do
- local ti=t[i]
- m=m+1 r[m]=" {"
- for k,v in next,ti do
- m=m+1 r[m]=f_key_value(k,v)
- end
- m=m+1 r[m]="},\n"
- end
- m=m+1
- r[m]="}"
- return concat(r)
-end
-function table.drop(t,slow)
- if #t==0 then
- return "return { }"
- elseif slow==true then
- return slowdrop(t)
- else
- return fastdrop(t)
- end
-end
-local selfmapper={ __index=function(t,k) t[k]=k return k end }
-function table.twowaymapper(t)
- if not t then
- t={}
- else
- local zero=rawget(t,0)
- for i=zero and 0 or 1,#t do
- local ti=t[i]
- if ti then
- local i=tostring(i)
- t[i]=ti
- t[ti]=i
- end
- end
- end
- setmetatable(t,selfmapper)
- return t
-end
-local f_start_key_idx=formatters["%w{"]
-local f_start_key_num=JITSUPPORTED and formatters["%w[%s]={"] or formatters["%w[%q]={"]
-local f_start_key_str=formatters["%w[%q]={"]
-local f_start_key_boo=formatters["%w[%l]={"]
-local f_start_key_nop=formatters["%w{"]
-local f_stop=formatters["%w},"]
-local f_key_num_value_num=JITSUPPORTED and formatters["%w[%s]=%s,"] or formatters["%w[%s]=%q,"]
-local f_key_str_value_num=JITSUPPORTED and formatters["%w[%Q]=%s,"] or formatters["%w[%Q]=%q,"]
-local f_key_boo_value_num=JITSUPPORTED and formatters["%w[%l]=%s,"] or formatters["%w[%l]=%q,"]
-local f_key_num_value_str=JITSUPPORTED and formatters["%w[%s]=%Q,"] or formatters["%w[%q]=%Q,"]
-local f_key_str_value_str=formatters["%w[%Q]=%Q,"]
-local f_key_boo_value_str=formatters["%w[%l]=%Q,"]
-local f_key_num_value_boo=JITSUPPORTED and formatters["%w[%s]=%l,"] or formatters["%w[%q]=%l,"]
-local f_key_str_value_boo=formatters["%w[%Q]=%l,"]
-local f_key_boo_value_boo=formatters["%w[%l]=%l,"]
-local f_key_num_value_not=JITSUPPORTED and formatters["%w[%s]={},"] or formatters["%w[%q]={},"]
-local f_key_str_value_not=formatters["%w[%Q]={},"]
-local f_key_boo_value_not=formatters["%w[%l]={},"]
-local f_key_num_value_seq=JITSUPPORTED and formatters["%w[%s]={ %, t },"] or formatters["%w[%q]={ %, t },"]
-local f_key_str_value_seq=formatters["%w[%Q]={ %, t },"]
-local f_key_boo_value_seq=formatters["%w[%l]={ %, t },"]
-local f_val_num=JITSUPPORTED and formatters["%w%s,"] or formatters["%w%q,"]
-local f_val_str=formatters["%w%Q,"]
-local f_val_boo=formatters["%w%l,"]
-local f_val_not=formatters["%w{},"]
-local f_val_seq=formatters["%w{ %, t },"]
-local f_fin_seq=formatters[" %, t }"]
-local f_table_return=formatters["return {"]
-local f_table_name=formatters["%s={"]
-local f_table_direct=formatters["{"]
-local f_table_entry=formatters["[%Q]={"]
-local f_table_finish=formatters["}"]
-local spaces=utilities.strings.newrepeater(" ")
-local original_serialize=table.serialize
-local is_simple_table=table.is_simple_table
-local function serialize(root,name,specification)
- if type(specification)=="table" then
- return original_serialize(root,name,specification)
- end
- local t
- local n=1
- local unknown=false
- local function do_serialize(root,name,depth,level,indexed)
- if level>0 then
- n=n+1
- if indexed then
- t[n]=f_start_key_idx(depth)
- else
- local tn=type(name)
- if tn=="number" then
- t[n]=f_start_key_num(depth,name)
- elseif tn=="string" then
- t[n]=f_start_key_str(depth,name)
- elseif tn=="boolean" then
- t[n]=f_start_key_boo(depth,name)
- else
- t[n]=f_start_key_nop(depth)
- end
- end
- depth=depth+1
- end
- if root and next(root)~=nil then
- local first=nil
- local last=#root
- if last>0 then
- for k=1,last do
- if rawget(root,k)==nil then
- last=k-1
- break
- end
- end
- if last>0 then
- first=1
- end
- end
- local sk=sortedkeys(root)
- for i=1,#sk do
- local k=sk[i]
- local v=root[k]
- local tv=type(v)
- local tk=type(k)
- if first and tk=="number" and k<=last and k>=first then
- if tv=="number" then
- n=n+1 t[n]=f_val_num(depth,v)
- elseif tv=="string" then
- n=n+1 t[n]=f_val_str(depth,v)
- elseif tv=="table" then
- if next(v)==nil then
- n=n+1 t[n]=f_val_not(depth)
- else
- local st=is_simple_table(v)
- if st then
- n=n+1 t[n]=f_val_seq(depth,st)
- else
- do_serialize(v,k,depth,level+1,true)
- end
- end
- elseif tv=="boolean" then
- n=n+1 t[n]=f_val_boo(depth,v)
- elseif unknown then
- n=n+1 t[n]=f_val_str(depth,tostring(v))
- end
- elseif tv=="number" then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_num(depth,k,v)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_num(depth,k,v)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_num(depth,k,v)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_num(depth,tostring(k),v)
- end
- elseif tv=="string" then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_str(depth,k,v)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_str(depth,k,v)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_str(depth,k,v)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_str(depth,tostring(k),v)
- end
- elseif tv=="table" then
- if next(v)==nil then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_not(depth,k)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_not(depth,k)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_not(depth,k)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_not(depth,tostring(k))
- end
- else
- local st=is_simple_table(v)
- if not st then
- do_serialize(v,k,depth,level+1)
- elseif tk=="number" then
- n=n+1 t[n]=f_key_num_value_seq(depth,k,st)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_seq(depth,k,st)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_seq(depth,k,st)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_seq(depth,tostring(k),st)
- end
- end
- elseif tv=="boolean" then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_boo(depth,k,v)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_boo(depth,k,v)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_boo(depth,k,v)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_boo(depth,tostring(k),v)
- end
- else
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_str(depth,k,tostring(v))
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_str(depth,k,tostring(v))
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_str(depth,k,tostring(v))
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_str(depth,tostring(k),tostring(v))
- end
- end
- end
- end
- if level>0 then
- n=n+1 t[n]=f_stop(depth-1)
- end
- end
- local tname=type(name)
- if tname=="string" then
- if name=="return" then
- t={ f_table_return() }
- else
- t={ f_table_name(name) }
- end
- elseif tname=="number" then
- t={ f_table_entry(name) }
- elseif tname=="boolean" then
- if name then
- t={ f_table_return() }
- else
- t={ f_table_direct() }
- end
- else
- t={ f_table_name("t") }
- end
- if root then
- if getmetatable(root) then
- local dummy=root._w_h_a_t_e_v_e_r_
- root._w_h_a_t_e_v_e_r_=nil
- end
- if next(root)~=nil then
- local st=is_simple_table(root)
- if st then
- return t[1]..f_fin_seq(st)
- else
- do_serialize(root,name,1,0)
- end
- end
- end
- n=n+1
- t[n]=f_table_finish()
- return concat(t,"\n")
-end
-table.serialize=serialize
-if setinspector then
- setinspector("table",function(v)
- if type(v)=="table" then
- print(serialize(v,"table",{ metacheck=false }))
- return true
- end
- end)
-end
-local mt={
- __newindex=function(t,k,v)
- local n=t.last+1
- t.last=n
- t.list[n]=k
- t.hash[k]=v
- end,
- __index=function(t,k)
- return t.hash[k]
- end,
- __len=function(t)
- return t.last
- end,
-}
-function table.orderedhash()
- return setmetatable({ list={},hash={},last=0 },mt)
-end
-function table.ordered(t)
- local n=t.last
- if n>0 then
- local l=t.list
- local i=1
- local h=t.hash
- local f=function()
- if i<=n then
- local k=i
- local v=h[l[k]]
- i=i+1
- return k,v
- end
- end
- return f,1,h[l[1]]
- else
- return function() end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-fil"] = package.loaded["util-fil"] or true
-
--- original size: 11552, stripped down to: 9023
-
-if not modules then modules={} end modules ['util-fil']={
- version=1.001,
- optimize=true,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local tonumber=tonumber
-local byte=string.byte
-local char=string.char
-utilities=utilities or {}
-local files={}
-utilities.files=files
-local zerobased={}
-function files.open(filename,zb)
- local f=io.open(filename,"rb")
- if f then
- zerobased[f]=zb or false
- end
- return f
-end
-function files.close(f)
- zerobased[f]=nil
- f:close()
-end
-function files.size(f)
- local current=f:seek()
- local size=f:seek("end")
- f:seek("set",current)
- return size
-end
-files.getsize=files.size
-function files.setposition(f,n)
- if zerobased[f] then
- f:seek("set",n)
- else
- f:seek("set",n-1)
- end
-end
-function files.getposition(f)
- if zerobased[f] then
- return f:seek()
- else
- return f:seek()+1
- end
-end
-function files.look(f,n,chars)
- local p=f:seek()
- local s=f:read(n)
- f:seek("set",p)
- if chars then
- return s
- else
- return byte(s,1,#s)
- end
-end
-function files.skip(f,n)
- if n==1 then
- f:read(n)
- else
- f:seek("set",f:seek()+n)
- end
-end
-function files.readbyte(f)
- return byte(f:read(1))
-end
-function files.readbytes(f,n)
- return byte(f:read(n),1,n)
-end
-function files.readbytetable(f,n)
- local s=f:read(n or 1)
- return { byte(s,1,#s) }
-end
-function files.readchar(f)
- return f:read(1)
-end
-function files.readstring(f,n)
- return f:read(n or 1)
-end
-function files.readinteger1(f)
- local n=byte(f:read(1))
- if n>=0x80 then
- return n-0x100
- else
- return n
- end
-end
-files.readcardinal1=files.readbyte
-files.readcardinal=files.readcardinal1
-files.readinteger=files.readinteger1
-files.readsignedbyte=files.readinteger1
-function files.readcardinal2(f)
- local a,b=byte(f:read(2),1,2)
- return 0x100*a+b
-end
-function files.readcardinal2le(f)
- local b,a=byte(f:read(2),1,2)
- return 0x100*a+b
-end
-function files.readinteger2(f)
- local a,b=byte(f:read(2),1,2)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function files.readinteger2le(f)
- local b,a=byte(f:read(2),1,2)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function files.readcardinal3(f)
- local a,b,c=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
-end
-function files.readcardinal3le(f)
- local c,b,a=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
-end
-function files.readinteger3(f)
- local a,b,c=byte(f:read(3),1,3)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function files.readinteger3le(f)
- local c,b,a=byte(f:read(3),1,3)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function files.readcardinal4(f)
- local a,b,c,d=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function files.readcardinal4le(f)
- local d,c,b,a=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function files.readinteger4(f)
- local a,b,c,d=byte(f:read(4),1,4)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function files.readinteger4le(f)
- local d,c,b,a=byte(f:read(4),1,4)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function files.readfixed2(f)
- local a,b=byte(f:read(2),1,2)
- if a>=0x80 then
- tonumber((a-0x100).."."..b)
- else
- tonumber((a ).."."..b)
- end
-end
-function files.readfixed4(f)
- local a,b,c,d=byte(f:read(4),1,4)
- if a>=0x80 then
- tonumber((0x100*a+b-0x10000).."."..(0x100*c+d))
- else
- tonumber((0x100*a+b ).."."..(0x100*c+d))
- end
-end
-if bit32 then
- local extract=bit32.extract
- local band=bit32.band
- function files.read2dot14(f)
- local a,b=byte(f:read(2),1,2)
- if a>=0x80 then
- local n=-(0x100*a+b)
- return-(extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- else
- local n=0x100*a+b
- return (extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- end
- end
-end
-function files.skipshort(f,n)
- f:read(2*(n or 1))
-end
-function files.skiplong(f,n)
- f:read(4*(n or 1))
-end
-if bit32 then
- local rshift=bit32.rshift
- function files.writecardinal2(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- f:write(b,a)
- end
- function files.writecardinal4(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- n=rshift(n,8)
- local c=char(n%256)
- n=rshift(n,8)
- local d=char(n%256)
- f:write(d,c,b,a)
- end
- function files.writecardinal2le(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- f:write(a,b)
- end
- function files.writecardinal4le(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- n=rshift(n,8)
- local c=char(n%256)
- n=rshift(n,8)
- local d=char(n%256)
- f:write(a,b,c,d)
- end
-else
- local floor=math.floor
- function files.writecardinal2(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- f:write(b,a)
- end
- function files.writecardinal4(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- n=floor(n/256)
- local c=char(n%256)
- n=floor(n/256)
- local d=char(n%256)
- f:write(d,c,b,a)
- end
- function files.writecardinal2le(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- f:write(a,b)
- end
- function files.writecardinal4le(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- n=floor(n/256)
- local c=char(n%256)
- n=floor(n/256)
- local d=char(n%256)
- f:write(a,b,c,d)
- end
-end
-function files.writestring(f,s)
- f:write(char(byte(s,1,#s)))
-end
-function files.writebyte(f,b)
- f:write(char(b))
-end
-if fio and fio.readcardinal1 then
- files.readcardinal1=fio.readcardinal1
- files.readcardinal2=fio.readcardinal2
- files.readcardinal3=fio.readcardinal3
- files.readcardinal4=fio.readcardinal4
- files.readcardinal1le=fio.readcardinal1le or files.readcardinal1le
- files.readcardinal2le=fio.readcardinal2le or files.readcardinal2le
- files.readcardinal3le=fio.readcardinal3le or files.readcardinal3le
- files.readcardinal4le=fio.readcardinal4le or files.readcardinal4le
- files.readinteger1=fio.readinteger1
- files.readinteger2=fio.readinteger2
- files.readinteger3=fio.readinteger3
- files.readinteger4=fio.readinteger4
- files.readinteger1le=fio.readinteger1le or files.readinteger1le
- files.readinteger2le=fio.readinteger2le or files.readinteger2le
- files.readinteger3le=fio.readinteger3le or files.readinteger3le
- files.readinteger4le=fio.readinteger4le or files.readinteger4le
- files.readfixed2=fio.readfixed2
- files.readfixed4=fio.readfixed4
- files.read2dot14=fio.read2dot14
- files.setposition=fio.setposition
- files.getposition=fio.getposition
- files.readbyte=files.readcardinal1
- files.readsignedbyte=files.readinteger1
- files.readcardinal=files.readcardinal1
- files.readinteger=files.readinteger1
- local skipposition=fio.skipposition
- files.skipposition=skipposition
- files.readbytes=fio.readbytes
- files.readbytetable=fio.readbytetable
- function files.skipshort(f,n)
- skipposition(f,2*(n or 1))
- end
- function files.skiplong(f,n)
- skipposition(f,4*(n or 1))
- end
-end
-if fio and fio.writecardinal1 then
- files.writecardinal1=fio.writecardinal1
- files.writecardinal2=fio.writecardinal2
- files.writecardinal3=fio.writecardinal3
- files.writecardinal4=fio.writecardinal4
- files.writecardinal1le=fio.writecardinal1le
- files.writecardinal2le=fio.writecardinal2le
- files.writecardinal3le=fio.writecardinal3le
- files.writecardinal4le=fio.writecardinal4le
- files.writeinteger1=fio.writeinteger1 or fio.writecardinal1
- files.writeinteger2=fio.writeinteger2 or fio.writecardinal2
- files.writeinteger3=fio.writeinteger3 or fio.writecardinal3
- files.writeinteger4=fio.writeinteger4 or fio.writecardinal4
- files.writeinteger1le=files.writeinteger1le or fio.writecardinal1le
- files.writeinteger2le=files.writeinteger2le or fio.writecardinal2le
- files.writeinteger3le=files.writeinteger3le or fio.writecardinal3le
- files.writeinteger4le=files.writeinteger4le or fio.writecardinal4le
-end
-if fio and fio.readcardinaltable then
- files.readcardinaltable=fio.readcardinaltable
- files.readintegertable=fio.readintegertable
-else
- local readcardinal1=files.readcardinal1
- local readcardinal2=files.readcardinal2
- local readcardinal3=files.readcardinal3
- local readcardinal4=files.readcardinal4
- function files.readcardinaltable(f,n,b)
- local t={}
- if b==1 then for i=1,n do t[i]=readcardinal1(f) end
- elseif b==2 then for i=1,n do t[i]=readcardinal2(f) end
- elseif b==3 then for i=1,n do t[i]=readcardinal3(f) end
- elseif b==4 then for i=1,n do t[i]=readcardinal4(f) end end
- return t
- end
- local readinteger1=files.readinteger1
- local readinteger2=files.readinteger2
- local readinteger3=files.readinteger3
- local readinteger4=files.readinteger4
- function files.readintegertable(f,n,b)
- local t={}
- if b==1 then for i=1,n do t[i]=readinteger1(f) end
- elseif b==2 then for i=1,n do t[i]=readinteger2(f) end
- elseif b==3 then for i=1,n do t[i]=readinteger3(f) end
- elseif b==4 then for i=1,n do t[i]=readinteger4(f) end end
- return t
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-sac"] = package.loaded["util-sac"] or true
-
--- original size: 12968, stripped down to: 9523
-
-if not modules then modules={} end modules ['util-sac']={
- version=1.001,
- optimize=true,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local byte,sub=string.byte,string.sub
-local tonumber=tonumber
-utilities=utilities or {}
-local streams={}
-utilities.streams=streams
-function streams.open(filename,zerobased)
- local f=filename and io.loaddata(filename)
- if f then
- return { f,1,#f,zerobased or false }
- end
-end
-function streams.openstring(f,zerobased)
- if f then
- return { f,1,#f,zerobased or false }
- end
-end
-function streams.getstring(f)
- if f then
- return f[1]
- end
-end
-function streams.close()
-end
-function streams.size(f)
- return f and f[3] or 0
-end
-streams.getsize=streams.size
-function streams.setposition(f,i)
- if f[4] then
- if i<=0 then
- f[2]=1
- else
- f[2]=i+1
- end
- else
- if i<=1 then
- f[2]=1
- else
- f[2]=i
- end
- end
-end
-function streams.getposition(f)
- if f[4] then
- return f[2]-1
- else
- return f[2]
- end
-end
-function streams.look(f,n,chars)
- local b=f[2]
- local e=b+n-1
- if chars then
- return sub(f[1],b,e)
- else
- return byte(f[1],b,e)
- end
-end
-function streams.skip(f,n)
- f[2]=f[2]+n
-end
-function streams.readbyte(f)
- local i=f[2]
- f[2]=i+1
- return byte(f[1],i)
-end
-function streams.readbytes(f,n)
- local i=f[2]
- local j=i+n
- f[2]=j
- return byte(f[1],i,j-1)
-end
-function streams.readbytetable(f,n)
- local i=f[2]
- local j=i+n
- f[2]=j
- return { byte(f[1],i,j-1) }
-end
-function streams.skipbytes(f,n)
- f[2]=f[2]+n
-end
-function streams.readchar(f)
- local i=f[2]
- f[2]=i+1
- return sub(f[1],i,i)
-end
-function streams.readstring(f,n)
- local i=f[2]
- local j=i+n
- f[2]=j
- return sub(f[1],i,j-1)
-end
-function streams.readinteger1(f)
- local i=f[2]
- f[2]=i+1
- local n=byte(f[1],i)
- if n>=0x80 then
- return n-0x100
- else
- return n
- end
-end
-streams.readcardinal1=streams.readbyte
-streams.readcardinal=streams.readcardinal1
-streams.readinteger=streams.readinteger1
-function streams.readcardinal2(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- return 0x100*a+b
-end
-function streams.readcardinal2le(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local b,a=byte(f[1],i,j)
- return 0x100*a+b
-end
-function streams.readinteger2(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function streams.readinteger2le(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local b,a=byte(f[1],i,j)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function streams.readcardinal3(f)
- local i=f[2]
- local j=i+2
- f[2]=j+1
- local a,b,c=byte(f[1],i,j)
- return 0x10000*a+0x100*b+c
-end
-function streams.readcardinal3le(f)
- local i=f[2]
- local j=i+2
- f[2]=j+1
- local c,b,a=byte(f[1],i,j)
- return 0x10000*a+0x100*b+c
-end
-function streams.readinteger3(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c=byte(f[1],i,j)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function streams.readinteger3le(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local c,b,a=byte(f[1],i,j)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function streams.readcardinal4(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c,d=byte(f[1],i,j)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function streams.readcardinal4le(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local d,c,b,a=byte(f[1],i,j)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function streams.readinteger4(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c,d=byte(f[1],i,j)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function streams.readinteger4le(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local d,c,b,a=byte(f[1],i,j)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function streams.readfixed2(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- if a>=0x80 then
- return tonumber((a-0x100).."."..b) or 0
- else
- return tonumber((a ).."."..b) or 0
- end
-end
-function streams.readfixed4(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c,d=byte(f[1],i,j)
- if a>=0x80 then
- return tonumber((0x100*a+b-0x10000).."."..(0x100*c+d)) or 0
- else
- return tonumber((0x100*a+b ).."."..(0x100*c+d)) or 0
- end
-end
-if bit32 then
- local extract=bit32.extract
- local band=bit32.band
- function streams.read2dot14(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- if a>=0x80 then
- local n=-(0x100*a+b)
- return-(extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- else
- local n=0x100*a+b
- return (extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- end
- end
-end
-function streams.skipshort(f,n)
- f[2]=f[2]+2*(n or 1)
-end
-function streams.skiplong(f,n)
- f[2]=f[2]+4*(n or 1)
-end
-if sio and sio.readcardinal2 then
- local readcardinal1=sio.readcardinal1
- local readcardinal2=sio.readcardinal2
- local readcardinal3=sio.readcardinal3
- local readcardinal4=sio.readcardinal4
- local readinteger1=sio.readinteger1
- local readinteger2=sio.readinteger2
- local readinteger3=sio.readinteger3
- local readinteger4=sio.readinteger4
- local readfixed2=sio.readfixed2
- local readfixed4=sio.readfixed4
- local read2dot14=sio.read2dot14
- local readbytes=sio.readbytes
- local readbytetable=sio.readbytetable
- function streams.readcardinal1(f)
- local i=f[2]
- f[2]=i+1
- return readcardinal1(f[1],i)
- end
- function streams.readcardinal2(f)
- local i=f[2]
- f[2]=i+2
- return readcardinal2(f[1],i)
- end
- function streams.readcardinal3(f)
- local i=f[2]
- f[2]=i+3
- return readcardinal3(f[1],i)
- end
- function streams.readcardinal4(f)
- local i=f[2]
- f[2]=i+4
- return readcardinal4(f[1],i)
- end
- function streams.readinteger1(f)
- local i=f[2]
- f[2]=i+1
- return readinteger1(f[1],i)
- end
- function streams.readinteger2(f)
- local i=f[2]
- f[2]=i+2
- return readinteger2(f[1],i)
- end
- function streams.readinteger3(f)
- local i=f[2]
- f[2]=i+3
- return readinteger3(f[1],i)
- end
- function streams.readinteger4(f)
- local i=f[2]
- f[2]=i+4
- return readinteger4(f[1],i)
- end
- function streams.readfixed2(f)
- local i=f[2]
- f[2]=i+2
- return readfixed2(f[1],i)
- end
- function streams.readfixed4(f)
- local i=f[2]
- f[2]=i+4
- return readfixed4(f[1],i)
- end
- function streams.read2dot4(f)
- local i=f[2]
- f[2]=i+2
- return read2dot4(f[1],i)
- end
- function streams.readbytes(f,n)
- local i=f[2]
- local s=f[3]
- local p=i+n
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readbytes(f[1],i,n)
- end
- function streams.readbytetable(f,n)
- local i=f[2]
- local s=f[3]
- local p=i+n
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readbytetable(f[1],i,n)
- end
- streams.readbyte=streams.readcardinal1
- streams.readsignedbyte=streams.readinteger1
- streams.readcardinal=streams.readcardinal1
- streams.readinteger=streams.readinteger1
-end
-if sio and sio.readcardinaltable then
- local readcardinaltable=sio.readcardinaltable
- local readintegertable=sio.readintegertable
- function utilities.streams.readcardinaltable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readcardinaltable(f[1],i,n,b)
- end
- function utilities.streams.readintegertable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readintegertable(f[1],i,n,b)
- end
-else
- local readcardinal1=streams.readcardinal1
- local readcardinal2=streams.readcardinal2
- local readcardinal3=streams.readcardinal3
- local readcardinal4=streams.readcardinal4
- function streams.readcardinaltable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- local t={}
- if b==1 then for i=1,n do t[i]=readcardinal1(f[1],i) end
- elseif b==2 then for i=1,n do t[i]=readcardinal2(f[1],i) end
- elseif b==3 then for i=1,n do t[i]=readcardinal3(f[1],i) end
- elseif b==4 then for i=1,n do t[i]=readcardinal4(f[1],i) end end
- return t
- end
- local readinteger1=streams.readinteger1
- local readinteger2=streams.readinteger2
- local readinteger3=streams.readinteger3
- local readinteger4=streams.readinteger4
- function streams.readintegertable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- local t={}
- if b==1 then for i=1,n do t[i]=readinteger1(f[1],i) end
- elseif b==2 then for i=1,n do t[i]=readinteger2(f[1],i) end
- elseif b==3 then for i=1,n do t[i]=readinteger3(f[1],i) end
- elseif b==4 then for i=1,n do t[i]=readinteger4(f[1],i) end end
- return t
- end
-end
-do
- local files=utilities.files
- if files then
- local openfile=files.open
- local openstream=streams.open
- local openstring=streams.openstring
- local setmetatable=setmetatable
- function io.newreader(str,method)
- local f,m
- if method=="string" then
- f=openstring(str)
- m=streams
- elseif method=="stream" then
- f=openstream(str)
- m=streams
- else
- f=openfile(str,"rb")
- m=files
- end
- if f then
- local t={}
- setmetatable(t,{
- __index=function(t,k)
- local r=m[k]
- if k=="close" then
- if f then
- m.close(f)
- f=nil
- end
- return function() end
- elseif r then
- local v=function(_,a,b) return r(f,a,b) end
- t[k]=v
- return v
- else
- print("unknown key",k)
- end
- end
- } )
- return t
- end
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-sto"] = package.loaded["util-sto"] or true
-
--- original size: 6661, stripped down to: 3074
-
-if not modules then modules={} end modules ['util-sto']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local setmetatable,getmetatable,rawset,type=setmetatable,getmetatable,rawset,type
-utilities=utilities or {}
-utilities.storage=utilities.storage or {}
-local storage=utilities.storage
-function storage.mark(t)
- if not t then
- print("\nfatal error: storage cannot be marked\n")
- os.exit()
- return
- end
- local m=getmetatable(t)
- if not m then
- m={}
- setmetatable(t,m)
- end
- m.__storage__=true
- return t
-end
-function storage.allocate(t)
- t=t or {}
- local m=getmetatable(t)
- if not m then
- m={}
- setmetatable(t,m)
- end
- m.__storage__=true
- return t
-end
-function storage.marked(t)
- local m=getmetatable(t)
- return m and m.__storage__
-end
-function storage.checked(t)
- if not t then
- report("\nfatal error: storage has not been allocated\n")
- os.exit()
- return
- end
- return t
-end
-function storage.setinitializer(data,initialize)
- local m=getmetatable(data) or {}
- m.__index=function(data,k)
- m.__index=nil
- initialize()
- return data[k]
- end
- setmetatable(data,m)
-end
-local keyisvalue={ __index=function(t,k)
- t[k]=k
- return k
-end }
-function storage.sparse(t)
- t=t or {}
- setmetatable(t,keyisvalue)
- return t
-end
-local function f_empty () return "" end
-local function f_self (t,k) t[k]=k return k end
-local function f_table (t,k) local v={} t[k]=v return v end
-local function f_number(t,k) t[k]=0 return 0 end
-local function f_ignore() end
-local f_index={
- ["empty"]=f_empty,
- ["self"]=f_self,
- ["table"]=f_table,
- ["number"]=f_number,
-}
-function table.setmetatableindex(t,f)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- local i=f_index[f] or f
- if m then
- m.__index=i
- else
- setmetatable(t,{ __index=i })
- end
- return t
-end
-local f_index={
- ["ignore"]=f_ignore,
-}
-function table.setmetatablenewindex(t,f)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- local i=f_index[f] or f
- if m then
- m.__newindex=i
- else
- setmetatable(t,{ __newindex=i })
- end
- return t
-end
-function table.setmetatablecall(t,f)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- if m then
- m.__call=f
- else
- setmetatable(t,{ __call=f })
- end
- return t
-end
-function table.setmetatableindices(t,f,n,c)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- local i=f_index[f] or f
- if m then
- m.__index=i
- m.__newindex=n
- m.__call=c
- else
- setmetatable(t,{
- __index=i,
- __newindex=n,
- __call=c,
- })
- end
- return t
-end
-function table.setmetatablekey(t,key,value)
- local m=getmetatable(t)
- if not m then
- m={}
- setmetatable(t,m)
- end
- m[key]=value
- return t
-end
-function table.getmetatablekey(t,key,value)
- local m=getmetatable(t)
- return m and m[key]
-end
-function table.makeweak(t)
- if not t then
- t={}
- end
- local m=getmetatable(t)
- if m then
- m.__mode="v"
- else
- setmetatable(t,{ __mode="v" })
- end
- return t
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-prs"] = package.loaded["util-prs"] or true
-
--- original size: 24683, stripped down to: 16431
-
-if not modules then modules={} end modules ['util-prs']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local lpeg,table,string=lpeg,table,string
-local P,R,V,S,C,Ct,Cs,Carg,Cc,Cg,Cf,Cp=lpeg.P,lpeg.R,lpeg.V,lpeg.S,lpeg.C,lpeg.Ct,lpeg.Cs,lpeg.Carg,lpeg.Cc,lpeg.Cg,lpeg.Cf,lpeg.Cp
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local concat,gmatch,find=table.concat,string.gmatch,string.find
-local tonumber,tostring,type,next,rawset=tonumber,tostring,type,next,rawset
-local mod,div=math.mod,math.div
-utilities=utilities or {}
-local parsers=utilities.parsers or {}
-utilities.parsers=parsers
-local patterns=parsers.patterns or {}
-parsers.patterns=patterns
-local setmetatableindex=table.setmetatableindex
-local sortedhash=table.sortedhash
-local sortedkeys=table.sortedkeys
-local tohash=table.tohash
-local hashes={}
-parsers.hashes=hashes
-local digit=R("09")
-local space=P(' ')
-local equal=P("=")
-local colon=P(":")
-local comma=P(",")
-local lbrace=P("{")
-local rbrace=P("}")
-local lparent=P("(")
-local rparent=P(")")
-local lbracket=P("[")
-local rbracket=P("]")
-local period=S(".")
-local punctuation=S(".,:;")
-local spacer=lpegpatterns.spacer
-local whitespace=lpegpatterns.whitespace
-local newline=lpegpatterns.newline
-local anything=lpegpatterns.anything
-local endofstring=lpegpatterns.endofstring
-local nobrace=1-(lbrace+rbrace )
-local noparent=1-(lparent+rparent)
-local nobracket=1-(lbracket+rbracket)
-local escape,left,right=P("\\"),P('{'),P('}')
-lpegpatterns.balanced=P {
- [1]=((escape*(left+right))+(1-(left+right))+V(2))^0,
- [2]=left*V(1)*right
-}
-local nestedbraces=P { lbrace*(nobrace+V(1))^0*rbrace }
-local nestedparents=P { lparent*(noparent+V(1))^0*rparent }
-local nestedbrackets=P { lbracket*(nobracket+V(1))^0*rbracket }
-local spaces=space^0
-local argument=Cs((lbrace/"")*((nobrace+nestedbraces)^0)*(rbrace/""))
-local content=(1-endofstring)^0
-lpegpatterns.nestedbraces=nestedbraces
-lpegpatterns.nestedparents=nestedparents
-lpegpatterns.nested=nestedbraces
-lpegpatterns.argument=argument
-lpegpatterns.content=content
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+(1-comma))^0)
-local key=C((1-equal-comma)^1)
-local pattern_a=(space+comma)^0*(key*equal*value+key*C(""))
-local pattern_c=(space+comma)^0*(key*equal*value)
-local pattern_d=(space+comma)^0*(key*(equal+colon)*value+key*C(""))
-local key=C((1-space-equal-comma)^1)
-local pattern_b=spaces*comma^0*spaces*(key*((spaces*equal*spaces*value)+C("")))
-local hash={}
-local function set(key,value)
- hash[key]=value
-end
-local pattern_a_s=(pattern_a/set)^1
-local pattern_b_s=(pattern_b/set)^1
-local pattern_c_s=(pattern_c/set)^1
-local pattern_d_s=(pattern_d/set)^1
-patterns.settings_to_hash_a=pattern_a_s
-patterns.settings_to_hash_b=pattern_b_s
-patterns.settings_to_hash_c=pattern_c_s
-patterns.settings_to_hash_d=pattern_d_s
-function parsers.make_settings_to_hash_pattern(set,how)
- if how=="strict" then
- return (pattern_c/set)^1
- elseif how=="tolerant" then
- return (pattern_b/set)^1
- else
- return (pattern_a/set)^1
- end
-end
-function parsers.settings_to_hash(str,existing)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- if existing then
- for k,v in next,str do
- existing[k]=v
- end
- return exiting
- else
- return str
- end
- else
- hash=existing or {}
- lpegmatch(pattern_a_s,str)
- return hash
- end
-end
-function parsers.settings_to_hash_colon_too(str)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- return str
- else
- hash={}
- lpegmatch(pattern_d_s,str)
- return hash
- end
-end
-function parsers.settings_to_hash_tolerant(str,existing)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- if existing then
- for k,v in next,str do
- existing[k]=v
- end
- return exiting
- else
- return str
- end
- else
- hash=existing or {}
- lpegmatch(pattern_b_s,str)
- return hash
- end
-end
-function parsers.settings_to_hash_strict(str,existing)
- if not str or str=="" then
- return nil
- elseif type(str)=="table" then
- if existing then
- for k,v in next,str do
- existing[k]=v
- end
- return exiting
- else
- return str
- end
- elseif str and str~="" then
- hash=existing or {}
- lpegmatch(pattern_c_s,str)
- return next(hash) and hash
- end
-end
-local separator=comma*space^0
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+(1-comma))^0)
-local pattern=spaces*Ct(value*(separator*value)^0)
-patterns.settings_to_array=pattern
-function parsers.settings_to_array(str,strict)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- return str
- elseif strict then
- if find(str,"{",1,true) then
- return lpegmatch(pattern,str)
- else
- return { str }
- end
- elseif find(str,",",1,true) then
- return lpegmatch(pattern,str)
- else
- return { str }
- end
-end
-function parsers.settings_to_numbers(str)
- if not str or str=="" then
- return {}
- end
- if type(str)=="table" then
- elseif find(str,",",1,true) then
- str=lpegmatch(pattern,str)
- else
- return { tonumber(str) }
- end
- for i=1,#str do
- str[i]=tonumber(str[i])
- end
- return str
-end
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+nestedbrackets+nestedparents+(1-comma))^0)
-local pattern=spaces*Ct(value*(separator*value)^0)
-function parsers.settings_to_array_obey_fences(str)
- return lpegmatch(pattern,str)
-end
-local cache_a={}
-local cache_b={}
-function parsers.groupedsplitat(symbol,withaction)
- if not symbol then
- symbol=","
- end
- local pattern=(withaction and cache_b or cache_a)[symbol]
- if not pattern then
- local symbols=S(symbol)
- local separator=space^0*symbols*space^0
- local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+(1-(space^0*(symbols+P(-1)))))^0)
- if withaction then
- local withvalue=Carg(1)*value/function(f,s) return f(s) end
- pattern=spaces*withvalue*(separator*withvalue)^0
- cache_b[symbol]=pattern
- else
- pattern=spaces*Ct(value*(separator*value)^0)
- cache_a[symbol]=pattern
- end
- end
- return pattern
-end
-local pattern_a=parsers.groupedsplitat(",",false)
-local pattern_b=parsers.groupedsplitat(",",true)
-function parsers.stripped_settings_to_array(str)
- if not str or str=="" then
- return {}
- else
- return lpegmatch(pattern_a,str)
- end
-end
-function parsers.process_stripped_settings(str,action)
- if not str or str=="" then
- return {}
- else
- return lpegmatch(pattern_b,str,1,action)
- end
-end
-local function set(t,v)
- t[#t+1]=v
-end
-local value=P(Carg(1)*value)/set
-local pattern=value*(separator*value)^0*Carg(1)
-function parsers.add_settings_to_array(t,str)
- return lpegmatch(pattern,str,nil,t)
-end
-function parsers.hash_to_string(h,separator,yes,no,strict,omit)
- if h then
- local t={}
- local tn=0
- local s=sortedkeys(h)
- omit=omit and tohash(omit)
- for i=1,#s do
- local key=s[i]
- if not omit or not omit[key] then
- local value=h[key]
- if type(value)=="boolean" then
- if yes and no then
- if value then
- tn=tn+1
- t[tn]=key..'='..yes
- elseif not strict then
- tn=tn+1
- t[tn]=key..'='..no
- end
- elseif value or not strict then
- tn=tn+1
- t[tn]=key..'='..tostring(value)
- end
- else
- tn=tn+1
- t[tn]=key..'='..value
- end
- end
- end
- return concat(t,separator or ",")
- else
- return ""
- end
-end
-function parsers.array_to_string(a,separator)
- if a then
- return concat(a,separator or ",")
- else
- return ""
- end
-end
-local pattern=Cf(Ct("")*Cg(C((1-S(", "))^1)*S(", ")^0*Cc(true))^1,rawset)
-function parsers.settings_to_set(str)
- return str and lpegmatch(pattern,str) or {}
-end
-hashes.settings_to_set=table.setmetatableindex(function(t,k)
- local v=k and lpegmatch(pattern,k) or {}
- t[k]=v
- return v
-end)
-getmetatable(hashes.settings_to_set).__mode="kv"
-function parsers.simple_hash_to_string(h,separator)
- local t={}
- local tn=0
- for k,v in sortedhash(h) do
- if v then
- tn=tn+1
- t[tn]=k
- end
- end
- return concat(t,separator or ",")
-end
-local str=Cs(lpegpatterns.unquoted)+C((1-whitespace-equal)^1)
-local setting=Cf(Carg(1)*(whitespace^0*Cg(str*whitespace^0*(equal*whitespace^0*str+Cc(""))))^1,rawset)
-local splitter=setting^1
-function parsers.options_to_hash(str,target)
- return str and lpegmatch(splitter,str,1,target or {}) or {}
-end
-local splitter=lpeg.tsplitat(" ")
-function parsers.options_to_array(str)
- return str and lpegmatch(splitter,str) or {}
-end
-local value=P(lbrace*C((nobrace+nestedbraces)^0)*rbrace)+C(digit^1*lparent*(noparent+nestedparents)^1*rparent)+C((nestedbraces+(1-comma))^1)
-local pattern_a=spaces*Ct(value*(separator*value)^0)
-local function repeater(n,str)
- if not n then
- return str
- else
- local s=lpegmatch(pattern_a,str)
- if n==1 then
- return unpack(s)
- else
- local t={}
- local tn=0
- for i=1,n do
- for j=1,#s do
- tn=tn+1
- t[tn]=s[j]
- end
- end
- return unpack(t)
- end
- end
-end
-local value=P(lbrace*C((nobrace+nestedbraces)^0)*rbrace)+(C(digit^1)/tonumber*lparent*Cs((noparent+nestedparents)^1)*rparent)/repeater+C((nestedbraces+(1-comma))^1)
-local pattern_b=spaces*Ct(value*(separator*value)^0)
-function parsers.settings_to_array_with_repeat(str,expand)
- if expand then
- return lpegmatch(pattern_b,str) or {}
- else
- return lpegmatch(pattern_a,str) or {}
- end
-end
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace
-local pattern=Ct((space+value)^0)
-function parsers.arguments_to_table(str)
- return lpegmatch(pattern,str)
-end
-function parsers.getparameters(self,class,parentclass,settings)
- local sc=self[class]
- if not sc then
- sc={}
- self[class]=sc
- if parentclass then
- local sp=self[parentclass]
- if not sp then
- sp={}
- self[parentclass]=sp
- end
- setmetatableindex(sc,sp)
- end
- end
- parsers.settings_to_hash(settings,sc)
-end
-function parsers.listitem(str)
- return gmatch(str,"[^, ]+")
-end
-local pattern=Cs { "start",
- start=V("one")+V("two")+V("three"),
- rest=(Cc(",")*V("thousand"))^0*(P(".")+endofstring)*anything^0,
- thousand=digit*digit*digit,
- one=digit*V("rest"),
- two=digit*digit*V("rest"),
- three=V("thousand")*V("rest"),
-}
-lpegpatterns.splitthousands=pattern
-function parsers.splitthousands(str)
- return lpegmatch(pattern,str) or str
-end
-local optionalwhitespace=whitespace^0
-lpegpatterns.words=Ct((Cs((1-punctuation-whitespace)^1)+anything)^1)
-lpegpatterns.sentences=Ct((optionalwhitespace*Cs((1-period)^0*period))^1)
-lpegpatterns.paragraphs=Ct((optionalwhitespace*Cs((whitespace^1*endofstring/""+1-(spacer^0*newline*newline))^1))^1)
-local dquote=P('"')
-local equal=P('=')
-local escape=P('\\')
-local separator=S(' ,')
-local key=C((1-equal)^1)
-local value=dquote*C((1-dquote-escape*dquote)^0)*dquote
-local pattern=Cf(Ct("")*(Cg(key*equal*value)*separator^0)^1,rawset)^0*P(-1)
-function parsers.keq_to_hash(str)
- if str and str~="" then
- return lpegmatch(pattern,str)
- else
- return {}
- end
-end
-local defaultspecification={ separator=",",quote='"' }
-function parsers.csvsplitter(specification)
- specification=specification and setmetatableindex(specification,defaultspecification) or defaultspecification
- local separator=specification.separator
- local quotechar=specification.quote
- local numbers=specification.numbers
- local separator=S(separator~="" and separator or ",")
- local whatever=C((1-separator-newline)^0)
- if quotechar and quotechar~="" then
- local quotedata=nil
- for chr in gmatch(quotechar,".") do
- local quotechar=P(chr)
- local quoteitem=(1-quotechar)^0
- local quoteword=quotechar*(numbers and (quoteitem/tonumber) or C(quoteitem))*quotechar
- if quotedata then
- quotedata=quotedata+quoteword
- else
- quotedata=quoteword
- end
- end
- whatever=quotedata+whatever
- end
- local parser=Ct((Ct(whatever*(separator*whatever)^0)*S("\n\r")^1)^0 )
- return function(data)
- return lpegmatch(parser,data)
- end
-end
-function parsers.rfc4180splitter(specification)
- specification=specification and setmetatableindex(specification,defaultspecification) or defaultspecification
- local numbers=specification.numbers
- local separator=specification.separator
- local quotechar=P(specification.quote)
- local dquotechar=quotechar*quotechar
-/specification.quote
- local separator=S(separator~="" and separator or ",")
- local whatever=(dquotechar+(1-quotechar))^0
- local escaped=quotechar*(numbers and (whatever/tonumber) or Cs(whatever))*quotechar
- local non_escaped=C((1-quotechar-newline-separator)^1)
- local field=escaped+non_escaped+Cc("")
- local record=Ct(field*(separator*field)^1)
- local headerline=record*Cp()
- local morerecords=(newline^(specification.strict and -1 or 1)*record)^0
- local headeryes=Ct(morerecords)
- local headernop=Ct(record*morerecords)
- return function(data,getheader)
- if getheader then
- local header,position=lpegmatch(headerline,data)
- local data=lpegmatch(headeryes,data,position)
- return data,header
- else
- return lpegmatch(headernop,data)
- end
- end
-end
-local function ranger(first,last,n,action)
- if not first then
- elseif last==true then
- for i=first,n or first do
- action(i)
- end
- elseif last then
- for i=first,last do
- action(i)
- end
- else
- action(first)
- end
-end
-local cardinal=lpegpatterns.cardinal/tonumber
-local spacers=lpegpatterns.spacer^0
-local endofstring=lpegpatterns.endofstring
-local stepper=spacers*(cardinal*(spacers*S(":-")*spacers*(cardinal+Cc(true) )+Cc(false) )*Carg(1)*Carg(2)/ranger*S(", ")^0 )^1
-local stepper=spacers*(cardinal*(spacers*S(":-")*spacers*(cardinal+(P("*")+endofstring)*Cc(true) )+Cc(false) )*Carg(1)*Carg(2)/ranger*S(", ")^0 )^1*endofstring
-function parsers.stepper(str,n,action)
- if type(n)=="function" then
- lpegmatch(stepper,str,1,false,n or print)
- else
- lpegmatch(stepper,str,1,n,action or print)
- end
-end
-local pattern_math=Cs((P("%")/"\\percent "+P("^")*Cc("{")*lpegpatterns.integer*Cc("}")+anything)^0)
-local pattern_text=Cs((P("%")/"\\percent "+(P("^")/"\\high")*Cc("{")*lpegpatterns.integer*Cc("}")+anything)^0)
-patterns.unittotex=pattern
-function parsers.unittotex(str,textmode)
- return lpegmatch(textmode and pattern_text or pattern_math,str)
-end
-local pattern=Cs((P("^")/"<sup>"*lpegpatterns.integer*Cc("</sup>")+anything)^0)
-function parsers.unittoxml(str)
- return lpegmatch(pattern,str)
-end
-local cache={}
-local spaces=lpegpatterns.space^0
-local dummy=function() end
-setmetatableindex(cache,function(t,k)
- local separator=P(k)
- local value=(1-separator)^0
- local pattern=spaces*C(value)*separator^0*Cp()
- t[k]=pattern
- return pattern
-end)
-local commalistiterator=cache[","]
-function parsers.iterator(str,separator)
- local n=#str
- if n==0 then
- return dummy
- else
- local pattern=separator and cache[separator] or commalistiterator
- local p=1
- return function()
- if p<=n then
- local s,e=lpegmatch(pattern,str,p)
- if e then
- p=e
- return s
- end
- end
- end
- end
-end
-local function initialize(t,name)
- local source=t[name]
- if source then
- local result={}
- for k,v in next,t[name] do
- result[k]=v
- end
- return result
- else
- return {}
- end
-end
-local function fetch(t,name)
- return t[name] or {}
-end
-local function process(result,more)
- for k,v in next,more do
- result[k]=v
- end
- return result
-end
-local name=C((1-S(", "))^1)
-local parser=(Carg(1)*name/initialize)*(S(", ")^1*(Carg(1)*name/fetch))^0
-local merge=Cf(parser,process)
-function parsers.mergehashes(hash,list)
- return lpegmatch(merge,list,1,hash)
-end
-function parsers.runtime(time)
- if not time then
- time=os.runtime()
- end
- local days=div(time,24*60*60)
- time=mod(time,24*60*60)
- local hours=div(time,60*60)
- time=mod(time,60*60)
- local minutes=div(time,60)
- local seconds=mod(time,60)
- return days,hours,minutes,seconds
-end
-local spacing=whitespace^0
-local apply=P("->")
-local method=C((1-apply)^1)
-local token=lbrace*C((1-rbrace)^1)*rbrace+C(anything^1)
-local pattern=spacing*(method*spacing*apply+Carg(1))*spacing*token
-function parsers.splitmethod(str,default)
- if str then
- return lpegmatch(pattern,str,1,default or false)
- else
- return default or false,""
- end
-end
-local p_year=lpegpatterns.digit^4/tonumber
-local pattern=Cf(Ct("")*(
- (Cg(Cc("year")*p_year)*S("-/")*Cg(Cc("month")*cardinal)*S("-/")*Cg(Cc("day")*cardinal)
- )+(Cg(Cc("day")*cardinal)*S("-/")*Cg(Cc("month")*cardinal)*S("-/")*Cg(Cc("year")*p_year)
- )
- )*P(" ")*Cg(Cc("hour")*cardinal)*P(":")*Cg(Cc("min")*cardinal)*(P(":")*Cg(Cc("sec")*cardinal))^-1
-,rawset)
-lpegpatterns.splittime=pattern
-function parsers.totime(str)
- return lpegmatch(pattern,str)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-fmt"] = package.loaded["util-fmt"] or true
-
--- original size: 2541, stripped down to: 1624
-
-if not modules then modules={} end modules ['util-fmt']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities=utilities or {}
-utilities.formatters=utilities.formatters or {}
-local formatters=utilities.formatters
-local concat,format=table.concat,string.format
-local tostring,type=tostring,type
-local strip=string.strip
-local lpegmatch=lpeg.match
-local stripper=lpeg.patterns.stripzeros
-function formatters.stripzeros(str)
- return lpegmatch(stripper,str)
-end
-function formatters.formatcolumns(result,between)
- if result and #result>0 then
- between=between or " "
- local widths,numbers={},{}
- local first=result[1]
- local n=#first
- for i=1,n do
- widths[i]=0
- end
- for i=1,#result do
- local r=result[i]
- for j=1,n do
- local rj=r[j]
- local tj=type(rj)
- if tj=="number" then
- numbers[j]=true
- rj=tostring(rj)
- elseif tj~="string" then
- rj=tostring(rj)
- r[j]=rj
- end
- local w=#rj
- if w>widths[j] then
- widths[j]=w
- end
- end
- end
- for i=1,n do
- local w=widths[i]
- if numbers[i] then
- if w>80 then
- widths[i]="%s"..between
- else
- widths[i]="%0"..w.."i"..between
- end
- else
- if w>80 then
- widths[i]="%s"..between
- elseif w>0 then
- widths[i]="%-"..w.."s"..between
- else
- widths[i]="%s"
- end
- end
- end
- local template=strip(concat(widths))
- for i=1,#result do
- local str=format(template,unpack(result[i]))
- result[i]=strip(str)
- end
- end
- return result
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-reset"] = package.loaded["util-soc-imp-reset"] or true
-
--- original size: 374, stripped down to: 282
-
-local loaded=package.loaded
-loaded["socket"]=nil
-loaded["copas"]=nil
-loaded["ltn12"]=nil
-loaded["mbox"]=nil
-loaded["mime"]=nil
-loaded["socket.url"]=nil
-loaded["socket.headers"]=nil
-loaded["socket.tp"]=nil
-loaded["socket.http"]=nil
-loaded["socket.ftp"]=nil
-loaded["socket.smtp"]=nil
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-socket"] = package.loaded["util-soc-imp-socket"] or true
-
--- original size: 4905, stripped down to: 3562
-
-
-local type,tostring,setmetatable=type,tostring,setmetatable
-local min=math.min
-local format=string.format
-local socket=socket or package.loaded.socket or require("socket.core")
-local connect=socket.connect
-local tcp4=socket.tcp4
-local tcp6=socket.tcp6
-local getaddrinfo=socket.dns.getaddrinfo
-local defaulthost="0.0.0.0"
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("socket")
- report(fmt,first,...)
- elseif fmt then
- fmt="socket: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-socket.report=report
-function socket.connect4(address,port,laddress,lport)
- return connect(address,port,laddress,lport,"inet")
-end
-function socket.connect6(address,port,laddress,lport)
- return connect(address,port,laddress,lport,"inet6")
-end
-function socket.bind(host,port,backlog)
- if host=="*" or host=="" then
- host=defaulthost
- end
- local addrinfo,err=getaddrinfo(host)
- if not addrinfo then
- return nil,err
- end
- for i=1,#addrinfo do
- local alt=addrinfo[i]
- local sock,err=(alt.family=="inet" and tcp4 or tcp6)()
- if not sock then
- return nil,err or "unknown error"
- end
- sock:setoption("reuseaddr",true)
- local res,err=sock:bind(alt.addr,port)
- if res then
- res,err=sock:listen(backlog)
- if res then
- return sock
- else
- sock:close()
- end
- else
- sock:close()
- end
- end
- return nil,"invalid address"
-end
-socket.try=socket.newtry()
-function socket.choose(list)
- return function(name,opt1,opt2)
- if type(name)~="string" then
- name,opt1,opt2="default",name,opt1
- end
- local f=list[name or "nil"]
- if f then
- return f(opt1,opt2)
- else
- report("error: unknown key '%s'",tostring(name))
- end
- end
-end
-local sourcet={}
-local sinkt={}
-socket.sourcet=sourcet
-socket.sinkt=sinkt
-socket.BLOCKSIZE=2048
-sinkt["close-when-done"]=function(sock)
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },
- {
- __call=function(self,chunk,err)
- if chunk then
- return sock:send(chunk)
- else
- sock:close()
- return 1
- end
- end
- }
- )
-end
-sinkt["keep-open"]=function(sock)
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },{
- __call=function(self,chunk,err)
- if chunk then
- return sock:send(chunk)
- else
- return 1
- end
- end
- }
- )
-end
-sinkt["default"]=sinkt["keep-open"]
-socket.sink=socket.choose(sinkt)
-sourcet["by-length"]=function(sock,length)
- local blocksize=socket.BLOCKSIZE
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },
- {
- __call=function()
- if length<=0 then
- return nil
- end
- local chunk,err=sock:receive(min(blocksize,length))
- if err then
- return nil,err
- end
- length=length-#chunk
- return chunk
- end
- }
- )
-end
-sourcet["until-closed"]=function(sock)
- local blocksize=socket.BLOCKSIZE
- local done=false
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },{
- __call=function()
- if done then
- return nil
- end
- local chunk,status,partial=sock:receive(blocksize)
- if not status then
- return chunk
- elseif status=="closed" then
- sock:close()
- done=true
- return partial
- else
- return nil,status
- end
- end
- }
- )
-end
-sourcet["default"]=sourcet["until-closed"]
-socket.source=socket.choose(sourcet)
-_G.socket=socket
-package.loaded["socket"]=socket
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-copas"] = package.loaded["util-soc-imp-copas"] or true
-
--- original size: 26186, stripped down to: 14893
-
-
-local socket=socket or require("socket")
-local ssl=ssl or nil
-local WATCH_DOG_TIMEOUT=120
-local UDP_DATAGRAM_MAX=8192
-local type,next,pcall,getmetatable,tostring=type,next,pcall,getmetatable,tostring
-local min,max,random=math.min,math.max,math.random
-local find=string.find
-local insert,remove=table.insert,table.remove
-local gettime=socket.gettime
-local selectsocket=socket.select
-local createcoroutine=coroutine.create
-local resumecoroutine=coroutine.resume
-local yieldcoroutine=coroutine.yield
-local runningcoroutine=coroutine.running
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("copas")
- report(fmt,first,...)
- elseif fmt then
- fmt="copas: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-local copas={
- _COPYRIGHT="Copyright (C) 2005-2016 Kepler Project",
- _DESCRIPTION="Coroutine Oriented Portable Asynchronous Services",
- _VERSION="Copas 2.0.1",
- autoclose=true,
- running=false,
- report=report,
- trace=false,
-}
-local function statushandler(status,...)
- if status then
- return...
- end
- local err=(...)
- if type(err)=="table" then
- err=err[1]
- end
- if copas.trace then
- report("error: %s",tostring(err))
- end
- return nil,err
-end
-function socket.protect(func)
- return function(...)
- return statushandler(pcall(func,...))
- end
-end
-function socket.newtry(finalizer)
- return function (...)
- local status=(...)
- if not status then
- local detail=select(2,...)
- pcall(finalizer,detail)
- if copas.trace then
- report("error: %s",tostring(detail))
- end
- return
- end
- return...
- end
-end
-local function newset()
- local reverse={}
- local set={}
- local queue={}
- setmetatable(set,{
- __index={
- insert=function(set,value)
- if not reverse[value] then
- local n=#set+1
- set[n]=value
- reverse[value]=n
- end
- end,
- remove=function(set,value)
- local index=reverse[value]
- if index then
- reverse[value]=nil
- local n=#set
- local top=set[n]
- set[n]=nil
- if top~=value then
- reverse[top]=index
- set[index]=top
- end
- end
- end,
- push=function (set,key,itm)
- local entry=queue[key]
- if entry==nil then
- queue[key]={ itm }
- else
- entry[#entry+1]=itm
- end
- end,
- pop=function (set,key)
- local top=queue[key]
- if top~=nil then
- local ret=remove(top,1)
- if top[1]==nil then
- queue[key]=nil
- end
- return ret
- end
- end
- }
- } )
- return set
-end
-local _sleeping={
- times={},
- cos={},
- lethargy={},
- insert=function()
- end,
- remove=function()
- end,
- push=function(self,sleeptime,co)
- if not co then
- return
- end
- if sleeptime<0 then
- self.lethargy[co]=true
- return
- else
- sleeptime=gettime()+sleeptime
- end
- local t=self.times
- local c=self.cos
- local i=1
- local n=#t
- while i<=n and t[i]<=sleeptime do
- i=i+1
- end
- insert(t,i,sleeptime)
- insert(c,i,co)
- end,
- getnext=
- function(self)
- local t=self.times
- local delay=t[1] and t[1]-gettime() or nil
- return delay and max(delay,0) or nil
- end,
- pop=
- function(self,time)
- local t=self.times
- local c=self.cos
- if #t==0 or time<t[1] then
- return
- end
- local co=c[1]
- remove(t,1)
- remove(c,1)
- return co
- end,
- wakeup=function(self,co)
- local let=self.lethargy
- if let[co] then
- self:push(0,co)
- let[co]=nil
- else
- local c=self.cos
- local t=self.times
- for i=1,#c do
- if c[i]==co then
- remove(c,i)
- remove(t,i)
- self:push(0,co)
- return
- end
- end
- end
- end
-}
-local _servers=newset()
-local _reading=newset()
-local _writing=newset()
-local _reading_log={}
-local _writing_log={}
-local _is_timeout={
- timeout=true,
- wantread=true,
- wantwrite=true,
-}
-local function isTCP(socket)
- return not find(tostring(socket),"^udp")
-end
-local function copasreceive(client,pattern,part)
- if not pattern or pattern=="" then
- pattern="*l"
- end
- local current_log=_reading_log
- local s,err
- repeat
- s,err,part=client:receive(pattern,part)
- if s or (not _is_timeout[err]) then
- current_log[client]=nil
- return s,err,part
- end
- if err=="wantwrite" then
- current_log=_writing_log
- current_log[client]=gettime()
- yieldcoroutine(client,_writing)
- else
- current_log=_reading_log
- current_log[client]=gettime()
- yieldcoroutine(client,_reading)
- end
- until false
-end
-local function copasreceivefrom(client,size)
- local s,err,port
- if not size or size==0 then
- size=UDP_DATAGRAM_MAX
- end
- repeat
- s,err,port=client:receivefrom(size)
- if s or err~="timeout" then
- _reading_log[client]=nil
- return s,err,port
- end
- _reading_log[client]=gettime()
- yieldcoroutine(client,_reading)
- until false
-end
-local function copasreceivepartial(client,pattern,part)
- if not pattern or pattern=="" then
- pattern="*l"
- end
- local logger=_reading_log
- local queue=_reading
- local s,err
- repeat
- s,err,part=client:receive(pattern,part)
- if s or (type(pattern)=="number" and part~="" and part) or not _is_timeout[err] then
- logger[client]=nil
- return s,err,part
- end
- if err=="wantwrite" then
- logger=_writing_log
- queue=_writing
- else
- logger=_reading_log
- queue=_reading
- end
- logger[client]=gettime()
- yieldcoroutine(client,queue)
- until false
-end
-local function copassend(client,data,from,to)
- if not from then
- from=1
- end
- local lastIndex=from-1
- local logger=_writing_log
- local queue=_writing
- local s,err
- repeat
- s,err,lastIndex=client:send(data,lastIndex+1,to)
- if random(100)>90 then
- logger[client]=gettime()
- yieldcoroutine(client,queue)
- end
- if s or not _is_timeout[err] then
- logger[client]=nil
- return s,err,lastIndex
- end
- if err=="wantread" then
- logger=_reading_log
- queue=_reading
- else
- logger=_writing_log
- queue=_writing
- end
- logger[client]=gettime()
- yieldcoroutine(client,queue)
- until false
-end
-local function copassendto(client,data,ip,port)
- repeat
- local s,err=client:sendto(data,ip,port)
- if random(100)>90 then
- _writing_log[client]=gettime()
- yieldcoroutine(client,_writing)
- end
- if s or err~="timeout" then
- _writing_log[client]=nil
- return s,err
- end
- _writing_log[client]=gettime()
- yieldcoroutine(client,_writing)
- until false
-end
-local function copasconnect(skt,host,port)
- skt:settimeout(0)
- local ret,err,tried_more_than_once
- repeat
- ret,err=skt:connect (host,port)
- if ret or (err~="timeout" and err~="Operation already in progress") then
- if not ret and err=="already connected" and tried_more_than_once then
- ret=1
- err=nil
- end
- _writing_log[skt]=nil
- return ret,err
- end
- tried_more_than_once=tried_more_than_once or true
- _writing_log[skt]=gettime()
- yieldcoroutine(skt,_writing)
- until false
-end
-local function copasdohandshake(skt,sslt)
- if not ssl then
- ssl=require("ssl")
- end
- if not ssl then
- report("error: no ssl library")
- return
- end
- local nskt,err=ssl.wrap(skt,sslt)
- if not nskt then
- report("error: %s",tostring(err))
- return
- end
- nskt:settimeout(0)
- local queue
- repeat
- local success,err=nskt:dohandshake()
- if success then
- return nskt
- elseif err=="wantwrite" then
- queue=_writing
- elseif err=="wantread" then
- queue=_reading
- else
- report("error: %s",tostring(err))
- return
- end
- yieldcoroutine(nskt,queue)
- until false
-end
-local function copasflush(client)
-end
-copas.connect=copassconnect
-copas.send=copassend
-copas.sendto=copassendto
-copas.receive=copasreceive
-copas.receivefrom=copasreceivefrom
-copas.copasreceivepartial=copasreceivepartial
-copas.copasreceivePartial=copasreceivepartial
-copas.dohandshake=copasdohandshake
-copas.flush=copasflush
-local function _skt_mt_tostring(self)
- return tostring(self.socket).." (copas wrapped)"
-end
-local _skt_mt_tcp_index={
- send=function(self,data,from,to)
- return copassend (self.socket,data,from,to)
- end,
- receive=function (self,pattern,prefix)
- if self.timeout==0 then
- return copasreceivePartial(self.socket,pattern,prefix)
- else
- return copasreceive(self.socket,pattern,prefix)
- end
- end,
- flush=function (self)
- return copasflush(self.socket)
- end,
- settimeout=function (self,time)
- self.timeout=time
- return true
- end,
- connect=function(self,...)
- local res,err=copasconnect(self.socket,...)
- if res and self.ssl_params then
- res,err=self:dohandshake()
- end
- return res,err
- end,
- close=function(self,...)
- return self.socket:close(...)
- end,
- bind=function(self,...)
- return self.socket:bind(...)
- end,
- getsockname=function(self,...)
- return self.socket:getsockname(...)
- end,
- getstats=function(self,...)
- return self.socket:getstats(...)
- end,
- setstats=function(self,...)
- return self.socket:setstats(...)
- end,
- listen=function(self,...)
- return self.socket:listen(...)
- end,
- accept=function(self,...)
- return self.socket:accept(...)
- end,
- setoption=function(self,...)
- return self.socket:setoption(...)
- end,
- getpeername=function(self,...)
- return self.socket:getpeername(...)
- end,
- shutdown=function(self,...)
- return self.socket:shutdown(...)
- end,
- dohandshake=function(self,sslt)
- self.ssl_params=sslt or self.ssl_params
- local nskt,err=copasdohandshake(self.socket,self.ssl_params)
- if not nskt then
- return nskt,err
- end
- self.socket=nskt
- return self
- end,
-}
-local _skt_mt_tcp={
- __tostring=_skt_mt_tostring,
- __index=_skt_mt_tcp_index,
-}
-local _skt_mt_udp_index={
- sendto=function (self,...)
- return copassendto(self.socket,...)
- end,
- receive=function (self,size)
- return copasreceive(self.socket,size or UDP_DATAGRAM_MAX)
- end,
- receivefrom=function (self,size)
- return copasreceivefrom(self.socket,size or UDP_DATAGRAM_MAX)
- end,
- setpeername=function(self,...)
- return self.socket:getpeername(...)
- end,
- setsockname=function(self,...)
- return self.socket:setsockname(...)
- end,
- close=function(self,...)
- return true
- end
-}
-local _skt_mt_udp={
- __tostring=_skt_mt_tostring,
- __index=_skt_mt_udp_index,
-}
-for k,v in next,_skt_mt_tcp_index do
- if not _skt_mt_udp_index[k] then
- _skt_mt_udp_index[k]=v
- end
-end
-local function wrap(skt,sslt)
- if getmetatable(skt)==_skt_mt_tcp or getmetatable(skt)==_skt_mt_udp then
- return skt
- end
- skt:settimeout(0)
- if isTCP(skt) then
- return setmetatable ({ socket=skt,ssl_params=sslt },_skt_mt_tcp)
- else
- return setmetatable ({ socket=skt },_skt_mt_udp)
- end
-end
-copas.wrap=wrap
-function copas.handler(handler,sslparams)
- return function (skt,...)
- skt=wrap(skt)
- if sslparams then
- skt:dohandshake(sslparams)
- end
- return handler(skt,...)
- end
-end
-local _errhandlers={}
-function copas.setErrorHandler(err)
- local co=runningcoroutine()
- if co then
- _errhandlers[co]=err
- end
-end
-local function _deferror (msg,co,skt)
- report("%s (%s) (%s)",msg,tostring(co),tostring(skt))
-end
-local function _doTick (co,skt,...)
- if not co then
- return
- end
- local ok,res,new_q=resumecoroutine(co,skt,...)
- if ok and res and new_q then
- new_q:insert(res)
- new_q:push(res,co)
- else
- if not ok then
- pcall(_errhandlers[co] or _deferror,res,co,skt)
- end
- if skt and copas.autoclose and isTCP(skt) then
- skt:close()
- end
- _errhandlers[co]=nil
- end
-end
-local function _accept(input,handler)
- local client=input:accept()
- if client then
- client:settimeout(0)
- local co=createcoroutine(handler)
- _doTick (co,client)
- end
- return client
-end
-local function _tickRead(skt)
- _doTick(_reading:pop(skt),skt)
-end
-local function _tickWrite(skt)
- _doTick(_writing:pop(skt),skt)
-end
-local function addTCPserver(server,handler,timeout)
- server:settimeout(timeout or 0)
- _servers[server]=handler
- _reading:insert(server)
-end
-local function addUDPserver(server,handler,timeout)
- server:settimeout(timeout or 0)
- local co=createcoroutine(handler)
- _reading:insert(server)
- _doTick(co,server)
-end
-function copas.addserver(server,handler,timeout)
- if isTCP(server) then
- addTCPserver(server,handler,timeout)
- else
- addUDPserver(server,handler,timeout)
- end
-end
-function copas.removeserver(server,keep_open)
- local s=server
- local mt=getmetatable(server)
- if mt==_skt_mt_tcp or mt==_skt_mt_udp then
- s=server.socket
- end
- _servers[s]=nil
- _reading:remove(s)
- if keep_open then
- return true
- end
- return server:close()
-end
-function copas.addthread(handler,...)
- local thread=createcoroutine(function(_,...) return handler(...) end)
- _doTick(thread,nil,...)
- return thread
-end
-local _tasks={}
-local function addtaskRead(task)
- task.def_tick=_tickRead
- _tasks[task]=true
-end
-local function addtaskWrite(task)
- task.def_tick=_tickWrite
- _tasks[task]=true
-end
-local function tasks()
- return next,_tasks
-end
-local _readable_t={
- events=function(self)
- local i=0
- return function ()
- i=i+1
- return self._evs[i]
- end
- end,
- tick=function(self,input)
- local handler=_servers[input]
- if handler then
- input=_accept(input,handler)
- else
- _reading:remove(input)
- self.def_tick(input)
- end
- end
-}
-addtaskRead(_readable_t)
-local _writable_t={
- events=function(self)
- local i=0
- return function()
- i=i+1
- return self._evs[i]
- end
- end,
- tick=function(self,output)
- _writing:remove(output)
- self.def_tick(output)
- end
-}
-addtaskWrite(_writable_t)
-local _sleeping_t={
- tick=function(self,time,...)
- _doTick(_sleeping:pop(time),...)
- end
-}
-function copas.sleep(sleeptime)
- yieldcoroutine((sleeptime or 0),_sleeping)
-end
-function copas.wakeup(co)
- _sleeping:wakeup(co)
-end
-local last_cleansing=0
-local function _select(timeout)
- local now=gettime()
- local r_evs,w_evs,err=selectsocket(_reading,_writing,timeout)
- _readable_t._evs=r_evs
- _writable_t._evs=w_evs
- if (last_cleansing-now)>WATCH_DOG_TIMEOUT then
- last_cleansing=now
- for skt,time in next,_reading_log do
- if not r_evs[skt] and (time-now)>WATCH_DOG_TIMEOUT then
- local n=#r_evs+1
- _reading_log[skt]=nil
- r_evs[n]=skt
- r_evs[skt]=n
- end
- end
- for skt,time in next,_writing_log do
- if not w_evs[skt] and (time-now)>WATCH_DOG_TIMEOUT then
- local n=#w_evs+1
- _writing_log[skt]=nil
- w_evs[n]=skt
- w_evs[skt]=n
- end
- end
- end
- if err=="timeout" and #r_evs+#w_evs>0 then
- return nil
- else
- return err
- end
-end
-local function copasfinished()
- return not (next(_reading) or next(_writing) or _sleeping:getnext())
-end
-local function copasstep(timeout)
- _sleeping_t:tick(gettime())
- local nextwait=_sleeping:getnext()
- if nextwait then
- timeout=timeout and min(nextwait,timeout) or nextwait
- elseif copasfinished() then
- return false
- end
- local err=_select(timeout)
- if err then
- if err=="timeout" then
- return false
- end
- return nil,err
- end
- for task in tasks() do
- for event in task:events() do
- task:tick(event)
- end
- end
- return true
-end
-copas.finished=copasfinished
-copas.step=copasstep
-function copas.loop(timeout)
- copas.running=true
- while not copasfinished() do
- copasstep(timeout)
- end
- copas.running=false
-end
-package.loaded["copas"]=copas
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-ltn12"] = package.loaded["util-soc-imp-ltn12"] or true
-
--- original size: 8709, stripped down to: 5411
-
-
-local select,unpack=select,unpack
-local insert,remove=table.insert,table.remove
-local sub=string.sub
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("ltn12")
- report(fmt,first,...)
- elseif fmt then
- fmt="ltn12: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-local filter={}
-local source={}
-local sink={}
-local pump={}
-local ltn12={
- _VERSION="LTN12 1.0.3",
- BLOCKSIZE=2048,
- filter=filter,
- source=source,
- sink=sink,
- pump=pump,
- report=report,
-}
-function filter.cycle(low,ctx,extra)
- if low then
- return function(chunk)
- return (low(ctx,chunk,extra))
- end
- end
-end
-function filter.chain(...)
- local arg={... }
- local n=select('#',...)
- local top=1
- local index=1
- local retry=""
- return function(chunk)
- retry=chunk and retry
- while true do
- local action=arg[index]
- if index==top then
- chunk=action(chunk)
- if chunk=="" or top==n then
- return chunk
- elseif chunk then
- index=index+1
- else
- top=top+1
- index=top
- end
- else
- chunk=action(chunk or "")
- if chunk=="" then
- index=index-1
- chunk=retry
- elseif chunk then
- if index==n then
- return chunk
- else
- index=index+1
- end
- else
- report("error: filter returned inappropriate 'nil'")
- return
- end
- end
- end
- end
-end
-local function empty()
- return nil
-end
-function source.empty()
- return empty
-end
-local function sourceerror(err)
- return function()
- return nil,err
- end
-end
-source.error=sourceerror
-function source.file(handle,io_err)
- if handle then
- local blocksize=ltn12.BLOCKSIZE
- return function()
- local chunk=handle:read(blocksize)
- if not chunk then
- handle:close()
- end
- return chunk
- end
- else
- return sourceerror(io_err or "unable to open file")
- end
-end
-function source.simplify(src)
- return function()
- local chunk,err_or_new=src()
- if err_or_new then
- src=err_or_new
- end
- if chunk then
- return chunk
- else
- return nil,err_or_new
- end
- end
-end
-function source.string(s)
- if s then
- local blocksize=ltn12.BLOCKSIZE
- local i=1
- return function()
- local nexti=i+blocksize
- local chunk=sub(s,i,nexti-1)
- i=nexti
- if chunk~="" then
- return chunk
- else
- return nil
- end
- end
- else return source.empty() end
-end
-function source.rewind(src)
- local t={}
- return function(chunk)
- if chunk then
- insert(t,chunk)
- else
- chunk=remove(t)
- if chunk then
- return chunk
- else
- return src()
- end
- end
- end
-end
-function source.chain(src,f,...)
- if... then
- f=filter.chain(f,...)
- end
- local last_in=""
- local last_out=""
- local state="feeding"
- local err
- return function()
- if not last_out then
- report("error: source is empty")
- return
- end
- while true do
- if state=="feeding" then
- last_in,err=src()
- if err then
- return nil,err
- end
- last_out=f(last_in)
- if not last_out then
- if last_in then
- report("error: filter returned inappropriate 'nil'")
- end
- return nil
- elseif last_out~="" then
- state="eating"
- if last_in then
- last_in=""
- end
- return last_out
- end
- else
- last_out=f(last_in)
- if last_out=="" then
- if last_in=="" then
- state="feeding"
- else
- report("error: filter returned nothing")
- return
- end
- elseif not last_out then
- if last_in then
- report("filter returned inappropriate 'nil'")
- end
- return nil
- else
- return last_out
- end
- end
- end
- end
-end
-function source.cat(...)
- local arg={... }
- local src=remove(arg,1)
- return function()
- while src do
- local chunk,err=src()
- if chunk then
- return chunk
- end
- if err then
- return nil,err
- end
- src=remove(arg,1)
- end
- end
-end
-function sink.table(t)
- if not t then
- t={}
- end
- local f=function(chunk,err)
- if chunk then
- insert(t,chunk)
- end
- return 1
- end
- return f,t
-end
-function sink.simplify(snk)
- return function(chunk,err)
- local ret,err_or_new=snk(chunk,err)
- if not ret then
- return nil,err_or_new
- end
- if err_or_new then
- snk=err_or_new
- end
- return 1
- end
-end
-local function null()
- return 1
-end
-function sink.null()
- return null
-end
-local function sinkerror(err)
- return function()
- return nil,err
- end
-end
-sink.error=sinkerror
-function sink.file(handle,io_err)
- if handle then
- return function(chunk,err)
- if not chunk then
- handle:close()
- return 1
- else
- return handle:write(chunk)
- end
- end
- else
- return sinkerror(io_err or "unable to open file")
- end
-end
-function sink.chain(f,snk,...)
- if... then
- local args={ f,snk,... }
- snk=remove(args,#args)
- f=filter.chain(unpack(args))
- end
- return function(chunk,err)
- if chunk~="" then
- local filtered=f(chunk)
- local done=chunk and ""
- while true do
- local ret,snkerr=snk(filtered,err)
- if not ret then
- return nil,snkerr
- end
- if filtered==done then
- return 1
- end
- filtered=f(done)
- end
- else
- return 1
- end
- end
-end
-function pump.step(src,snk)
- local chunk,src_err=src()
- local ret,snk_err=snk(chunk,src_err)
- if chunk and ret then
- return 1
- else
- return nil,src_err or snk_err
- end
-end
-function pump.all(src,snk,step)
- if not step then
- step=pump.step
- end
- while true do
- local ret,err=step(src,snk)
- if not ret then
- if err then
- return nil,err
- else
- return 1
- end
- end
- end
-end
-package.loaded["ltn12"]=ltn12
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-mime"] = package.loaded["util-soc-imp-mime"] or true
-
--- original size: 2373, stripped down to: 1931
-
-
-local type,tostring=type,tostring
-local mime=mime or package.loaded.mime or require("mime.core")
-local ltn12=ltn12 or package.loaded.ltn12 or require("ltn12")
-local filtercycle=ltn12.filter.cycle
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("mime")
- report(fmt,first,...)
- elseif fmt then
- fmt="mime: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-mime.report=report
-local encodet={}
-local decodet={}
-local wrapt={}
-mime.encodet=encodet
-mime.decodet=decodet
-mime.wrapt=wrapt
-local mime_b64=mime.b64
-local mime_qp=mime.qp
-local mime_unb64=mime.unb64
-local mime_unqp=mime.unqp
-local mime_wrp=mime.wrp
-local mime_qpwrp=mime.qpwrp
-local mime_eol=mime_eol
-local mime_dot=mime_dot
-encodet['base64']=function()
- return filtercycle(mime_b64,"")
-end
-encodet['quoted-printable']=function(mode)
- return filtercycle(mime_qp,"",mode=="binary" and "=0D=0A" or "\r\n")
-end
-decodet['base64']=function()
- return filtercycle(mime_unb64,"")
-end
-decodet['quoted-printable']=function()
- return filtercycle(mime_unqp,"")
-end
-local wraptext=function(length)
- if not length then
- length=76
- end
- return filtercycle(mime_wrp,length,length)
-end
-local wrapquoted=function()
- return filtercycle(mime_qpwrp,76,76)
-end
-wrapt['text']=wraptext
-wrapt['base64']=wraptext
-wrapt['default']=wraptext
-wrapt['quoted-printable']=wrapquoted
-function mime.normalize(marker)
- return filtercycle(mime_eol,0,marker)
-end
-function mime.stuff()
- return filtercycle(mime_dot,2)
-end
-local function choose(list)
- return function(name,opt1,opt2)
- if type(name)~="string" then
- name,opt1,opt2="default",name,opt1
- end
- local filter=list[name or "nil"]
- if filter then
- return filter(opt1,opt2)
- else
- report("error: unknown key '%s'",tostring(name))
- end
- end
-end
-mime.encode=choose(encodet)
-mime.decode=choose(decodet)
-mime.wrap=choose(wrapt)
-package.loaded["mime"]=mime
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-url"] = package.loaded["util-soc-imp-url"] or true
-
--- original size: 6863, stripped down to: 5269
-
-
-local tonumber,tostring,type=tonumber,tostring,type
-local gsub,sub,match,find,format,byte,char=string.gsub,string.sub,string.match,string.find,string.format,string.byte,string.char
-local insert=table.insert
-local socket=socket or require("socket")
-local url={
- _VERSION="URL 1.0.3",
-}
-socket.url=url
-function url.escape(s)
- return (gsub(s,"([^A-Za-z0-9_])",function(c)
- return format("%%%02x",byte(c))
- end))
-end
-local function make_set(t)
- local s={}
- for i=1,#t do
- s[t[i]]=true
- end
- return s
-end
-local segment_set=make_set {
- "-","_",".","!","~","*","'","(",
- ")",":","@","&","=","+","$",",",
-}
-local function protect_segment(s)
- return gsub(s,"([^A-Za-z0-9_])",function(c)
- if segment_set[c] then
- return c
- else
- return format("%%%02X",byte(c))
- end
- end)
-end
-function url.unescape(s)
- return (gsub(s,"%%(%x%x)",function(hex)
- return char(tonumber(hex,16))
- end))
-end
-local function absolute_path(base_path,relative_path)
- if find(relative_path,"^/") then
- return relative_path
- end
- local path=gsub(base_path,"[^/]*$","")
- path=path..relative_path
- path=gsub(path,"([^/]*%./)",function (s)
- if s~="./" then
- return s
- else
- return ""
- end
- end)
- path=gsub(path,"/%.$","/")
- local reduced
- while reduced~=path do
- reduced=path
- path=gsub(reduced,"([^/]*/%.%./)",function (s)
- if s~="../../" then
- return ""
- else
- return s
- end
- end)
- end
- path=gsub(reduced,"([^/]*/%.%.)$",function (s)
- if s~="../.." then
- return ""
- else
- return s
- end
- end)
- return path
-end
-function url.parse(url,default)
- local parsed={}
- for k,v in next,default or parsed do
- parsed[k]=v
- end
- if not url or url=="" then
- return nil,"invalid url"
- end
- url=gsub(url,"#(.*)$",function(f)
- parsed.fragment=f
- return ""
- end)
- url=gsub(url,"^([%w][%w%+%-%.]*)%:",function(s)
- parsed.scheme=s
- return ""
- end)
- url=gsub(url,"^//([^/]*)",function(n)
- parsed.authority=n
- return ""
- end)
- url=gsub(url,"%?(.*)",function(q)
- parsed.query=q
- return ""
- end)
- url=gsub(url,"%;(.*)",function(p)
- parsed.params=p
- return ""
- end)
- if url~="" then
- parsed.path=url
- end
- local authority=parsed.authority
- if not authority then
- return parsed
- end
- authority=gsub(authority,"^([^@]*)@",function(u)
- parsed.userinfo=u
- return ""
- end)
- authority=gsub(authority,":([^:%]]*)$",function(p)
- parsed.port=p
- return ""
- end)
- if authority~="" then
- parsed.host=match(authority,"^%[(.+)%]$") or authority
- end
- local userinfo=parsed.userinfo
- if not userinfo then
- return parsed
- end
- userinfo=gsub(userinfo,":([^:]*)$",function(p)
- parsed.password=p
- return ""
- end)
- parsed.user=userinfo
- return parsed
-end
-function url.build(parsed)
- local url=parsed.path or ""
- if parsed.params then
- url=url..";"..parsed.params
- end
- if parsed.query then
- url=url.."?"..parsed.query
- end
- local authority=parsed.authority
- if parsed.host then
- authority=parsed.host
- if find(authority,":") then
- authority="["..authority.."]"
- end
- if parsed.port then
- authority=authority..":"..tostring(parsed.port)
- end
- local userinfo=parsed.userinfo
- if parsed.user then
- userinfo=parsed.user
- if parsed.password then
- userinfo=userinfo..":"..parsed.password
- end
- end
- if userinfo then authority=userinfo.."@"..authority end
- end
- if authority then
- url="//"..authority..url
- end
- if parsed.scheme then
- url=parsed.scheme..":"..url
- end
- if parsed.fragment then
- url=url.."#"..parsed.fragment
- end
- return url
-end
-function url.absolute(base_url,relative_url)
- local base_parsed
- if type(base_url)=="table" then
- base_parsed=base_url
- base_url=url.build(base_parsed)
- else
- base_parsed=url.parse(base_url)
- end
- local relative_parsed=url.parse(relative_url)
- if not base_parsed then
- return relative_url
- elseif not relative_parsed then
- return base_url
- elseif relative_parsed.scheme then
- return relative_url
- else
- relative_parsed.scheme=base_parsed.scheme
- if not relative_parsed.authority then
- relative_parsed.authority=base_parsed.authority
- if not relative_parsed.path then
- relative_parsed.path=base_parsed.path
- if not relative_parsed.params then
- relative_parsed.params=base_parsed.params
- if not relative_parsed.query then
- relative_parsed.query=base_parsed.query
- end
- end
- else
- relative_parsed.path=absolute_path(base_parsed.path or "",relative_parsed.path)
- end
- end
- return url.build(relative_parsed)
- end
-end
-function url.parse_path(path)
- local parsed={}
- path=path or ""
- gsub(path,"([^/]+)",function (s)
- insert(parsed,s)
- end)
- for i=1,#parsed do
- parsed[i]=url.unescape(parsed[i])
- end
- if sub(path,1,1)=="/" then
- parsed.is_absolute=1
- end
- if sub(path,-1,-1)=="/" then
- parsed.is_directory=1
- end
- return parsed
-end
-function url.build_path(parsed,unsafe)
- local path=""
- local n=#parsed
- if unsafe then
- for i=1,n-1 do
- path=path..parsed[i].."/"
- end
- if n>0 then
- path=path..parsed[n]
- if parsed.is_directory then
- path=path.."/"
- end
- end
- else
- for i=1,n-1 do
- path=path..protect_segment(parsed[i]).."/"
- end
- if n>0 then
- path=path..protect_segment(parsed[n])
- if parsed.is_directory then
- path=path.."/"
- end
- end
- end
- if parsed.is_absolute then
- path="/"..path
- end
- return path
-end
-package.loaded["socket.url"]=url
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-headers"] = package.loaded["util-soc-imp-headers"] or true
-
--- original size: 5721, stripped down to: 3754
-
-
-local next=next
-local lower=string.lower
-local concat=table.concat
-local socket=socket or require("socket")
-local headers={}
-socket.headers=headers
-local canonic={
- ["accept"]="Accept",
- ["accept-charset"]="Accept-Charset",
- ["accept-encoding"]="Accept-Encoding",
- ["accept-language"]="Accept-Language",
- ["accept-ranges"]="Accept-Ranges",
- ["action"]="Action",
- ["alternate-recipient"]="Alternate-Recipient",
- ["age"]="Age",
- ["allow"]="Allow",
- ["arrival-date"]="Arrival-Date",
- ["authorization"]="Authorization",
- ["bcc"]="Bcc",
- ["cache-control"]="Cache-Control",
- ["cc"]="Cc",
- ["comments"]="Comments",
- ["connection"]="Connection",
- ["content-description"]="Content-Description",
- ["content-disposition"]="Content-Disposition",
- ["content-encoding"]="Content-Encoding",
- ["content-id"]="Content-ID",
- ["content-language"]="Content-Language",
- ["content-length"]="Content-Length",
- ["content-location"]="Content-Location",
- ["content-md5"]="Content-MD5",
- ["content-range"]="Content-Range",
- ["content-transfer-encoding"]="Content-Transfer-Encoding",
- ["content-type"]="Content-Type",
- ["cookie"]="Cookie",
- ["date"]="Date",
- ["diagnostic-code"]="Diagnostic-Code",
- ["dsn-gateway"]="DSN-Gateway",
- ["etag"]="ETag",
- ["expect"]="Expect",
- ["expires"]="Expires",
- ["final-log-id"]="Final-Log-ID",
- ["final-recipient"]="Final-Recipient",
- ["from"]="From",
- ["host"]="Host",
- ["if-match"]="If-Match",
- ["if-modified-since"]="If-Modified-Since",
- ["if-none-match"]="If-None-Match",
- ["if-range"]="If-Range",
- ["if-unmodified-since"]="If-Unmodified-Since",
- ["in-reply-to"]="In-Reply-To",
- ["keywords"]="Keywords",
- ["last-attempt-date"]="Last-Attempt-Date",
- ["last-modified"]="Last-Modified",
- ["location"]="Location",
- ["max-forwards"]="Max-Forwards",
- ["message-id"]="Message-ID",
- ["mime-version"]="MIME-Version",
- ["original-envelope-id"]="Original-Envelope-ID",
- ["original-recipient"]="Original-Recipient",
- ["pragma"]="Pragma",
- ["proxy-authenticate"]="Proxy-Authenticate",
- ["proxy-authorization"]="Proxy-Authorization",
- ["range"]="Range",
- ["received"]="Received",
- ["received-from-mta"]="Received-From-MTA",
- ["references"]="References",
- ["referer"]="Referer",
- ["remote-mta"]="Remote-MTA",
- ["reply-to"]="Reply-To",
- ["reporting-mta"]="Reporting-MTA",
- ["resent-bcc"]="Resent-Bcc",
- ["resent-cc"]="Resent-Cc",
- ["resent-date"]="Resent-Date",
- ["resent-from"]="Resent-From",
- ["resent-message-id"]="Resent-Message-ID",
- ["resent-reply-to"]="Resent-Reply-To",
- ["resent-sender"]="Resent-Sender",
- ["resent-to"]="Resent-To",
- ["retry-after"]="Retry-After",
- ["return-path"]="Return-Path",
- ["sender"]="Sender",
- ["server"]="Server",
- ["smtp-remote-recipient"]="SMTP-Remote-Recipient",
- ["status"]="Status",
- ["subject"]="Subject",
- ["te"]="TE",
- ["to"]="To",
- ["trailer"]="Trailer",
- ["transfer-encoding"]="Transfer-Encoding",
- ["upgrade"]="Upgrade",
- ["user-agent"]="User-Agent",
- ["vary"]="Vary",
- ["via"]="Via",
- ["warning"]="Warning",
- ["will-retry-until"]="Will-Retry-Until",
- ["www-authenticate"]="WWW-Authenticate",
- ["x-mailer"]="X-Mailer",
-}
-headers.canonic=setmetatable(canonic,{
- __index=function(t,k)
- socket.report("invalid header: %s",k)
- t[k]=k
- return k
- end
-})
-function headers.normalize(headers)
- if not headers then
- return {}
- end
- local normalized={}
- for k,v in next,headers do
- normalized[#normalized+1]=canonic[k]..": "..v
- end
- normalized[#normalized+1]=""
- normalized[#normalized+1]=""
- return concat(normalized,"\r\n")
-end
-function headers.lower(lowered,headers)
- if not lowered then
- return {}
- end
- if not headers then
- lowered,headers={},lowered
- end
- for k,v in next,headers do
- lowered[lower(k)]=v
- end
- return lowered
-end
-socket.headers=headers
-package.loaded["socket.headers"]=headers
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-tp"] = package.loaded["util-soc-imp-tp"] or true
-
--- original size: 3116, stripped down to: 2533
-
-
-local setmetatable,next,type,tonumber=setmetatable,next,type,tonumber
-local find,upper=string.find,string.upper
-local socket=socket or require("socket")
-local ltn12=ltn12 or require("ltn12")
-local skipsocket=socket.skip
-local sinksocket=socket.sink
-local tcpsocket=socket.tcp
-local ltn12pump=ltn12.pump
-local pumpall=ltn12pump.all
-local pumpstep=ltn12pump.step
-local tp={
- TIMEOUT=60,
-}
-socket.tp=tp
-local function get_reply(c)
- local line,err=c:receive()
- local reply=line
- if err then return
- nil,err
- end
- local code,sep=skipsocket(2,find(line,"^(%d%d%d)(.?)"))
- if not code then
- return nil,"invalid server reply"
- end
- if sep=="-" then
- local current
- repeat
- line,err=c:receive()
- if err then
- return nil,err
- end
- current,sep=skipsocket(2,find(line,"^(%d%d%d)(.?)"))
- reply=reply.."\n"..line
- until code==current and sep==" "
- end
- return code,reply
-end
-local methods={}
-local mt={ __index=methods }
-function methods.getpeername(self)
- return self.c:getpeername()
-end
-function methods.getsockname(self)
- return self.c:getpeername()
-end
-function methods.check(self,ok)
- local code,reply=get_reply(self.c)
- if not code then
- return nil,reply
- end
- local c=tonumber(code)
- local t=type(ok)
- if t=="function" then
- return ok(c,reply)
- elseif t=="table" then
- for i=1,#ok do
- if find(code,ok[i]) then
- return c,reply
- end
- end
- return nil,reply
- elseif find(code,ok) then
- return c,reply
- else
- return nil,reply
- end
-end
-function methods.command(self,cmd,arg)
- cmd=upper(cmd)
- if arg then
- cmd=cmd.." "..arg.."\r\n"
- else
- cmd=cmd.."\r\n"
- end
- return self.c:send(cmd)
-end
-function methods.sink(self,snk,pat)
- local chunk,err=self.c:receive(pat)
- return snk(chunk,err)
-end
-function methods.send(self,data)
- return self.c:send(data)
-end
-function methods.receive(self,pat)
- return self.c:receive(pat)
-end
-function methods.getfd(self)
- return self.c:getfd()
-end
-function methods.dirty(self)
- return self.c:dirty()
-end
-function methods.getcontrol(self)
- return self.c
-end
-function methods.source(self,source,step)
- local sink=sinksocket("keep-open",self.c)
- local ret,err=pumpall(source,sink,step or pumpstep)
- return ret,err
-end
-function methods.close(self)
- self.c:close()
- return 1
-end
-function tp.connect(host,port,timeout,create)
- local c,e=(create or tcpsocket)()
- if not c then
- return nil,e
- end
- c:settimeout(timeout or tp.TIMEOUT)
- local r,e=c:connect(host,port)
- if not r then
- c:close()
- return nil,e
- end
- return setmetatable({ c=c },mt)
-end
-package.loaded["socket.tp"]=tp
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-http"] = package.loaded["util-soc-imp-http"] or true
-
--- original size: 12624, stripped down to: 9598
-
-
-local tostring,tonumber,setmetatable,next,type=tostring,tonumber,setmetatable,next,type
-local find,lower,format,gsub,match=string.find,string.lower,string.format,string.gsub,string.match
-local concat=table.concat
-local socket=socket or require("socket")
-local url=socket.url or require("socket.url")
-local ltn12=ltn12 or require("ltn12")
-local mime=mime or require("mime")
-local headers=socket.headers or require("socket.headers")
-local normalizeheaders=headers.normalize
-local parseurl=url.parse
-local buildurl=url.build
-local absoluteurl=url.absolute
-local unescapeurl=url.unescape
-local skipsocket=socket.skip
-local sinksocket=socket.sink
-local sourcesocket=socket.source
-local trysocket=socket.try
-local tcpsocket=socket.tcp
-local newtrysocket=socket.newtry
-local protectsocket=socket.protect
-local emptysource=ltn12.source.empty
-local stringsource=ltn12.source.string
-local rewindsource=ltn12.source.rewind
-local pumpstep=ltn12.pump.step
-local pumpall=ltn12.pump.all
-local sinknull=ltn12.sink.null
-local sinktable=ltn12.sink.table
-local lowerheaders=headers.lower
-local mimeb64=mime.b64
-local http={
- TIMEOUT=60,
- USERAGENT=socket._VERSION,
-}
-socket.http=http
-local PORT=80
-local SCHEMES={
- http=true,
-}
-local function receiveheaders(sock,headers)
- if not headers then
- headers={}
- end
- local line,err=sock:receive("*l")
- if err then
- return nil,err
- end
- while line~="" do
- local name,value=skipsocket(2,find(line,"^(.-):%s*(.*)"))
- if not (name and value) then
- return nil,"malformed reponse headers"
- end
- name=lower(name)
- line,err=sock:receive("*l")
- if err then
- return nil,err
- end
- while find(line,"^%s") do
- value=value..line
- line=sock:receive("*l")
- if err then
- return nil,err
- end
- end
- local found=headers[name]
- if found then
- value=found..", "..value
- end
- headers[name]=value
- end
- return headers
-end
-socket.sourcet["http-chunked"]=function(sock,headers)
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },{
- __call=function()
- local line,err=sock:receive("*l")
- if err then
- return nil,err
- end
- local size=tonumber(gsub(line,";.*",""),16)
- if not size then
- return nil,"invalid chunk size"
- end
- if size>0 then
- local chunk,err,part=sock:receive(size)
- if chunk then
- sock:receive("*a")
- end
- return chunk,err
- else
- headers,err=receiveheaders(sock,headers)
- if not headers then
- return nil,err
- end
- end
- end
- }
- )
-end
-socket.sinkt["http-chunked"]=function(sock)
- return setmetatable(
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },
- {
- __call=function(self,chunk,err)
- if not chunk then
- chunk=""
- end
- return sock:send(format("%X\r\n%s\r\n",#chunk,chunk))
- end
- })
-end
-local methods={}
-local mt={ __index=methods }
-local function openhttp(host,port,create)
- local c=trysocket((create or tcpsocket)())
- local h=setmetatable({ c=c },mt)
- local try=newtrysocket(function() h:close() end)
- h.try=try
- try(c:settimeout(http.TIMEOUT))
- try(c:connect(host,port or PORT))
- return h
-end
-http.open=openhttp
-function methods.sendrequestline(self,method,uri)
- local requestline=format("%s %s HTTP/1.1\r\n",method or "GET",uri)
- return self.try(self.c:send(requestline))
-end
-function methods.sendheaders(self,headers)
- self.try(self.c:send(normalizeheaders(headers)))
- return 1
-end
-function methods.sendbody(self,headers,source,step)
- if not source then
- source=emptysource()
- end
- if not step then
- step=pumpstep
- end
- local mode="http-chunked"
- if headers["content-length"] then
- mode="keep-open"
- end
- return self.try(pumpall(source,sinksocket(mode,self.c),step))
-end
-function methods.receivestatusline(self)
- local try=self.try
- local status=try(self.c:receive(5))
- if status~="HTTP/" then
- return nil,status
- end
- status=try(self.c:receive("*l",status))
- local code=skipsocket(2,find(status,"HTTP/%d*%.%d* (%d%d%d)"))
- return try(tonumber(code),status)
-end
-function methods.receiveheaders(self)
- return self.try(receiveheaders(self.c))
-end
-function methods.receivebody(self,headers,sink,step)
- if not sink then
- sink=sinknull()
- end
- if not step then
- step=pumpstep
- end
- local length=tonumber(headers["content-length"])
- local encoding=headers["transfer-encoding"]
- local mode="default"
- if encoding and encoding~="identity" then
- mode="http-chunked"
- elseif length then
- mode="by-length"
- end
- return self.try(pumpall(sourcesocket(mode,self.c,length),sink,step))
-end
-function methods.receive09body(self,status,sink,step)
- local source=rewindsource(sourcesocket("until-closed",self.c))
- source(status)
- return self.try(pumpall(source,sink,step))
-end
-function methods.close(self)
- return self.c:close()
-end
-local function adjusturi(request)
- if not request.proxy and not http.PROXY then
- request={
- path=trysocket(request.path,"invalid path 'nil'"),
- params=request.params,
- query=request.query,
- fragment=request.fragment,
- }
- end
- return buildurl(request)
-end
-local function adjustheaders(request)
- local headers={
- ["user-agent"]=http.USERAGENT,
- ["host"]=gsub(request.authority,"^.-@",""),
- ["connection"]="close, TE",
- ["te"]="trailers"
- }
- local username=request.user
- local password=request.password
- if username and password then
- headers["authorization"]="Basic "..(mimeb64(username..":"..unescapeurl(password)))
- end
- local proxy=request.proxy or http.PROXY
- if proxy then
- proxy=parseurl(proxy)
- local username=proxy.user
- local password=proxy.password
- if username and password then
- headers["proxy-authorization"]="Basic "..(mimeb64(username..":"..password))
- end
- end
- local requestheaders=request.headers
- if requestheaders then
- headers=lowerheaders(headers,requestheaders)
- end
- return headers
-end
-local default={
- host="",
- port=PORT,
- path="/",
- scheme="http"
-}
-local function adjustrequest(originalrequest)
- local url=originalrequest.url
- local request=url and parseurl(url,default) or {}
- for k,v in next,originalrequest do
- request[k]=v
- end
- local host=request.host
- local port=request.port
- local uri=request.uri
- if not host or host=="" then
- trysocket(nil,"invalid host '"..tostring(host).."'")
- end
- if port=="" then
- request.port=PORT
- end
- if not uri or uri=="" then
- request.uri=adjusturi(request)
- end
- request.headers=adjustheaders(request)
- local proxy=request.proxy or http.PROXY
- if proxy then
- proxy=parseurl(proxy)
- request.host=proxy.host
- request.port=proxy.port or 3128
- end
- return request
-end
-local maxredericts=4
-local validredirects={ [301]=true,[302]=true,[303]=true,[307]=true }
-local validmethods={ [false]=true,GET=true,HEAD=true }
-local function shouldredirect(request,code,headers)
- local location=headers.location
- if not location then
- return false
- end
- location=gsub(location,"%s","")
- if location=="" then
- return false
- end
- local scheme=match(location,"^([%w][%w%+%-%.]*)%:")
- if scheme and not SCHEMES[scheme] then
- return false
- end
- local method=request.method
- local redirect=request.redirect
- local redirects=request.nredirects or 0
- return redirect and validredirects[code] and validmethods[method] and redirects<=maxredericts
-end
-local function shouldreceivebody(request,code)
- if request.method=="HEAD" then
- return nil
- end
- if code==204 or code==304 then
- return nil
- end
- if code>=100 and code<200 then
- return nil
- end
- return 1
-end
-local tredirect,trequest,srequest
-tredirect=function(request,location)
- local result,code,headers,status=trequest {
- url=absoluteurl(request.url,location),
- source=request.source,
- sink=request.sink,
- headers=request.headers,
- proxy=request.proxy,
- nredirects=(request.nredirects or 0)+1,
- create=request.create,
- }
- if not headers then
- headers={}
- end
- if not headers.location then
- headers.location=location
- end
- return result,code,headers,status
-end
-trequest=function(originalrequest)
- local request=adjustrequest(originalrequest)
- local connection=openhttp(request.host,request.port,request.create)
- local headers=request.headers
- connection:sendrequestline(request.method,request.uri)
- connection:sendheaders(headers)
- if request.source then
- connection:sendbody(headers,request.source,request.step)
- end
- local code,status=connection:receivestatusline()
- if not code then
- connection:receive09body(status,request.sink,request.step)
- return 1,200
- end
- while code==100 do
- headers=connection:receiveheaders()
- code,status=connection:receivestatusline()
- end
- headers=connection:receiveheaders()
- if shouldredirect(request,code,headers) and not request.source then
- connection:close()
- return tredirect(originalrequest,headers.location)
- end
- if shouldreceivebody(request,code) then
- connection:receivebody(headers,request.sink,request.step)
- end
- connection:close()
- return 1,code,headers,status
-end
-local function genericform(url,body)
- local buffer={}
- local request={
- url=url,
- sink=sinktable(buffer),
- target=buffer,
- }
- if body then
- request.source=stringsource(body)
- request.method="POST"
- request.headers={
- ["content-length"]=#body,
- ["content-type"]="application/x-www-form-urlencoded"
- }
- end
- return request
-end
-http.genericform=genericform
-srequest=function(url,body)
- local request=genericform(url,body)
- local _,code,headers,status=trequest(request)
- return concat(request.target),code,headers,status
-end
-http.request=protectsocket(function(request,body)
- if type(request)=="string" then
- return srequest(request,body)
- else
- return trequest(request)
- end
-end)
-package.loaded["socket.http"]=http
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-ftp"] = package.loaded["util-soc-imp-ftp"] or true
-
--- original size: 10357, stripped down to: 8548
-
-
-local setmetatable,type,next=setmetatable,type,next
-local find,format,gsub,match=string.find,string.format,string.gsub,string.match
-local concat=table.concat
-local mod=math.mod
-local socket=socket or require("socket")
-local url=socket.url or require("socket.url")
-local tp=socket.tp or require("socket.tp")
-local ltn12=ltn12 or require("ltn12")
-local tcpsocket=socket.tcp
-local trysocket=socket.try
-local skipsocket=socket.skip
-local sinksocket=socket.sink
-local selectsocket=socket.select
-local bindsocket=socket.bind
-local newtrysocket=socket.newtry
-local sourcesocket=socket.source
-local protectsocket=socket.protect
-local parseurl=url.parse
-local unescapeurl=url.unescape
-local pumpall=ltn12.pump.all
-local pumpstep=ltn12.pump.step
-local sourcestring=ltn12.source.string
-local sinktable=ltn12.sink.table
-local ftp={
- TIMEOUT=60,
- USER="ftp",
- PASSWORD="anonymous@anonymous.org",
-}
-socket.ftp=ftp
-local PORT=21
-local methods={}
-local mt={ __index=methods }
-function ftp.open(server,port,create)
- local tp=trysocket(tp.connect(server,port or PORT,ftp.TIMEOUT,create))
- local f=setmetatable({ tp=tp },metat)
- f.try=newtrysocket(function() f:close() end)
- return f
-end
-function methods.portconnect(self)
- local try=self.try
- local server=self.server
- try(server:settimeout(ftp.TIMEOUT))
- self.data=try(server:accept())
- try(self.data:settimeout(ftp.TIMEOUT))
-end
-function methods.pasvconnect(self)
- local try=self.try
- self.data=try(tcpsocket())
- self(self.data:settimeout(ftp.TIMEOUT))
- self(self.data:connect(self.pasvt.address,self.pasvt.port))
-end
-function methods.login(self,user,password)
- local try=self.try
- local tp=self.tp
- try(tp:command("user",user or ftp.USER))
- local code,reply=try(tp:check{"2..",331})
- if code==331 then
- try(tp:command("pass",password or ftp.PASSWORD))
- try(tp:check("2.."))
- end
- return 1
-end
-function methods.pasv(self)
- local try=self.try
- local tp=self.tp
- try(tp:command("pasv"))
- local code,reply=try(self.tp:check("2.."))
- local pattern="(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)"
- local a,b,c,d,p1,p2=skipsocket(2,find(reply,pattern))
- try(a and b and c and d and p1 and p2,reply)
- local address=format("%d.%d.%d.%d",a,b,c,d)
- local port=p1*256+p2
- local server=self.server
- self.pasvt={
- address=address,
- port=port,
- }
- if server then
- server:close()
- self.server=nil
- end
- return address,port
-end
-function methods.epsv(self)
- local try=self.try
- local tp=self.tp
- try(tp:command("epsv"))
- local code,reply=try(tp:check("229"))
- local pattern="%((.)(.-)%1(.-)%1(.-)%1%)"
- local d,prt,address,port=match(reply,pattern)
- try(port,"invalid epsv response")
- local address=tp:getpeername()
- local server=self.server
- self.pasvt={
- address=address,
- port=port,
- }
- if self.server then
- server:close()
- self.server=nil
- end
- return address,port
-end
-function methods.port(self,address,port)
- local try=self.try
- local tp=self.tp
- self.pasvt=nil
- if not address then
- address,port=try(tp:getsockname())
- self.server=try(bindsocket(address,0))
- address,port=try(self.server:getsockname())
- try(self.server:settimeout(ftp.TIMEOUT))
- end
- local pl=mod(port,256)
- local ph=(port-pl)/256
- local arg=gsub(format("%s,%d,%d",address,ph,pl),"%.",",")
- try(tp:command("port",arg))
- try(tp:check("2.."))
- return 1
-end
-function methods.eprt(self,family,address,port)
- local try=self.try
- local tp=self.tp
- self.pasvt=nil
- if not address then
- address,port=try(tp:getsockname())
- self.server=try(bindsocket(address,0))
- address,port=try(self.server:getsockname())
- try(self.server:settimeout(ftp.TIMEOUT))
- end
- local arg=format("|%s|%s|%d|",family,address,port)
- try(tp:command("eprt",arg))
- try(tp:check("2.."))
- return 1
-end
-function methods.send(self,sendt)
- local try=self.try
- local tp=self.tp
- try(self.pasvt or self.server,"need port or pasv first")
- if self.pasvt then
- self:pasvconnect()
- end
- local argument=sendt.argument or unescapeurl(gsub(sendt.path or "","^[/\\]",""))
- if argument=="" then
- argument=nil
- end
- local command=sendt.command or "stor"
- try(tp:command(command,argument))
- local code,reply=try(tp:check{"2..","1.."})
- if not self.pasvt then
- self:portconnect()
- end
- local step=sendt.step or pumpstep
- local readt={ tp }
- local checkstep=function(src,snk)
- local readyt=selectsocket(readt,nil,0)
- if readyt[tp] then
- code=try(tp:check("2.."))
- end
- return step(src,snk)
- end
- local sink=sinksocket("close-when-done",self.data)
- try(pumpall(sendt.source,sink,checkstep))
- if find(code,"1..") then
- try(tp:check("2.."))
- end
- self.data:close()
- local sent=skipsocket(1,self.data:getstats())
- self.data=nil
- return sent
-end
-function methods.receive(self,recvt)
- local try=self.try
- local tp=self.tp
- try(self.pasvt or self.server,"need port or pasv first")
- if self.pasvt then self:pasvconnect() end
- local argument=recvt.argument or unescapeurl(gsub(recvt.path or "","^[/\\]",""))
- if argument=="" then
- argument=nil
- end
- local command=recvt.command or "retr"
- try(tp:command(command,argument))
- local code,reply=try(tp:check{"1..","2.."})
- if code>=200 and code<=299 then
- recvt.sink(reply)
- return 1
- end
- if not self.pasvt then
- self:portconnect()
- end
- local source=sourcesocket("until-closed",self.data)
- local step=recvt.step or pumpstep
- try(pumpall(source,recvt.sink,step))
- if find(code,"1..") then
- try(tp:check("2.."))
- end
- self.data:close()
- self.data=nil
- return 1
-end
-function methods.cwd(self,dir)
- local try=self.try
- local tp=self.tp
- try(tp:command("cwd",dir))
- try(tp:check(250))
- return 1
-end
-function methods.type(self,typ)
- local try=self.try
- local tp=self.tp
- try(tp:command("type",typ))
- try(tp:check(200))
- return 1
-end
-function methods.greet(self)
- local try=self.try
- local tp=self.tp
- local code=try(tp:check{"1..","2.."})
- if find(code,"1..") then
- try(tp:check("2.."))
- end
- return 1
-end
-function methods.quit(self)
- local try=self.try
- try(self.tp:command("quit"))
- try(self.tp:check("2.."))
- return 1
-end
-function methods.close(self)
- local data=self.data
- if data then
- data:close()
- end
- local server=self.server
- if server then
- server:close()
- end
- local tp=self.tp
- if tp then
- tp:close()
- end
-end
-local function override(t)
- if t.url then
- local u=parseurl(t.url)
- for k,v in next,t do
- u[k]=v
- end
- return u
- else
- return t
- end
-end
-local function tput(putt)
- putt=override(putt)
- local host=putt.host
- trysocket(host,"missing hostname")
- local f=ftp.open(host,putt.port,putt.create)
- f:greet()
- f:login(putt.user,putt.password)
- local typ=putt.type
- if typ then
- f:type(typ)
- end
- f:epsv()
- local sent=f:send(putt)
- f:quit()
- f:close()
- return sent
-end
-local default={
- path="/",
- scheme="ftp",
-}
-local function genericform(u)
- local t=trysocket(parseurl(u,default))
- trysocket(t.scheme=="ftp","wrong scheme '"..t.scheme.."'")
- trysocket(t.host,"missing hostname")
- local pat="^type=(.)$"
- if t.params then
- local typ=skipsocket(2,find(t.params,pat))
- t.type=typ
- trysocket(typ=="a" or typ=="i","invalid type '"..typ.."'")
- end
- return t
-end
-ftp.genericform=genericform
-local function sput(u,body)
- local putt=genericform(u)
- putt.source=sourcestring(body)
- return tput(putt)
-end
-ftp.put=protectsocket(function(putt,body)
- if type(putt)=="string" then
- return sput(putt,body)
- else
- return tput(putt)
- end
-end)
-local function tget(gett)
- gett=override(gett)
- local host=gett.host
- trysocket(host,"missing hostname")
- local f=ftp.open(host,gett.port,gett.create)
- f:greet()
- f:login(gett.user,gett.password)
- if gett.type then
- f:type(gett.type)
- end
- f:epsv()
- f:receive(gett)
- f:quit()
- return f:close()
-end
-local function sget(u)
- local gett=genericform(u)
- local t={}
- gett.sink=sinktable(t)
- tget(gett)
- return concat(t)
-end
-ftp.command=protectsocket(function(cmdt)
- cmdt=override(cmdt)
- local command=cmdt.command
- local argument=cmdt.argument
- local check=cmdt.check
- local host=cmdt.host
- trysocket(host,"missing hostname")
- trysocket(command,"missing command")
- local f=ftp.open(host,cmdt.port,cmdt.create)
- local try=f.try
- local tp=f.tp
- f:greet()
- f:login(cmdt.user,cmdt.password)
- if type(command)=="table" then
- local argument=argument or {}
- for i=1,#command do
- local cmd=command[i]
- try(tp:command(cmd,argument[i]))
- if check and check[i] then
- try(tp:check(check[i]))
- end
- end
- else
- try(tp:command(command,argument))
- if check then
- try(tp:check(check))
- end
- end
- f:quit()
- return f:close()
-end)
-ftp.get=protectsocket(function(gett)
- if type(gett)=="string" then
- return sget(gett)
- else
- return tget(gett)
- end
-end)
-package.loaded["socket.ftp"]=ftp
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-smtp"] = package.loaded["util-soc-imp-smtp"] or true
-
--- original size: 7018, stripped down to: 5883
-
-
-local type,setmetatable,next=type,setmetatable,next
-local find,lower,format=string.find,string.lower,string.format
-local osdate,osgetenv=os.date,os.getenv
-local random=math.random
-local socket=socket or require("socket")
-local headers=socket.headers or require("socket.headers")
-local ltn12=ltn12 or require("ltn12")
-local tp=socket.tp or require("socket.tp")
-local mime=mime or require("mime")
-local mimeb64=mime.b64
-local mimestuff=mime.stuff
-local skipsocket=socket.skip
-local trysocket=socket.try
-local newtrysocket=socket.newtry
-local protectsocket=socket.protect
-local normalizeheaders=headers.normalize
-local lowerheaders=headers.lower
-local createcoroutine=coroutine.create
-local resumecoroutine=coroutine.resume
-local yieldcoroutine=coroutine.resume
-local smtp={
- TIMEOUT=60,
- SERVER="localhost",
- PORT=25,
- DOMAIN=osgetenv("SERVER_NAME") or "localhost",
- ZONE="-0000",
-}
-socket.smtp=smtp
-local methods={}
-local mt={ __index=methods }
-function methods.greet(self,domain)
- local try=self.try
- local tp=self.tp
- try(tp:check("2.."))
- try(tp:command("EHLO",domain or _M.DOMAIN))
- return skipsocket(1,try(tp:check("2..")))
-end
-function methods.mail(self,from)
- local try=self.try
- local tp=self.tp
- try(tp:command("MAIL","FROM:"..from))
- return try(tp:check("2.."))
-end
-function methods.rcpt(self,to)
- local try=self.try
- local tp=self.tp
- try(tp:command("RCPT","TO:"..to))
- return try(tp:check("2.."))
-end
-function methods.data(self,src,step)
- local try=self.try
- local tp=self.tp
- try(tp:command("DATA"))
- try(tp:check("3.."))
- try(tp:source(src,step))
- try(tp:send("\r\n.\r\n"))
- return try(tp:check("2.."))
-end
-function methods.quit(self)
- local try=self.try
- local tp=self.tp
- try(tp:command("QUIT"))
- return try(tp:check("2.."))
-end
-function methods.close(self)
- return self.tp:close()
-end
-function methods.login(self,user,password)
- local try=self.try
- local tp=self.tp
- try(tp:command("AUTH","LOGIN"))
- try(tp:check("3.."))
- try(tp:send(mimeb64(user).."\r\n"))
- try(tp:check("3.."))
- try(tp:send(mimeb64(password).."\r\n"))
- return try(tp:check("2.."))
-end
-function methods.plain(self,user,password)
- local try=self.try
- local tp=self.tp
- local auth="PLAIN "..mimeb64("\0"..user.."\0"..password)
- try(tp:command("AUTH",auth))
- return try(tp:check("2.."))
-end
-function methods.auth(self,user,password,ext)
- if not user or not password then
- return 1
- end
- local try=self.try
- if find(ext,"AUTH[^\n]+LOGIN") then
- return self:login(user,password)
- elseif find(ext,"AUTH[^\n]+PLAIN") then
- return self:plain(user,password)
- else
- try(nil,"authentication not supported")
- end
-end
-function methods.send(self,mail)
- self:mail(mail.from)
- local receipt=mail.rcpt
- if type(receipt)=="table" then
- for i=1,#receipt do
- self:rcpt(receipt[i])
- end
- elseif receipt then
- self:rcpt(receipt)
- end
- self:data(ltn12.source.chain(mail.source,mimestuff()),mail.step)
-end
-local function opensmtp(self,server,port,create)
- if not server or server=="" then
- server=smtp.SERVER
- end
- if not port or port=="" then
- port=smtp.PORT
- end
- local s={
- tp=trysocket(tp.connect(server,port,smtp.TIMEOUT,create)),
- try=newtrysocket(function()
- s:close()
- end),
- }
- setmetatable(s,mt)
- return s
-end
-smtp.open=opensmtp
-local nofboundaries=0
-local function newboundary()
- nofboundaries=nofboundaries+1
- return format('%s%05d==%05u',osdate('%d%m%Y%H%M%S'),random(0,99999),nofboundaries)
-end
-local send_message
-local function send_headers(headers)
- yieldcoroutine(normalizeheaders(headers))
-end
-local function send_multipart(message)
- local boundary=newboundary()
- local headers=lowerheaders(message.headers)
- local body=message.body
- local preamble=body.preamble
- local epilogue=body.epilogue
- local content=headers['content-type'] or 'multipart/mixed'
- headers['content-type']=content..'; boundary="'..boundary..'"'
- send_headers(headers)
- if preamble then
- yieldcoroutine(preamble)
- yieldcoroutine("\r\n")
- end
- for i=1,#body do
- yieldcoroutine("\r\n--"..boundary.."\r\n")
- send_message(body[i])
- end
- yieldcoroutine("\r\n--"..boundary.."--\r\n\r\n")
- if epilogue then
- yieldcoroutine(epilogue)
- yieldcoroutine("\r\n")
- end
-end
-local default_content_type='text/plain; charset="UTF-8"'
-local function send_source(message)
- local headers=lowerheaders(message.headers)
- if not headers['content-type'] then
- headers['content-type']=default_content_type
- end
- send_headers(headers)
- local getchunk=message.body
- while true do
- local chunk,err=getchunk()
- if err then
- yieldcoroutine(nil,err)
- elseif chunk then
- yieldcoroutine(chunk)
- else
- break
- end
- end
-end
-local function send_string(message)
- local headers=lowerheaders(message.headers)
- if not headers['content-type'] then
- headers['content-type']=default_content_type
- end
- send_headers(headers)
- yieldcoroutine(message.body)
-end
-function send_message(message)
- local body=message.body
- if type(body)=="table" then
- send_multipart(message)
- elseif type(body)=="function" then
- send_source(message)
- else
- send_string(message)
- end
-end
-local function adjust_headers(message)
- local headers=lowerheaders(message.headers)
- if not headers["date"] then
- headers["date"]=osdate("!%a, %d %b %Y %H:%M:%S ")..(message.zone or smtp.ZONE)
- end
- if not headers["x-mailer"] then
- headers["x-mailer"]=socket._VERSION
- end
- headers["mime-version"]="1.0"
- return headers
-end
-function smtp.message(message)
- message.headers=adjust_headers(message)
- local action=createcoroutine(function()
- send_message(message)
- end)
- return function()
- local ret,a,b=resumecoroutine(action)
- if ret then
- return a,b
- else
- return nil,a
- end
- end
-end
-smtp.send=protectsocket(function(mail)
- local snd=opensmtp(smtp,mail.server,mail.port,mail.create)
- local ext=snd:greet(mail.domain)
- snd:auth(mail.user,mail.password,ext)
- snd:send(mail)
- snd:quit()
- return snd:close()
-end)
-package.loaded["socket.smtp"]=smtp
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-set"] = package.loaded["trac-set"] or true
-
--- original size: 13901, stripped down to: 9175
-
-if not modules then modules={} end modules ['trac-set']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,next,tostring,tonumber=type,next,tostring,tonumber
-local print=print
-local concat,sortedhash=table.concat,table.sortedhash
-local formatters,find,lower,gsub,topattern=string.formatters,string.find,string.lower,string.gsub,string.topattern
-local is_boolean=string.is_boolean
-local settings_to_hash=utilities.parsers.settings_to_hash
-local allocate=utilities.storage.allocate
-utilities=utilities or {}
-local utilities=utilities
-local setters=utilities.setters or {}
-utilities.setters=setters
-local data={}
-local trace_initialize=false
-local frozen=true
-local function initialize_setter(filename,name,values)
- local setter=data[name]
- if setter then
- local data=setter.data
- if data then
- for key,newvalue in sortedhash(values) do
- local newvalue=is_boolean(newvalue,newvalue,true)
- local functions=data[key]
- if functions then
- local oldvalue=functions.value
- if functions.frozen then
- if trace_initialize then
- setter.report("%s: %a is %s to %a",filename,key,"frozen",oldvalue)
- end
- elseif #functions>0 and not oldvalue then
- if trace_initialize then
- setter.report("%s: %a is %s to %a",filename,key,"set",newvalue)
- end
- for i=1,#functions do
- functions[i](newvalue)
- end
- functions.value=newvalue
- functions.frozen=functions.frozen or frozen
- else
- if trace_initialize then
- setter.report("%s: %a is %s as %a",filename,key,"kept",oldvalue)
- end
- end
- else
- functions={ default=newvalue,frozen=frozen }
- data[key]=functions
- if trace_initialize then
- setter.report("%s: %a is %s to %a",filename,key,"defaulted",newvalue)
- end
- end
- end
- return true
- end
- end
-end
-local function set(t,what,newvalue)
- local data=t.data
- if data and not data.frozen then
- local done=t.done
- if type(what)=="string" then
- what=settings_to_hash(what)
- end
- if type(what)~="table" then
- return
- end
- if not done then
- done={}
- t.done=done
- end
- for w,value in sortedhash(what) do
- if value=="" then
- value=newvalue
- elseif not value then
- value=false
- else
- value=is_boolean(value,value,true)
- end
- w=topattern(w,true,true)
- for name,functions in sortedhash(data) do
- if done[name] then
- elseif find(name,w) then
- done[name]=true
- for i=1,#functions do
- functions[i](value)
- end
- functions.value=value
- end
- end
- end
- end
-end
-local function reset(t)
- local data=t.data
- if data and not data.frozen then
- for name,functions in sortedthash(data) do
- for i=1,#functions do
- functions[i](false)
- end
- functions.value=false
- end
- end
-end
-local function enable(t,what)
- set(t,what,true)
-end
-local function disable(t,what)
- local data=t.data
- if not what or what=="" then
- t.done={}
- reset(t)
- else
- set(t,what,false)
- end
-end
-local function register_setter(t,what,...)
- local data=t.data
- what=lower(what)
- local functions=data[what]
- if not functions then
- functions={}
- data[what]=functions
- if trace_initialize then
- t.report("defining %a",what)
- end
- end
- local default=functions.default
- for i=1,select("#",...) do
- local fnc=select(i,...)
- local typ=type(fnc)
- if typ=="string" then
- if trace_initialize then
- t.report("coupling %a to %a",what,fnc)
- end
- local s=fnc
- fnc=function(value) set(t,s,value) end
- elseif typ~="function" then
- fnc=nil
- end
- if fnc then
- functions[#functions+1]=fnc
- local value=functions.value or default
- if value~=nil then
- fnc(value)
- functions.value=value
- end
- end
- end
- return false
-end
-local function enable_setter(t,what)
- local e=t.enable
- t.enable,t.done=enable,{}
- set(t,what,true)
- enable(t,what)
- t.enable,t.done=e,{}
-end
-local function disable_setter(t,what)
- local e=t.disable
- t.disable,t.done=disable,{}
- disable(t,what)
- t.disable,t.done=e,{}
-end
-local function reset_setter(t)
- t.done={}
- reset(t)
-end
-local function list_setter(t)
- local list=table.sortedkeys(t.data)
- local user,system={},{}
- for l=1,#list do
- local what=list[l]
- if find(what,"^%*") then
- system[#system+1]=what
- else
- user[#user+1]=what
- end
- end
- return user,system
-end
-local function show_setter(t)
- local list=list_setter(t)
- t.report()
- for k=1,#list do
- local name=list[k]
- local functions=t.data[name]
- if functions then
- local value=functions.value
- local default=functions.default
- local modules=#functions
- if default==nil then
- default="unset"
- elseif type(default)=="table" then
- default=concat(default,"|")
- else
- default=tostring(default)
- end
- if value==nil then
- value="unset"
- elseif type(value)=="table" then
- value=concat(value,"|")
- else
- value=tostring(value)
- end
- t.report(name)
- t.report(" modules : %i",modules)
- t.report(" default : %s",default)
- t.report(" value : %s",value)
- t.report()
- end
- end
-end
-function setters.report(setter,fmt,...)
- if fmt then
- print(formatters["%-15s : %s"](setter.name,formatters[fmt](...)))
- else
- print("")
- end
-end
-local function setter_default(setter,name)
- local d=setter.data[name]
- return d and d.default
-end
-local function setter_value(setter,name)
- local d=setter.data[name]
- return d and (d.value or d.default)
-end
-local function new_setter(name)
- local setter
- setter={
- data=allocate(),
- name=name,
- report=function(...) setters.report (setter,...) end,
- enable=function(...) enable_setter (setter,...) end,
- disable=function(...) disable_setter (setter,...) end,
- reset=function(...) reset_setter (setter,...) end,
- register=function(...) register_setter(setter,...) end,
- list=function(...) return list_setter (setter,...) end,
- show=function(...) show_setter (setter,...) end,
- default=function(...) return setter_default (setter,...) end,
- value=function(...) return setter_value (setter,...) end,
- }
- data[name]=setter
- return setter
-end
-setters.enable=enable_setter
-setters.disable=disable_setter
-setters.register=register_setter
-setters.list=list_setter
-setters.show=show_setter
-setters.reset=reset_setter
-setters.new=new_setter
-setters.initialize=initialize_setter
-trackers=new_setter("trackers")
-directives=new_setter("directives")
-experiments=new_setter("experiments")
-local t_enable,t_disable=trackers .enable,trackers .disable
-local d_enable,d_disable=directives .enable,directives .disable
-local e_enable,e_disable=experiments.enable,experiments.disable
-local trace_directives=false local trace_directives=false trackers.register("system.directives",function(v) trace_directives=v end)
-local trace_experiments=false local trace_experiments=false trackers.register("system.experiments",function(v) trace_experiments=v end)
-function directives.enable(...)
- if trace_directives then
- directives.report("enabling: % t",{...})
- end
- d_enable(...)
-end
-function directives.disable(...)
- if trace_directives then
- directives.report("disabling: % t",{...})
- end
- d_disable(...)
-end
-function experiments.enable(...)
- if trace_experiments then
- experiments.report("enabling: % t",{...})
- end
- e_enable(...)
-end
-function experiments.disable(...)
- if trace_experiments then
- experiments.report("disabling: % t",{...})
- end
- e_disable(...)
-end
-directives.register("system.nostatistics",function(v)
- if statistics then
- statistics.enable=not v
- else
- end
-end)
-directives.register("system.nolibraries",function(v)
- if libraries then
- libraries=nil
- else
- end
-end)
-if environment then
- local engineflags=environment.engineflags
- if engineflags then
- local list=engineflags["c:trackers"] or engineflags["trackers"]
- if type(list)=="string" then
- initialize_setter("commandline flags","trackers",settings_to_hash(list))
- end
- local list=engineflags["c:directives"] or engineflags["directives"]
- if type(list)=="string" then
- initialize_setter("commandline flags","directives",settings_to_hash(list))
- end
- end
-end
-if texconfig then
- local function set(k,v)
- v=tonumber(v)
- if v then
- texconfig[k]=v
- end
- end
- directives.register("luatex.expanddepth",function(v) set("expand_depth",v) end)
- directives.register("luatex.hashextra",function(v) set("hash_extra",v) end)
- directives.register("luatex.nestsize",function(v) set("nest_size",v) end)
- directives.register("luatex.maxinopen",function(v) set("max_in_open",v) end)
- directives.register("luatex.maxprintline",function(v) set("max_print_line",v) end)
- directives.register("luatex.maxstrings",function(v) set("max_strings",v) end)
- directives.register("luatex.paramsize",function(v) set("param_size",v) end)
- directives.register("luatex.savesize",function(v) set("save_size",v) end)
- directives.register("luatex.stacksize",function(v) set("stack_size",v) end)
-end
-local data=table.setmetatableindex("table")
-updaters={
- register=function(what,f)
- local d=data[what]
- d[#d+1]=f
- end,
- apply=function(what,...)
- local d=data[what]
- for i=1,#d do
- d[i](...)
- end
- end,
-}
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-log"] = package.loaded["trac-log"] or true
-
--- original size: 16017, stripped down to: 11045
-
-if not modules then modules={} end modules ['trac-log']={
- version=1.001,
- comment="companion to trac-log.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local next,type,select,print=next,type,select,print
-local format,gmatch,find=string.format,string.gmatch,string.find
-local concat,insert,remove=table.concat,table.insert,table.remove
-local topattern=string.topattern
-local utfchar=utf.char
-local datetime=os.date
-local openfile=io.open
-local write_nl=print
-local write=io.write
-local setmetatableindex=table.setmetatableindex
-local formatters=string.formatters
-local settings_to_hash=utilities.parsers.settings_to_hash
-local sortedkeys=table.sortedkeys
-local variant="default"
-logs=logs or {}
-local logs=logs
-local moreinfo=[[
-More information about ConTeXt and the tools that come with it can be found at:
-]].."\n"..[[
-maillist : ntg-context@ntg.nl / http://www.ntg.nl/mailman/listinfo/ntg-context
-webpage : http://www.pragma-ade.nl / http://tex.aanhet.net
-wiki : http://contextgarden.net
-]]
-formatters.add (
- formatters,"unichr",
- [["U+" .. format("%%05X",%s) .. " (" .. utfchar(%s) .. ")"]]
-)
-formatters.add (
- formatters,"chruni",
- [[utfchar(%s) .. " (U+" .. format("%%05X",%s) .. ")"]]
-)
-local function ignore() end
-setmetatableindex(logs,function(t,k) t[k]=ignore;return ignore end)
-local report,subreport,status,settarget,setformats,settranslations
-local direct,subdirect,writer,pushtarget,poptarget,setlogfile,settimedlog,setprocessor,setformatters,newline
-local function ansisupported(specification)
- if specification~="ansi" and specification~="ansilog" then
- return false
- elseif os and os.enableansi then
- return os.enableansi()
- else
- return false
- end
-end
-do
- local report_yes,subreport_yes,status_yes
- local report_nop,subreport_nop,status_nop
- local variants={
- default={
- formats={
- report_yes=formatters["%-15s | %s"],
- report_nop=formatters["%-15s |"],
- subreport_yes=formatters["%-15s | %s | %s"],
- subreport_nop=formatters["%-15s | %s |"],
- status_yes=formatters["%-15s : %s\n"],
- status_nop=formatters["%-15s :\n"],
- },
- },
- ansi={
- formats={
- report_yes=formatters["%-15s | %s"],
- report_nop=formatters["%-15s |"],
- subreport_yes=formatters["%-15s | %s | %s"],
- subreport_nop=formatters["%-15s | %s |"],
- status_yes=formatters["%-15s : %s\n"],
- status_nop=formatters["%-15s :\n"],
- },
- },
- }
- logs.flush=ignore
- writer=function(s)
- write_nl(s)
- end
- newline=function()
- write_nl("\n")
- end
- report=function(a,b,c,...)
- if c then
- write_nl(report_yes(a,formatters[b](c,...)))
- elseif b then
- write_nl(report_yes(a,b))
- elseif a then
- write_nl(report_nop(a))
- else
- write_nl("")
- end
- end
- subreport=function(a,sub,b,c,...)
- if c then
- write_nl(subreport_yes(a,sub,formatters[b](c,...)))
- elseif b then
- write_nl(subreport_yes(a,sub,b))
- elseif a then
- write_nl(subreport_nop(a,sub))
- else
- write_nl("")
- end
- end
- status=function(a,b,c,...)
- if c then
- write_nl(status_yes(a,formatters[b](c,...)))
- elseif b then
- write_nl(status_yes(a,b))
- elseif a then
- write_nl(status_nop(a))
- else
- write_nl("\n")
- end
- end
- direct=ignore
- subdirect=ignore
- settarget=ignore
- pushtarget=ignore
- poptarget=ignore
- setformats=ignore
- settranslations=ignore
- setprocessor=function(f)
- local writeline=write_nl
- write_nl=function(s)
- writeline(f(s))
- end
- end
- setformatters=function(specification)
- local f=nil
- local d=variants.default
- if specification then
- if type(specification)=="table" then
- f=specification.formats or specification
- else
- if not ansisupported(specification) then
- specification="default"
- end
- local v=variants[specification]
- if v then
- f=v.formats
- end
- end
- end
- if f then
- d=d.formats
- else
- f=d.formats
- d=f
- end
- setmetatableindex(f,d)
- report_yes=f.report_yes
- report_nop=f.report_nop
- subreport_yes=f.subreport_yes
- subreport_nop=f.subreport_nop
- status_yes=f.status_yes
- status_nop=f.status_nop
- end
- setformatters(variant)
- setlogfile=function(name,keepopen)
- if name and name~="" then
- local localtime=os.localtime
- local writeline=write_nl
- if keepopen then
- local f=io.open(name,"ab")
- write_nl=function(s)
- writeline(s)
- f:write(localtime()," | ",s,"\n")
- end
- else
- write_nl=function(s)
- writeline(s)
- local f=io.open(name,"ab")
- f:write(localtime()," | ",s,"\n")
- f:close()
- end
- end
- end
- setlogfile=ignore
- end
- settimedlog=function()
- local localtime=os.localtime
- local writeline=write_nl
- write_nl=function(s)
- writeline(localtime().." | "..s)
- end
- settimedlog=ignore
- end
-end
-logs.report=report
-logs.subreport=subreport
-logs.status=status
-logs.settarget=settarget
-logs.pushtarget=pushtarget
-logs.poptarget=poptarget
-logs.setformats=setformats
-logs.settranslations=settranslations
-logs.setlogfile=setlogfile
-logs.settimedlog=settimedlog
-logs.setprocessor=setprocessor
-logs.setformatters=setformatters
-logs.direct=direct
-logs.subdirect=subdirect
-logs.writer=writer
-logs.newline=newline
-local data={}
-local states=nil
-local force=false
-function logs.reporter(category,subcategory)
- local logger=data[category]
- if not logger then
- local state=states==true
- if not state and type(states)=="table" then
- for c,_ in next,states do
- if find(category,c) then
- state=true
- break
- end
- end
- end
- logger={
- reporters={},
- state=state,
- }
- data[category]=logger
- end
- local reporter=logger.reporters[subcategory or "default"]
- if not reporter then
- if subcategory then
- reporter=function(...)
- if force or not logger.state then
- subreport(category,subcategory,...)
- end
- end
- logger.reporters[subcategory]=reporter
- else
- local tag=category
- reporter=function(...)
- if force or not logger.state then
- report(category,...)
- end
- end
- logger.reporters.default=reporter
- end
- end
- return reporter
-end
-logs.new=logs.reporter
-local ctxreport=logs.writer
-function logs.setmessenger(m)
- ctxreport=m
-end
-function logs.messenger(category,subcategory)
- if subcategory then
- return function(...)
- ctxreport(subdirect(category,subcategory,...))
- end
- else
- return function(...)
- ctxreport(direct(category,...))
- end
- end
-end
-local function setblocked(category,value)
- if category==true or category=="all" then
- category,value="*",true
- elseif category==false then
- category,value="*",false
- elseif value==nil then
- value=true
- end
- if category=="*" then
- states=value
- for k,v in next,data do
- v.state=value
- end
- else
- alllocked=false
- states=settings_to_hash(category,type(states)=="table" and states or nil)
- for c in next,states do
- local v=data[c]
- if v then
- v.state=value
- else
- c=topattern(c,true,true)
- for k,v in next,data do
- if find(k,c) then
- v.state=value
- end
- end
- end
- end
- end
-end
-function logs.disable(category,value)
- setblocked(category,value==nil and true or value)
-end
-function logs.enable(category)
- setblocked(category,false)
-end
-function logs.categories()
- return sortedkeys(data)
-end
-function logs.show()
- local n,c,s,max=0,0,0,0
- for category,v in table.sortedpairs(data) do
- n=n+1
- local state=v.state
- local reporters=v.reporters
- local nc=#category
- if nc>c then
- c=nc
- end
- for subcategory,_ in next,reporters do
- local ns=#subcategory
- if ns>c then
- s=ns
- end
- local m=nc+ns
- if m>max then
- max=m
- end
- end
- local subcategories=concat(sortedkeys(reporters),", ")
- if state==true then
- state="disabled"
- elseif state==false then
- state="enabled"
- else
- state="unknown"
- end
- report("logging","category %a, subcategories %a, state %a",category,subcategories,state)
- end
- report("logging","categories: %s, max category: %s, max subcategory: %s, max combined: %s",n,c,s,max)
-end
-local delayed_reporters={}
-setmetatableindex(delayed_reporters,function(t,k)
- local v=logs.reporter(k.name)
- t[k]=v
- return v
-end)
-function utilities.setters.report(setter,...)
- delayed_reporters[setter](...)
-end
-directives.register("logs.blocked",function(v)
- setblocked(v,true)
-end)
-directives.register("logs.target",function(v)
- settarget(v)
-end)
-local nesting=0
-local verbose=false
-local hasscheme=url.hasscheme
-local simple=logs.reporter("comment")
-logs.simple=simple
-logs.simpleline=simple
-logs.setprogram=ignore
-logs.extendbanner=ignore
-logs.reportlines=ignore
-logs.reportbanner=ignore
-logs.reportline=ignore
-logs.simplelines=ignore
-logs.help=ignore
-local Carg,C,lpegmatch=lpeg.Carg,lpeg.C,lpeg.match
-local p_newline=lpeg.patterns.newline
-local linewise=(
- Carg(1)*C((1-p_newline)^1)/function(t,s) t.report(s) end+Carg(1)*p_newline^2/function(t) t.report() end+p_newline
-)^1
-local function reportlines(t,str)
- if str then
- lpegmatch(linewise,str,1,t)
- end
-end
-local function reportbanner(t)
- local banner=t.banner
- if banner then
- t.report(banner)
- t.report()
- end
-end
-local function reportversion(t)
- local banner=t.banner
- if banner then
- t.report(banner)
- end
-end
-local function reporthelp(t,...)
- local helpinfo=t.helpinfo
- if type(helpinfo)=="string" then
- reportlines(t,helpinfo)
- elseif type(helpinfo)=="table" then
- for i=1,select("#",...) do
- reportlines(t,t.helpinfo[select(i,...)])
- if i<n then
- t.report()
- end
- end
- end
-end
-local function reportinfo(t)
- t.report()
- reportlines(t,t.moreinfo)
-end
-local function reportexport(t,method)
- report(t.helpinfo)
-end
-local reporters={
- lines=reportlines,
- banner=reportbanner,
- version=reportversion,
- help=reporthelp,
- info=reportinfo,
- export=reportexport,
-}
-local exporters={
-}
-logs.reporters=reporters
-logs.exporters=exporters
-function logs.application(t)
- local arguments=environment and environment.arguments
- if arguments then
- local ansi=arguments.ansi or arguments.ansilog
- if ansi then
- logs.setformatters(arguments.ansi and "ansi" or "ansilog")
- end
- end
- t.name=t.name or "unknown"
- t.banner=t.banner
- t.moreinfo=moreinfo
- t.report=logs.reporter(t.name)
- t.help=function(...)
- reporters.banner(t)
- reporters.help(t,...)
- reporters.info(t)
- end
- t.export=function(...)
- reporters.export(t,...)
- end
- t.identify=function()
- reporters.banner(t)
- end
- t.version=function()
- reporters.version(t)
- end
- return t
-end
-local f_syslog=formatters["%s %s => %s => %s => %s\r"]
-function logs.system(whereto,process,jobname,category,fmt,arg,...)
- local message=f_syslog(datetime("%d/%m/%y %H:%m:%S"),process,jobname,category,arg==nil and fmt or format(fmt,arg,...))
- for i=1,10 do
- local f=openfile(whereto,"a")
- if f then
- f:write(message)
- f:close()
- break
- else
- sleep(0.1)
- end
- end
-end
-local report_system=logs.reporter("system","logs")
-if utilities then
- utilities.report=report_system
-end
-if package.helpers.report then
- package.helpers.report=logs.reporter("package loader")
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-inf"] = package.loaded["trac-inf"] or true
-
--- original size: 9740, stripped down to: 7296
-
-if not modules then modules={} end modules ['trac-inf']={
- version=1.001,
- comment="companion to trac-inf.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,tonumber,select=type,tonumber,select
-local format,lower,find=string.format,string.lower,string.find
-local concat=table.concat
-local clock=os.gettimeofday or os.clock
-local setmetatableindex=table.setmetatableindex
-local serialize=table.serialize
-local formatters=string.formatters
-statistics=statistics or {}
-local statistics=statistics
-statistics.enable=true
-statistics.threshold=0.01
-local statusinfo,n,registered,timers={},0,{},{}
-setmetatableindex(timers,function(t,k)
- local v={ timing=0,loadtime=0,offset=0 }
- t[k]=v
- return v
-end)
-local function hastiming(instance)
- return instance and timers[instance]
-end
-local function resettiming(instance)
- timers[instance or "notimer"]={ timing=0,loadtime=0,offset=0 }
-end
-local ticks=clock
-local seconds=function(n) return n or 0 end
-if os.type~="windows" then
-elseif lua.getpreciseticks then
- ticks=lua.getpreciseticks
- seconds=lua.getpreciseseconds
-elseif FFISUPPORTED then
- local okay,kernel=pcall(ffi.load,"kernel32")
- if kernel then
- local tonumber=ffi.number or tonumber
- ffi.cdef[[
- int QueryPerformanceFrequency(int64_t *lpFrequency);
- int QueryPerformanceCounter(int64_t *lpPerformanceCount);
- ]]
- local target=ffi.new("__int64[1]")
- ticks=function()
- if kernel.QueryPerformanceCounter(target)==1 then
- return tonumber(target[0])
- else
- return 0
- end
- end
- local target=ffi.new("__int64[1]")
- seconds=function(ticks)
- if kernel.QueryPerformanceFrequency(target)==1 then
- return ticks/tonumber(target[0])
- else
- return 0
- end
- end
- end
-else
-end
-local function starttiming(instance,reset)
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if reset then
- it=0
- timer.loadtime=0
- end
- if it==0 then
- timer.starttime=ticks()
- if not timer.loadtime then
- timer.loadtime=0
- end
- end
- timer.timing=it+1
-end
-local function stoptiming(instance)
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if it>1 then
- timer.timing=it-1
- else
- local starttime=timer.starttime
- if starttime and starttime>0 then
- local stoptime=ticks()
- local loadtime=stoptime-starttime
- timer.stoptime=stoptime
- timer.loadtime=timer.loadtime+loadtime
- timer.timing=0
- timer.starttime=0
- end
- end
-end
-local function benchmarktimer(instance)
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if it>1 then
- timer.timing=it-1
- else
- local starttime=timer.starttime
- if starttime and starttime>0 then
- timer.offset=ticks()-starttime
- else
- timer.offset=0
- end
- end
-end
-local function elapsed(instance)
- if type(instance)=="number" then
- return instance
- else
- local timer=timers[instance or "notimer"]
- return timer and seconds(timer.loadtime-2*(timer.offset or 0)) or 0
- end
-end
-local function currenttime(instance)
- if type(instance)=="number" then
- return instance
- else
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if it>1 then
- else
- local starttime=timer.starttime
- if starttime and starttime>0 then
- return seconds(timer.loadtime+ticks()-starttime-2*(timer.offset or 0))
- end
- end
- return 0
- end
-end
-local function elapsedtime(instance)
- return format("%0.3f",elapsed(instance))
-end
-local function elapsedindeed(instance)
- return elapsed(instance)>statistics.threshold
-end
-local function elapsedseconds(instance,rest)
- if elapsedindeed(instance) then
- return format("%0.3f seconds %s",elapsed(instance),rest or "")
- end
-end
-statistics.hastiming=hastiming
-statistics.resettiming=resettiming
-statistics.starttiming=starttiming
-statistics.stoptiming=stoptiming
-statistics.currenttime=currenttime
-statistics.elapsed=elapsed
-statistics.elapsedtime=elapsedtime
-statistics.elapsedindeed=elapsedindeed
-statistics.elapsedseconds=elapsedseconds
-statistics.benchmarktimer=benchmarktimer
-function statistics.register(tag,fnc)
- if statistics.enable and type(fnc)=="function" then
- local rt=registered[tag] or (#statusinfo+1)
- statusinfo[rt]={ tag,fnc }
- registered[tag]=rt
- if #tag>n then n=#tag end
- end
-end
-local report=logs.reporter("mkiv lua stats")
-function statistics.show()
- if statistics.enable then
- local register=statistics.register
- register("used platform",function()
- return format("%s, type: %s, binary subtree: %s",
- os.platform or "unknown",os.type or "unknown",environment.texos or "unknown")
- end)
- register("used engine",function()
- return format("%s version: %s, functionality level: %s, banner: %s",
- LUATEXENGINE,LUATEXVERSION,LUATEXFUNCTIONALITY,lower(status.banner))
- end)
- register("used hash slots",function()
- return format("%s of %s + %s",status.cs_count,status.hash_size,status.hash_extra)
- end)
- register("callbacks",statistics.callbacks)
- if JITSUPPORTED then
- local jitstatus=jit.status
- if jitstatus then
- local jitstatus={ jitstatus() }
- if jitstatus[1] then
- register("luajit options",concat(jitstatus," ",2))
- end
- end
- end
- register("lua properties",function()
- local hash=2^status.luatex_hashchars
- local mask=load([[τεχ = 1]]) and "utf" or "ascii"
- return format("engine: %s %s, used memory: %s, hash chars: min(%i,40), symbol mask: %s (%s)",
- jit and "luajit" or "lua",LUAVERSION,statistics.memused(),hash,mask,mask=="utf" and "τεχ" or "tex")
- end)
- register("runtime",statistics.runtime)
- logs.newline()
- for i=1,#statusinfo do
- local s=statusinfo[i]
- local r=s[2]()
- if r then
- report("%s: %s",s[1],r)
- end
- end
- statistics.enable=false
- end
-end
-function statistics.memused()
- local round=math.round or math.floor
- return format("%s MB, ctx: %s MB, max: %s MB",
- round(collectgarbage("count")/1000),
- round(status.luastate_bytes/1000000),
- status.luastate_bytes_max and round(status.luastate_bytes_max/1000000) or "unknown"
- )
-end
-starttiming(statistics)
-function statistics.formatruntime(runtime)
- return format("%s seconds",runtime)
-end
-function statistics.runtime()
- stoptiming(statistics)
- local runtime=lua.getruntime and lua.getruntime() or elapsedtime(statistics)
- return statistics.formatruntime(runtime)
-end
-local report=logs.reporter("system")
-function statistics.timed(action,all)
- starttiming("run")
- action()
- stoptiming("run")
- local runtime=tonumber(elapsedtime("run"))
- if all then
- local alltime=tonumber(lua.getruntime and lua.getruntime() or elapsedtime(statistics))
- if alltime and alltime>0 then
- report("total runtime: %0.3f seconds of %0.3f seconds",runtime,alltime)
- return
- end
- end
- report("total runtime: %0.3f seconds",runtime)
-end
-function statistics.tracefunction(base,tag,...)
- for i=1,select("#",...) do
- local name=select(i,...)
- local stat={}
- local func=base[name]
- setmetatableindex(stat,function(t,k) t[k]=0 return 0 end)
- base[name]=function(n,k,v) stat[k]=stat[k]+1 return func(n,k,v) end
- statistics.register(formatters["%s.%s"](tag,name),function() return serialize(stat,"calls") end)
- end
-end
-function status.getreadstate()
- return {
- filename=status.filename or "?",
- linenumber=status.linenumber or 0,
- iocode=status.inputid or 0,
- }
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-pro"] = package.loaded["trac-pro"] or true
-
--- original size: 5841, stripped down to: 3352
-
-if not modules then modules={} end modules ['trac-pro']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local getmetatable,setmetatable,rawset,type,next=getmetatable,setmetatable,rawset,type,next
-local trace_namespaces=false trackers.register("system.namespaces",function(v) trace_namespaces=v end)
-local report_system=logs.reporter("system","protection")
-namespaces=namespaces or {}
-local namespaces=namespaces
-local registered={}
-local function report_index(k,name)
- if trace_namespaces then
- report_system("reference to %a in protected namespace %a: %s",k,name)
- debugger.showtraceback(report_system)
- else
- report_system("reference to %a in protected namespace %a",k,name)
- end
-end
-local function report_newindex(k,name)
- if trace_namespaces then
- report_system("assignment to %a in protected namespace %a: %s",k,name)
- debugger.showtraceback(report_system)
- else
- report_system("assignment to %a in protected namespace %a",k,name)
- end
-end
-local function register(name)
- local data=name=="global" and _G or _G[name]
- if not data then
- return
- end
- registered[name]=data
- local m=getmetatable(data)
- if not m then
- m={}
- setmetatable(data,m)
- end
- local index,newindex={},{}
- m.__saved__index=m.__index
- m.__no__index=function(t,k)
- if not index[k] then
- index[k]=true
- report_index(k,name)
- end
- return nil
- end
- m.__saved__newindex=m.__newindex
- m.__no__newindex=function(t,k,v)
- if not newindex[k] then
- newindex[k]=true
- report_newindex(k,name)
- end
- rawset(t,k,v)
- end
- m.__protection__depth=0
-end
-local function private(name)
- local data=registered[name]
- if not data then
- data=_G[name]
- if not data then
- data={}
- _G[name]=data
- end
- register(name)
- end
- return data
-end
-local function protect(name)
- local data=registered[name]
- if not data then
- return
- end
- local m=getmetatable(data)
- local pd=m.__protection__depth
- if pd>0 then
- m.__protection__depth=pd+1
- else
- m.__save_d_index,m.__saved__newindex=m.__index,m.__newindex
- m.__index,m.__newindex=m.__no__index,m.__no__newindex
- m.__protection__depth=1
- end
-end
-local function unprotect(name)
- local data=registered[name]
- if not data then
- return
- end
- local m=getmetatable(data)
- local pd=m.__protection__depth
- if pd>1 then
- m.__protection__depth=pd-1
- else
- m.__index,m.__newindex=m.__saved__index,m.__saved__newindex
- m.__protection__depth=0
- end
-end
-local function protectall()
- for name,_ in next,registered do
- if name~="global" then
- protect(name)
- end
- end
-end
-local function unprotectall()
- for name,_ in next,registered do
- if name~="global" then
- unprotect(name)
- end
- end
-end
-namespaces.register=register
-namespaces.private=private
-namespaces.protect=protect
-namespaces.unprotect=unprotect
-namespaces.protectall=protectall
-namespaces.unprotectall=unprotectall
-namespaces.private("namespaces") registered={} register("global")
-directives.register("system.protect",function(v)
- if v then
- protectall()
- else
- unprotectall()
- end
-end)
-directives.register("system.checkglobals",function(v)
- if v then
- report_system("enabling global namespace guard")
- protect("global")
- else
- report_system("disabling global namespace guard")
- unprotect("global")
- end
-end)
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-lua"] = package.loaded["util-lua"] or true
-
--- original size: 7149, stripped down to: 4997
-
-if not modules then modules={} end modules ['util-lua']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- comment="the strip code is written by Peter Cawley",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local rep,sub,byte,dump,format=string.rep,string.sub,string.byte,string.dump,string.format
-local load,loadfile,type,collectgarbage=load,loadfile,type,collectgarbage
-utilities=utilities or {}
-utilities.lua=utilities.lua or {}
-local luautilities=utilities.lua
-local report_lua=logs.reporter("system","lua")
-local report_mem=logs.reporter("system","lua memory")
-local tracestripping=false
-local tracememory=false
-luautilities.stripcode=true
-luautilities.alwaysstripcode=false
-luautilities.nofstrippedchunks=0
-luautilities.nofstrippedbytes=0
-local strippedchunks={}
-luautilities.strippedchunks=strippedchunks
-if not LUATEXENGINE then
- LUATEXENGINE=status.luatex_engine and string.lower(status.luatex_engine)
- JITSUPPORTED=LUATEXENGINE=="luajittex" or jit
- CONTEXTLMTXMODE=CONTEXTLMTXMODE or (LUATEXENGINE=="luametatex" and 1) or 0
-end
-luautilities.suffixes={
- tma="tma",
- tmc=(CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and "tmd") or (jit and "tmb") or "tmc",
- lua="lua",
- luc=(CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and "lud") or (jit and "lub") or "luc",
- lui="lui",
- luv="luv",
- luj="luj",
- tua="tua",
- tuc=(CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and "tud") or (jit and "tub") or "tuc",
-}
-local function register(name)
- if tracestripping then
- report_lua("stripped bytecode from %a",name or "unknown")
- end
- strippedchunks[#strippedchunks+1]=name
- luautilities.nofstrippedchunks=luautilities.nofstrippedchunks+1
-end
-local function stupidcompile(luafile,lucfile,strip)
- local code=io.loaddata(luafile)
- if code and code~="" then
- code=load(code)
- if code then
- code=dump(code,strip and luautilities.stripcode or luautilities.alwaysstripcode)
- if code and code~="" then
- register(name)
- io.savedata(lucfile,code)
- return true,0
- end
- else
- report_lua("fatal error %a in file %a",1,luafile)
- end
- else
- report_lua("fatal error %a in file %a",2,luafile)
- end
- return false,0
-end
-function luautilities.loadedluacode(fullname,forcestrip,name,macros)
- name=name or fullname
- if macros then
- macros=lua.macros
- end
- local code,message
- if macros then
- code,message=macros.loaded(fullname,true,false)
- else
- code,message=loadfile(fullname)
- end
- if code then
- code()
- else
- report_lua("loading of file %a failed:\n\t%s",fullname,message or "no message")
- code,message=loadfile(fullname)
- end
- if forcestrip and luautilities.stripcode then
- if type(forcestrip)=="function" then
- forcestrip=forcestrip(fullname)
- end
- if forcestrip or luautilities.alwaysstripcode then
- register(name)
- return load(dump(code,true)),0
- else
- return code,0
- end
- elseif luautilities.alwaysstripcode then
- register(name)
- return load(dump(code,true)),0
- else
- return code,0
- end
-end
-function luautilities.strippedloadstring(code,name,forcestrip)
- local code,message=load(code)
- if not code then
- report_lua("loading of file %a failed:\n\t%s",name,message or "no message")
- end
- if forcestrip and luautilities.stripcode or luautilities.alwaysstripcode then
- register(name)
- return load(dump(code,true)),0
- else
- return code,0
- end
-end
-function luautilities.loadstring(code,name)
- local code,message=load(code)
- if not code then
- report_lua("loading of file %a failed:\n\t%s",name,message or "no message")
- end
- return code,0
-end
-function luautilities.compile(luafile,lucfile,cleanup,strip,fallback)
- report_lua("compiling %a into %a",luafile,lucfile)
- os.remove(lucfile)
- local done=stupidcompile(luafile,lucfile,strip~=false)
- if done then
- report_lua("dumping %a into %a stripped",luafile,lucfile)
- if cleanup==true and lfs.isfile(lucfile) and lfs.isfile(luafile) then
- report_lua("removing %a",luafile)
- os.remove(luafile)
- end
- end
- return done
-end
-function luautilities.loadstripped(...)
- local l=load(...)
- if l then
- return load(dump(l,true))
- end
-end
-local finalizers={}
-setmetatable(finalizers,{
- __gc=function(t)
- for i=1,#t do
- pcall(t[i])
- end
- end
-} )
-function luautilities.registerfinalizer(f)
- finalizers[#finalizers+1]=f
-end
-function luautilities.checkmemory(previous,threshold,trace)
- local current=collectgarbage("count")
- if previous then
- local checked=(threshold or 64)*1024
- local delta=current-previous
- if current-previous>checked then
- collectgarbage("collect")
- local afterwards=collectgarbage("count")
- if trace or tracememory then
- report_mem("previous %r MB, current %r MB, delta %r MB, threshold %r MB, afterwards %r MB",
- previous/1024,current/1024,delta/1024,threshold,afterwards)
- end
- return afterwards
- elseif trace or tracememory then
- report_mem("previous %r MB, current %r MB, delta %r MB, threshold %r MB",
- previous/1024,current/1024,delta/1024,threshold)
- end
- end
- return current
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-deb"] = package.loaded["util-deb"] or true
-
--- original size: 10136, stripped down to: 6832
-
-if not modules then modules={} end modules ['util-deb']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,next,tostring,tonumber=type,next,tostring,tonumber
-local format,find,sub,gsub=string.format,string.find,string.sub,string.gsub
-local insert,remove,sort=table.insert,table.remove,table.sort
-local setmetatableindex=table.setmetatableindex
-utilities=utilities or {}
-local debugger=utilities.debugger or {}
-utilities.debugger=debugger
-local report=logs.reporter("debugger")
-local ticks=os.gettimeofday or os.clock
-local seconds=function(n) return n or 0 end
-local overhead=0
-local dummycalls=10*1000
-local nesting=0
-local names={}
-local initialize=false
-if lua.getpreciseticks then
- initialize=function()
- ticks=lua.getpreciseticks
- seconds=lua.getpreciseseconds
- initialize=false
- end
-elseif not (FFISUPPORTED and ffi) then
-elseif os.type=="windows" then
- initialize=function()
- local kernel=ffilib("kernel32","system")
- if kernel then
- local tonumber=ffi.number or tonumber
- ffi.cdef[[
- int QueryPerformanceFrequency(int64_t *lpFrequency);
- int QueryPerformanceCounter(int64_t *lpPerformanceCount);
- ]]
- local target=ffi.new("__int64[1]")
- ticks=function()
- if kernel.QueryPerformanceCounter(target)==1 then
- return tonumber(target[0])
- else
- return 0
- end
- end
- local target=ffi.new("__int64[1]")
- seconds=function(ticks)
- if kernel.QueryPerformanceFrequency(target)==1 then
- return ticks/tonumber(target[0])
- else
- return 0
- end
- end
- end
- initialize=false
- end
-elseif os.type=="unix" then
- initialize=function()
- local C=ffi.C
- local tonumber=ffi.number or tonumber
- ffi.cdef [[
- /* what a mess */
- typedef int clk_id_t;
- typedef enum { CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID } clk_id;
- typedef struct timespec { long sec; long nsec; } ctx_timespec;
- int clock_gettime(clk_id_t timerid, struct timespec *t);
- ]]
- local target=ffi.new("ctx_timespec[?]",1)
- local clock=C.CLOCK_PROCESS_CPUTIME_ID
- ticks=function ()
- C.clock_gettime(clock,target)
- return tonumber(target[0].sec*1000000000+target[0].nsec)
- end
- seconds=function(ticks)
- return ticks/1000000000
- end
- initialize=false
- end
-end
-setmetatableindex(names,function(t,name)
- local v=setmetatableindex(function(t,source)
- local v=setmetatableindex(function(t,line)
- local v={ total=0,count=0,nesting=0 }
- t[line]=v
- return v
- end)
- t[source]=v
- return v
- end)
- t[name]=v
- return v
-end)
-local getinfo=nil
-local sethook=nil
-local function hook(where)
- local f=getinfo(2,"nSl")
- if f then
- local source=f.short_src
- if not source then
- return
- end
- local line=f.linedefined or 0
- local name=f.name
- if not name then
- local what=f.what
- if what=="C" then
- name="<anonymous>"
- else
- name=f.namewhat or what or "<unknown>"
- end
- end
- local data=names[name][source][line]
- if where=="call" then
- local nesting=data.nesting
- if nesting==0 then
- data.count=data.count+1
- insert(data,ticks())
- data.nesting=1
- else
- data.nesting=nesting+1
- end
- elseif where=="return" then
- local nesting=data.nesting
- if nesting==1 then
- local t=remove(data)
- if t then
- data.total=data.total+ticks()-t
- end
- data.nesting=0
- else
- data.nesting=nesting-1
- end
- end
- end
-end
-function debugger.showstats(printer,threshold)
- local printer=printer or report
- local calls=0
- local functions=0
- local dataset={}
- local length=0
- local realtime=0
- local totaltime=0
- local threshold=threshold or 0
- for name,sources in next,names do
- for source,lines in next,sources do
- for line,data in next,lines do
- local count=data.count
- if count>threshold then
- if #name>length then
- length=#name
- end
- local total=data.total
- local real=total
- if real>0 then
- real=total-(count*overhead/dummycalls)
- if real<0 then
- real=0
- end
- realtime=realtime+real
- end
- totaltime=totaltime+total
- if line<0 then
- line=0
- end
- dataset[#dataset+1]={ real,total,count,name,source,line }
- end
- end
- end
- end
- sort(dataset,function(a,b)
- if a[1]==b[1] then
- if a[2]==b[2] then
- if a[3]==b[3] then
- if a[4]==b[4] then
- if a[5]==b[5] then
- return a[6]<b[6]
- else
- return a[5]<b[5]
- end
- else
- return a[4]<b[4]
- end
- else
- return b[3]<a[3]
- end
- else
- return b[2]<a[2]
- end
- else
- return b[1]<a[1]
- end
- end)
- if length>50 then
- length=50
- end
- local fmt=string.formatters["%4.9k s %3.3k %% %4.9k s %3.3k %% %8i # %-"..length.."s %4i %s"]
- for i=1,#dataset do
- local data=dataset[i]
- local real=data[1]
- local total=data[2]
- local count=data[3]
- local name=data[4]
- local source=data[5]
- local line=data[6]
- calls=calls+count
- functions=functions+1
- name=gsub(name,"%s+"," ")
- if #name>length then
- name=sub(name,1,length)
- end
- printer(fmt(seconds(total),100*total/totaltime,seconds(real),100*real/realtime,count,name,line,source))
- end
- printer("")
- printer(format("functions : %i",functions))
- printer(format("calls : %i",calls))
- printer(format("overhead : %f",seconds(overhead/1000)))
-end
-local function getdebug()
- if sethook and getinfo then
- return
- end
- if not debug then
- local okay
- okay,debug=pcall(require,"debug")
- end
- if type(debug)~="table" then
- return
- end
- getinfo=debug.getinfo
- sethook=debug.sethook
- if type(getinfo)~="function" then
- getinfo=nil
- end
- if type(sethook)~="function" then
- sethook=nil
- end
-end
-function debugger.savestats(filename,threshold)
- local f=io.open(filename,'w')
- if f then
- debugger.showstats(function(str) f:write(str,"\n") end,threshold)
- f:close()
- end
-end
-function debugger.enable()
- getdebug()
- if sethook and getinfo and nesting==0 then
- running=true
- if initialize then
- initialize()
- end
- sethook(hook,"cr")
- local function dummy() end
- local t=ticks()
- for i=1,dummycalls do
- dummy()
- end
- overhead=ticks()-t
- end
- if nesting>0 then
- nesting=nesting+1
- end
-end
-function debugger.disable()
- if nesting>0 then
- nesting=nesting-1
- end
- if sethook and getinfo and nesting==0 then
- sethook()
- end
-end
-local function showtraceback(rep)
- getdebug()
- if getinfo then
- local level=2
- local reporter=rep or report
- while true do
- local info=getinfo(level,"Sl")
- if not info then
- break
- elseif info.what=="C" then
- reporter("%2i : %s",level-1,"C function")
- else
- reporter("%2i : %s : %s",level-1,info.short_src,info.currentline)
- end
- level=level+1
- end
- end
-end
-debugger.showtraceback=showtraceback
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-tpl"] = package.loaded["util-tpl"] or true
-
--- original size: 7722, stripped down to: 4212
-
-if not modules then modules={} end modules ['util-tpl']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities.templates=utilities.templates or {}
-local templates=utilities.templates
-local trace_template=false trackers.register("templates.trace",function(v) trace_template=v end)
-local report_template=logs.reporter("template")
-local tostring,next=tostring,next
-local format,sub,byte=string.format,string.sub,string.byte
-local P,C,R,Cs,Cc,Carg,lpegmatch,lpegpatterns=lpeg.P,lpeg.C,lpeg.R,lpeg.Cs,lpeg.Cc,lpeg.Carg,lpeg.match,lpeg.patterns
-local formatters=string.formatters
-local replacer
-local function replacekey(k,t,how,recursive)
- local v=t[k]
- if not v then
- if trace_template then
- report_template("unknown key %a",k)
- end
- return ""
- else
- v=tostring(v)
- if trace_template then
- report_template("setting key %a to value %a",k,v)
- end
- if recursive then
- return lpegmatch(replacer,v,1,t,how,recursive)
- else
- return v
- end
- end
-end
-local sqlescape=lpeg.replacer {
- { "'","''" },
- { "\\","\\\\" },
- { "\r\n","\\n" },
- { "\r","\\n" },
-}
-local sqlquoted=Cs(Cc("'")*sqlescape*Cc("'"))
-lpegpatterns.sqlescape=sqlescape
-lpegpatterns.sqlquoted=sqlquoted
-local luaescape=lpegpatterns.luaescape
-local escapers={
- lua=function(s)
- return lpegmatch(luaescape,s)
- end,
- sql=function(s)
- return lpegmatch(sqlescape,s)
- end,
-}
-local quotedescapers={
- lua=function(s)
- return format("%q",s)
- end,
- sql=function(s)
- return lpegmatch(sqlquoted,s)
- end,
-}
-local luaescaper=escapers.lua
-local quotedluaescaper=quotedescapers.lua
-local function replacekeyunquoted(s,t,how,recurse)
- if how==false then
- return replacekey(s,t,how,recurse)
- else
- local escaper=how and escapers[how] or luaescaper
- return escaper(replacekey(s,t,how,recurse))
- end
-end
-local function replacekeyquoted(s,t,how,recurse)
- if how==false then
- return replacekey(s,t,how,recurse)
- else
- local escaper=how and quotedescapers[how] or quotedluaescaper
- return escaper(replacekey(s,t,how,recurse))
- end
-end
-local function replaceoptional(l,m,r,t,how,recurse)
- local v=t[l]
- return v and v~="" and lpegmatch(replacer,r,1,t,how or "lua",recurse or false) or ""
-end
-local function replaceformatted(l,m,r,t,how,recurse)
- local v=t[r]
- return v and formatters[l](v)
-end
-local single=P("%")
-local double=P("%%")
-local lquoted=P("%[")
-local rquoted=P("]%")
-local lquotedq=P("%(")
-local rquotedq=P(")%")
-local escape=double/'%%'
-local nosingle=single/''
-local nodouble=double/''
-local nolquoted=lquoted/''
-local norquoted=rquoted/''
-local nolquotedq=lquotedq/''
-local norquotedq=rquotedq/''
-local nolformatted=P(":")/"%%"
-local norformatted=P(":")/""
-local noloptional=P("%?")/''
-local noroptional=P("?%")/''
-local nomoptional=P(":")/''
-local args=Carg(1)*Carg(2)*Carg(3)
-local key=nosingle*((C((1-nosingle)^1)*args)/replacekey)*nosingle
-local quoted=nolquotedq*((C((1-norquotedq)^1)*args)/replacekeyquoted)*norquotedq
-local unquoted=nolquoted*((C((1-norquoted)^1)*args)/replacekeyunquoted)*norquoted
-local optional=noloptional*((C((1-nomoptional)^1)*nomoptional*C((1-noroptional)^1)*args)/replaceoptional)*noroptional
-local formatted=nosingle*((Cs(nolformatted*(1-norformatted )^1)*norformatted*C((1-nosingle)^1)*args)/replaceformatted)*nosingle
-local any=P(1)
- replacer=Cs((unquoted+quoted+formatted+escape+optional+key+any)^0)
-local function replace(str,mapping,how,recurse)
- if mapping and str then
- return lpegmatch(replacer,str,1,mapping,how or "lua",recurse or false) or str
- else
- return str
- end
-end
-templates.replace=replace
-function templates.replacer(str,how,recurse)
- return function(mapping)
- return lpegmatch(replacer,str,1,mapping,how or "lua",recurse or false) or str
- end
-end
-function templates.load(filename,mapping,how,recurse)
- local data=io.loaddata(filename) or ""
- if mapping and next(mapping) then
- return replace(data,mapping,how,recurse)
- else
- return data
- end
-end
-function templates.resolve(t,mapping,how,recurse)
- if not mapping then
- mapping=t
- end
- for k,v in next,t do
- t[k]=replace(v,mapping,how,recurse)
- end
- return t
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-sbx"] = package.loaded["util-sbx"] or true
-
--- original size: 21084, stripped down to: 13214
-
-if not modules then modules={} end modules ['util-sbx']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if not sandbox then require("l-sandbox") end
-local next,type=next,type
-local replace=utilities.templates.replace
-local collapsepath=file.collapsepath
-local expandname=dir.expandname
-local sortedhash=table.sortedhash
-local lpegmatch=lpeg.match
-local platform=os.type
-local P,S,C=lpeg.P,lpeg.S,lpeg.C
-local gsub=string.gsub
-local lower=string.lower
-local find=string.find
-local concat=string.concat
-local unquoted=string.unquoted
-local optionalquoted=string.optionalquoted
-local basename=file.basename
-local nameonly=file.nameonly
-local sandbox=sandbox
-local validroots={}
-local validrunners={}
-local validbinaries=true
-local validlibraries=true
-local validators={}
-local finalized=nil
-local trace=false
-local p_validroot=nil
-local p_split=lpeg.firstofsplit(" ")
-local report=logs.reporter("sandbox")
-trackers.register("sandbox",function(v) trace=v end)
-sandbox.setreporter(report)
-sandbox.finalizer {
- category="files",
- action=function()
- finalized=true
- end
-}
-local function registerroot(root,what)
- if finalized then
- report("roots are already finalized")
- else
- if type(root)=="table" then
- root,what=root[1],root[2]
- end
- if type(root)=="string" and root~="" then
- root=collapsepath(expandname(root))
- if what=="r" or what=="ro" or what=="readable" then
- what="read"
- elseif what=="w" or what=="wo" or what=="writable" then
- what="write"
- end
- validroots[root]=what=="write" or false
- end
- end
-end
-sandbox.finalizer {
- category="files",
- action=function()
- if p_validroot then
- report("roots are already initialized")
- else
- sandbox.registerroot(".","write")
- for name in sortedhash(validroots) do
- if p_validroot then
- p_validroot=P(name)+p_validroot
- else
- p_validroot=P(name)
- end
- end
- p_validroot=p_validroot/validroots
- end
- end
-}
-local function registerbinary(name)
- if finalized then
- report("binaries are already finalized")
- elseif type(name)=="string" and name~="" then
- if not validbinaries then
- return
- end
- if validbinaries==true then
- validbinaries={ [name]=true }
- else
- validbinaries[name]=true
- end
- elseif name==true then
- validbinaries={}
- end
-end
-local function registerlibrary(name)
- if finalized then
- report("libraries are already finalized")
- elseif type(name)=="string" and name~="" then
- if not validlibraries then
- return
- end
- if validlibraries==true then
- validlibraries={ [nameonly(name)]=true }
- else
- validlibraries[nameonly(name)]=true
- end
- elseif name==true then
- validlibraries={}
- end
-end
-local p_write=S("wa") p_write=(1-p_write)^0*p_write
-local p_path=S("\\/~$%:") p_path=(1-p_path )^0*p_path
-local function normalized(name)
- if platform=="windows" then
- name=gsub(name,"/","\\")
- end
- return name
-end
-function sandbox.possiblepath(name)
- return lpegmatch(p_path,name) and true or false
-end
-local filenamelogger=false
-function sandbox.setfilenamelogger(l)
- filenamelogger=type(l)=="function" and l or false
-end
-local function validfilename(name,what)
- if p_validroot and type(name)=="string" and lpegmatch(p_path,name) then
- local asked=collapsepath(expandname(name))
- local okay=lpegmatch(p_validroot,asked)
- if okay==true then
- if filenamelogger then
- filenamelogger(name,"w",asked,true)
- end
- return name
- elseif okay==false then
- if not what then
- if filenamelogger then
- filenamelogger(name,"r",asked,true)
- end
- return name
- elseif lpegmatch(p_write,what) then
- if filenamelogger then
- filenamelogger(name,"w",asked,false)
- end
- return
- else
- if filenamelogger then
- filenamelogger(name,"r",asked,true)
- end
- return name
- end
- elseif filenamelogger then
- filenamelogger(name,"*",name,false)
- end
- else
- return name
- end
-end
-local function readable(name,finalized)
- return validfilename(name,"r")
-end
-local function normalizedreadable(name,finalized)
- local valid=validfilename(name,"r")
- if valid then
- return normalized(valid)
- end
-end
-local function writeable(name,finalized)
- return validfilename(name,"w")
-end
-local function normalizedwriteable(name,finalized)
- local valid=validfilename(name,"w")
- if valid then
- return normalized(valid)
- end
-end
-validators.readable=readable
-validators.writeable=normalizedwriteable
-validators.normalizedreadable=normalizedreadable
-validators.normalizedwriteable=writeable
-validators.filename=readable
-table.setmetatableindex(validators,function(t,k)
- if k then
- t[k]=readable
- end
- return readable
-end)
-function validators.string(s,finalized)
- if finalized and suspicious(s) then
- return ""
- else
- return s
- end
-end
-function validators.cache(s)
- if finalized then
- return basename(s)
- else
- return s
- end
-end
-function validators.url(s)
- if finalized and find("^file:") then
- return ""
- else
- return s
- end
-end
-local function filehandlerone(action,one,...)
- local checkedone=validfilename(one)
- if checkedone then
- return action(one,...)
- else
- end
-end
-local function filehandlertwo(action,one,two,...)
- local checkedone=validfilename(one)
- if checkedone then
- local checkedtwo=validfilename(two)
- if checkedtwo then
- return action(one,two,...)
- else
- end
- else
- end
-end
-local function iohandler(action,one,...)
- if type(one)=="string" then
- local checkedone=validfilename(one)
- if checkedone then
- return action(one,...)
- end
- elseif one then
- return action(one,...)
- else
- return action()
- end
-end
-local osexecute=sandbox.original(os.execute)
-local iopopen=sandbox.original(io.popen)
-local reported={}
-local function validcommand(name,program,template,checkers,defaults,variables,reporter,strict)
- if validbinaries~=false and (validbinaries==true or validbinaries[program]) then
- local binpath=nil
- if variables then
- for variable,value in next,variables do
- local chktype=checkers[variable]
- if chktype=="verbose" then
- else
- local checker=validators[chktype]
- if checker then
- value=checker(unquoted(value),strict)
- if value then
- variables[variable]=optionalquoted(value)
- else
- report("variable %a with value %a fails the check",variable,value)
- return
- end
- else
- report("variable %a has no checker",variable)
- return
- end
- end
- end
- for variable,default in next,defaults do
- local value=variables[variable]
- if not value or value=="" then
- local chktype=checkers[variable]
- if chktype=="verbose" then
- else
- local checker=validators[chktype]
- if checker then
- default=checker(unquoted(default),strict)
- if default then
- variables[variable]=optionalquoted(default)
- else
- report("variable %a with default %a fails the check",variable,default)
- return
- end
- end
- end
- end
- end
- binpath=variables.binarypath
- end
- if type(binpath)=="string" and binpath~="" then
- program=binpath.."/"..program
- end
- local command=program.." "..replace(template,variables)
- if reporter then
- reporter("executing runner %a: %s",name,command)
- elseif trace then
- report("executing runner %a: %s",name,command)
- end
- return command
- elseif not reported[name] then
- report("executing program %a of runner %a is not permitted",program,name)
- reported[name]=true
- end
-end
-local runners={
- resultof=function(...)
- local command=validcommand(...)
- if command then
- if trace then
- report("resultof: %s",command)
- end
- local handle=iopopen(command,"r")
- if handle then
- local result=handle:read("*all") or ""
- handle:close()
- return result
- end
- end
- end,
- execute=function(...)
- local command=validcommand(...)
- if command then
- if trace then
- report("execute: %s",command)
- end
- local okay=osexecute(command)
- return okay
- end
- end,
- pipeto=function(...)
- local command=validcommand(...)
- if command then
- if trace then
- report("pipeto: %s",command)
- end
- return iopopen(command,"w")
- end
- end,
-}
-function sandbox.registerrunner(specification)
- if type(specification)=="string" then
- local wrapped=validrunners[specification]
- inspect(table.sortedkeys(validrunners))
- if wrapped then
- return wrapped
- else
- report("unknown predefined runner %a",specification)
- return
- end
- end
- if type(specification)~="table" then
- report("specification should be a table (or string)")
- return
- end
- local name=specification.name
- if type(name)~="string" then
- report("invalid name, string expected",name)
- return
- end
- if validrunners[name] then
- report("invalid name, runner %a already defined",name)
- return
- end
- local program=specification.program
- if type(program)=="string" then
- elseif type(program)=="table" then
- program=program[platform] or program.default or program.unix
- end
- if type(program)~="string" or program=="" then
- report("invalid runner %a specified for platform %a",name,platform)
- return
- end
- local template=specification.template
- if not template then
- report("missing template for runner %a",name)
- return
- end
- local method=specification.method or "execute"
- local checkers=specification.checkers or {}
- local defaults=specification.defaults or {}
- local runner=runners[method]
- if runner then
- local finalized=finalized
- local wrapped=function(variables)
- return runner(name,program,template,checkers,defaults,variables,specification.reporter,finalized)
- end
- validrunners[name]=wrapped
- return wrapped
- else
- validrunners[name]=nil
- report("invalid method for runner %a",name)
- end
-end
-function sandbox.getrunner(name)
- return name and validrunners[name]
-end
-local function suspicious(str)
- return (find(str,"[/\\]") or find(command,"..",1,true)) and true or false
-end
-local function binaryrunner(action,command,...)
- if validbinaries==false then
- report("no binaries permitted, ignoring command: %s",command)
- return
- end
- if type(command)~="string" then
- report("command should be a string")
- return
- end
- local program=lpegmatch(p_split,command)
- if not program or program=="" then
- report("unable to filter binary from command: %s",command)
- return
- end
- if validbinaries==true then
- elseif not validbinaries[program] then
- report("binary not permitted, ignoring command: %s",command)
- return
- elseif suspicious(command) then
- report("/ \\ or .. found, ignoring command (use sandbox.registerrunner): %s",command)
- return
- end
- return action(command,...)
-end
-local function dummyrunner(action,command,...)
- if type(command)=="table" then
- command=concat(command," ",command[0] and 0 or 1)
- end
- report("ignoring command: %s",command)
-end
-sandbox.filehandlerone=filehandlerone
-sandbox.filehandlertwo=filehandlertwo
-sandbox.iohandler=iohandler
-function sandbox.disablerunners()
- validbinaries=false
-end
-function sandbox.disablelibraries()
- validlibraries=false
-end
-if FFISUPPORTED and ffi then
- function sandbox.disablelibraries()
- validlibraries=false
- for k,v in next,ffi do
- if k~="gc" then
- ffi[k]=nil
- end
- end
- end
- local fiiload=ffi.load
- if fiiload then
- local reported={}
- function ffi.load(name,...)
- if validlibraries==false then
- elseif validlibraries==true then
- return fiiload(name,...)
- elseif validlibraries[nameonly(name)] then
- return fiiload(name,...)
- else
- end
- if not reported[name] then
- report("using library %a is not permitted",name)
- reported[name]=true
- end
- return nil
- end
- end
-end
-local overload=sandbox.overload
-local register=sandbox.register
- overload(loadfile,filehandlerone,"loadfile")
-if io then
- overload(io.open,filehandlerone,"io.open")
- overload(io.popen,binaryrunner,"io.popen")
- overload(io.input,iohandler,"io.input")
- overload(io.output,iohandler,"io.output")
- overload(io.lines,filehandlerone,"io.lines")
-end
-if os then
- overload(os.execute,binaryrunner,"os.execute")
- overload(os.spawn,dummyrunner,"os.spawn")
- overload(os.exec,dummyrunner,"os.exec")
- overload(os.resultof,binaryrunner,"os.resultof")
- overload(os.pipeto,binaryrunner,"os.pipeto")
- overload(os.rename,filehandlertwo,"os.rename")
- overload(os.remove,filehandlerone,"os.remove")
-end
-if lfs then
- overload(lfs.chdir,filehandlerone,"lfs.chdir")
- overload(lfs.mkdir,filehandlerone,"lfs.mkdir")
- overload(lfs.rmdir,filehandlerone,"lfs.rmdir")
- overload(lfs.isfile,filehandlerone,"lfs.isfile")
- overload(lfs.isdir,filehandlerone,"lfs.isdir")
- overload(lfs.attributes,filehandlerone,"lfs.attributes")
- overload(lfs.dir,filehandlerone,"lfs.dir")
- overload(lfs.lock_dir,filehandlerone,"lfs.lock_dir")
- overload(lfs.touch,filehandlerone,"lfs.touch")
- overload(lfs.link,filehandlertwo,"lfs.link")
- overload(lfs.setmode,filehandlerone,"lfs.setmode")
- overload(lfs.readlink,filehandlerone,"lfs.readlink")
- overload(lfs.shortname,filehandlerone,"lfs.shortname")
- overload(lfs.symlinkattributes,filehandlerone,"lfs.symlinkattributes")
-end
-if zip then
- zip.open=register(zip.open,filehandlerone,"zip.open")
-end
-sandbox.registerroot=registerroot
-sandbox.registerbinary=registerbinary
-sandbox.registerlibrary=registerlibrary
-sandbox.validfilename=validfilename
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-mrg"] = package.loaded["util-mrg"] or true
-
--- original size: 7819, stripped down to: 5881
-
-if not modules then modules={} end modules ['util-mrg']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local gsub,format=string.gsub,string.format
-local concat=table.concat
-local type,next=type,next
-local P,R,S,V,Ct,C,Cs,Cc,Cp,Cmt,Cb,Cg=lpeg.P,lpeg.R,lpeg.S,lpeg.V,lpeg.Ct,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Cp,lpeg.Cmt,lpeg.Cb,lpeg.Cg
-local lpegmatch,patterns=lpeg.match,lpeg.patterns
-utilities=utilities or {}
-local merger=utilities.merger or {}
-utilities.merger=merger
-merger.strip_comment=true
-local report=logs.reporter("system","merge")
-utilities.report=report
-local m_begin_merge="begin library merge"
-local m_end_merge="end library merge"
-local m_begin_closure="do -- create closure to overcome 200 locals limit"
-local m_end_closure="end -- of closure"
-local m_pattern="%c+".."%-%-%s+"..m_begin_merge.."%c+(.-)%c+".."%-%-%s+"..m_end_merge.."%c+"
-local m_format="\n\n-- "..m_begin_merge.."\n%s\n".."-- "..m_end_merge.."\n\n"
-local m_faked="-- ".."created merged file".."\n\n".."-- "..m_begin_merge.."\n\n".."-- "..m_end_merge.."\n\n"
-local m_report=[[
--- used libraries : %s
--- skipped libraries : %s
--- original bytes : %s
--- stripped bytes : %s
-]]
-local m_preloaded=[[package.loaded[%q] = package.loaded[%q] or true]]
-local function self_fake()
- return m_faked
-end
-local function self_nothing()
- return ""
-end
-local function self_load(name)
- local data=io.loaddata(name) or ""
- if data=="" then
- report("unknown file %a",name)
- else
- report("inserting file %a",name)
- end
- return data or ""
-end
-local space=patterns.space
-local eol=patterns.newline
-local equals=P("=")^0
-local open=P("[")*Cg(equals,"init")*P("[")*P("\n")^-1
-local close=P("]")*C(equals)*P("]")
-local closeeq=Cmt(close*Cb("init"),function(s,i,a,b) return a==b end)
-local longstring=open*(1-closeeq)^0*close
-local quoted=patterns.quoted
-local digit=patterns.digit
-local emptyline=space^0*eol
-local operator1=P("<=")+P(">=")+P("~=")+P("..")+S("/^<>=*+%%")
-local operator2=S("*+/")
-local operator3=S("-")
-local operator4=P("..")
-local separator=S(",;")
-local ignore=(P("]")*space^1*P("=")*space^1*P("]"))/"]=["+(P("=")*space^1*P("{"))/"={"+(P("(")*space^1)/"("+(P("{")*(space+eol)^1*P("}"))/"{}"
-local strings=quoted
-local longcmt=(emptyline^0*P("--")*longstring*emptyline^0)/""
-local longstr=longstring
-local comment=emptyline^0*P("--")*P("-")^0*(1-eol)^0*emptyline^1/"\n"
-local optionalspaces=space^0/""
-local mandatespaces=space^1/""
-local optionalspacing=(eol+space)^0/""
-local mandatespacing=(eol+space)^1/""
-local pack=digit*space^1*operator4*optionalspacing+optionalspacing*operator1*optionalspacing+optionalspacing*operator2*optionalspaces+mandatespacing*operator3*mandatespaces+optionalspaces*separator*optionalspaces
-local lines=emptyline^2/"\n"
-local spaces=(space*space)/" "
-local spaces=(space*space*space*space)/" "
-local compact=Cs ((
- ignore+strings+longcmt+longstr+comment+pack+lines+spaces+1
-)^1 )
-local strip=Cs((emptyline^2/"\n"+1)^0)
-local stripreturn=Cs((1-P("return")*space^1*P(1-space-eol)^1*(space+eol)^0*P(-1))^1)
-function merger.compact(data)
- return lpegmatch(strip,lpegmatch(compact,data))
-end
-local function self_compact(data)
- local delta=0
- if merger.strip_comment then
- local before=#data
- data=lpegmatch(compact,data)
- data=lpegmatch(strip,data)
- local after=#data
- delta=before-after
- report("original size %s, compacted to %s, stripped %s",before,after,delta)
- data=format("-- original size: %s, stripped down to: %s\n\n%s",before,after,data)
- end
- return lpegmatch(stripreturn,data) or data,delta
-end
-local function self_save(name,data)
- if data~="" then
- io.savedata(name,data)
- report("saving %s with size %s",name,#data)
- end
-end
-local function self_swap(data,code)
- return data~="" and (gsub(data,m_pattern,function() return format(m_format,code) end,1)) or ""
-end
-local function self_libs(libs,list)
- local result,f,frozen,foundpath={},nil,false,nil
- result[#result+1]="\n"
- if type(libs)=='string' then libs={ libs } end
- if type(list)=='string' then list={ list } end
- for i=1,#libs do
- local lib=libs[i]
- for j=1,#list do
- local pth=gsub(list[j],"\\","/")
- report("checking library path %a",pth)
- local name=pth.."/"..lib
- if lfs.isfile(name) then
- foundpath=pth
- end
- end
- if foundpath then break end
- end
- if foundpath then
- report("using library path %a",foundpath)
- local right,wrong,original,stripped={},{},0,0
- for i=1,#libs do
- local lib=libs[i]
- local fullname=foundpath.."/"..lib
- if lfs.isfile(fullname) then
- report("using library %a",fullname)
- local preloaded=file.nameonly(lib)
- local data=io.loaddata(fullname,true)
- original=original+#data
- local data,delta=self_compact(data)
- right[#right+1]=lib
- result[#result+1]=m_begin_closure
- result[#result+1]=format(m_preloaded,preloaded,preloaded)
- result[#result+1]=data
- result[#result+1]=m_end_closure
- stripped=stripped+delta
- else
- report("skipping library %a",fullname)
- wrong[#wrong+1]=lib
- end
- end
- right=#right>0 and concat(right," ") or "-"
- wrong=#wrong>0 and concat(wrong," ") or "-"
- report("used libraries: %a",right)
- report("skipped libraries: %a",wrong)
- report("original bytes: %a",original)
- report("stripped bytes: %a",stripped)
- result[#result+1]=format(m_report,right,wrong,original,stripped)
- else
- report("no valid library path found")
- end
- return concat(result,"\n\n")
-end
-function merger.selfcreate(libs,list,target)
- if target then
- self_save(target,self_swap(self_fake(),self_libs(libs,list)))
- end
-end
-function merger.selfmerge(name,libs,list,target)
- self_save(target or name,self_swap(self_load(name),self_libs(libs,list)))
-end
-function merger.selfclean(name)
- self_save(name,self_swap(self_load(name),self_nothing()))
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-env"] = package.loaded["util-env"] or true
-
--- original size: 9738, stripped down to: 5531
-
-if not modules then modules={} end modules ['util-env']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local allocate,mark=utilities.storage.allocate,utilities.storage.mark
-local format,sub,match,gsub,find=string.format,string.sub,string.match,string.gsub,string.find
-local unquoted,quoted,optionalquoted=string.unquoted,string.quoted,string.optionalquoted
-local concat,insert,remove=table.concat,table.insert,table.remove
-environment=environment or {}
-local environment=environment
-local setlocale=os.setlocale
-setlocale(nil,nil)
-local report=logs.reporter("system")
-function os.setlocale(a,b)
- if a or b then
- if report then
- report()
- report("You're messing with os.locale in a supposedly locale neutral enviroment. From")
- report("now on are on your own and without support. Crashes or unexpected side effects")
- report("can happen but don't bother the luatex and context developer team with it.")
- report()
- report=nil
- end
- setlocale(a,b)
- end
-end
-local validengines=allocate {
- ["luatex"]=true,
- ["luajittex"]=true,
-}
-local basicengines=allocate {
- ["luatex"]="luatex",
- ["texlua"]="luatex",
- ["texluac"]="luatex",
- ["luajittex"]="luajittex",
- ["texluajit"]="luajittex",
-}
-local luaengines=allocate {
- ["lua"]=true,
- ["luajit"]=true,
-}
-environment.validengines=validengines
-environment.basicengines=basicengines
-if not arg then
- environment.used_as_library=true
-elseif luaengines[file.removesuffix(arg[-1])] then
-elseif validengines[file.removesuffix(arg[0])] then
- if arg[1]=="--luaonly" then
- arg[-1]=arg[0]
- arg[ 0]=arg[2]
- for k=3,#arg do
- arg[k-2]=arg[k]
- end
- remove(arg)
- remove(arg)
- else
- end
- local originalzero=file.basename(arg[0])
- local specialmapping={ luatools=="base" }
- if originalzero~="mtxrun" and originalzero~="mtxrun.lua" then
- arg[0]=specialmapping[originalzero] or originalzero
- insert(arg,0,"--script")
- insert(arg,0,"mtxrun")
- end
-end
-environment.arguments=allocate()
-environment.files=allocate()
-environment.sortedflags=nil
-function environment.initializearguments(arg)
- local arguments={}
- local files={}
- environment.arguments=arguments
- environment.files=files
- environment.sortedflags=nil
- for index=1,#arg do
- local argument=arg[index]
- if index>0 then
- local flag,value=match(argument,"^%-+(.-)=(.-)$")
- if flag then
- flag=gsub(flag,"^c:","")
- arguments[flag]=unquoted(value or "")
- else
- flag=match(argument,"^%-+(.+)")
- if flag then
- flag=gsub(flag,"^c:","")
- arguments[flag]=true
- else
- files[#files+1]=argument
- end
- end
- end
- end
- if not environment.ownname then
- if os.selfpath and os.selfname then
- environment.ownname=file.addsuffix(file.join(os.selfpath,os.selfname),"lua")
- end
- end
- environment.ownname=file.reslash(environment.ownname or arg[0] or 'unknown.lua')
-end
-function environment.setargument(name,value)
- environment.arguments[name]=value
-end
-function environment.getargument(name,partial)
- local arguments,sortedflags=environment.arguments,environment.sortedflags
- if arguments[name] then
- return arguments[name]
- elseif partial then
- if not sortedflags then
- sortedflags=allocate(table.sortedkeys(arguments))
- for k=1,#sortedflags do
- sortedflags[k]="^"..sortedflags[k]
- end
- environment.sortedflags=sortedflags
- end
- for k=1,#sortedflags do
- local v=sortedflags[k]
- if find(name,v) then
- return arguments[sub(v,2,#v)]
- end
- end
- end
- return nil
-end
-environment.argument=environment.getargument
-function environment.splitarguments(separator)
- local done,before,after=false,{},{}
- local originalarguments=environment.originalarguments
- for k=1,#originalarguments do
- local v=originalarguments[k]
- if not done and v==separator then
- done=true
- elseif done then
- after[#after+1]=v
- else
- before[#before+1]=v
- end
- end
- return before,after
-end
-function environment.reconstructcommandline(arg,noquote)
- local resolveprefix=resolvers.resolve
- arg=arg or environment.originalarguments
- if noquote and #arg==1 then
- return unquoted(resolveprefix and resolveprefix(arg[1]) or arg[1])
- elseif #arg>0 then
- local result={}
- for i=1,#arg do
- result[i]=optionalquoted(resolveprefix and resolveprefix(arg[i]) or resolveprefix)
- end
- return concat(result," ")
- else
- return ""
- end
-end
-function environment.relativepath(path,root)
- if not path then
- path=""
- end
- if not file.is_rootbased_path(path) then
- if not root then
- root=file.pathpart(environment.ownscript or environment.ownname or ".")
- end
- if root=="" then
- root="."
- end
- path=root.."/"..path
- end
- return file.collapsepath(path,true)
-end
-if arg then
- local newarg,instring={},false
- for index=1,#arg do
- local argument=arg[index]
- if find(argument,"^\"") then
- if find(argument,"\"$") then
- newarg[#newarg+1]=gsub(argument,"^\"(.-)\"$","%1")
- instring=false
- else
- newarg[#newarg+1]=gsub(argument,"^\"","")
- instring=true
- end
- elseif find(argument,"\"$") then
- if instring then
- newarg[#newarg]=newarg[#newarg].." "..gsub(argument,"\"$","")
- instring=false
- else
- newarg[#newarg+1]=argument
- end
- elseif instring then
- newarg[#newarg]=newarg[#newarg].." "..argument
- else
- newarg[#newarg+1]=argument
- end
- end
- for i=1,-5,-1 do
- newarg[i]=arg[i]
- end
- environment.initializearguments(newarg)
- environment.originalarguments=mark(newarg)
- environment.rawarguments=mark(arg)
- arg={}
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["luat-env"] = package.loaded["luat-env"] or true
-
--- original size: 6267, stripped down to: 4115
-
- if not modules then modules={} end modules ['luat-env']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local rawset,loadfile=rawset,loadfile
-local gsub=string.gsub
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_lua=logs.reporter("resolvers","lua")
-local luautilities=utilities.lua
-local luasuffixes=luautilities.suffixes
-local texgettoks=tex and tex.gettoks
-environment=environment or {}
-local environment=environment
-local mt={
- __index=function(_,k)
- if k=="version" then
- local version=texgettoks and texgettoks("contextversiontoks")
- if version and version~="" then
- rawset(environment,"version",version)
- return version
- else
- return "unknown"
- end
- elseif k=="jobname" or k=="formatname" then
- local name=tex and tex[k]
- if name or name=="" then
- rawset(environment,k,name)
- return name
- else
- return "unknown"
- end
- elseif k=="outputfilename" then
- local name=environment.jobname
- rawset(environment,k,name)
- return name
- end
- end
-}
-setmetatable(environment,mt)
-function environment.texfile(filename)
- return resolvers.findfile(filename,'tex')
-end
-function environment.luafile(filename)
- if CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and file.suffix(filename)=="lua" then
- local resolved=resolvers.findfile(file.replacesuffix(filename,"lmt")) or ""
- if resolved~="" then
- return resolved
- end
- end
- local resolved=resolvers.findfile(filename,'tex') or ""
- if resolved~="" then
- return resolved
- end
- resolved=resolvers.findfile(filename,'texmfscripts') or ""
- if resolved~="" then
- return resolved
- end
- return resolvers.findfile(filename,'luatexlibs') or ""
-end
-local stripindeed=false directives.register("system.compile.strip",function(v) stripindeed=v end)
-local function strippable(filename)
- if stripindeed then
- local modu=modules[file.nameonly(filename)]
- return modu and modu.dataonly
- else
- return false
- end
-end
-function environment.luafilechunk(filename,silent,macros)
- filename=file.replacesuffix(filename,"lua")
- local fullname=environment.luafile(filename)
- if fullname and fullname~="" then
- local data=luautilities.loadedluacode(fullname,strippable,filename,macros)
- if not silent then
- report_lua("loading file %a %s",fullname,not data and "failed" or "succeeded")
- end
- return data
- else
- if not silent then
- report_lua("unknown file %a",filename)
- end
- return nil
- end
-end
-function environment.loadluafile(filename,version)
- local lucname,luaname,chunk
- local basename=file.removesuffix(filename)
- if basename==filename then
- luaname=file.addsuffix(basename,luasuffixes.lua)
- lucname=file.addsuffix(basename,luasuffixes.luc)
- else
- luaname=filename
- lucname=nil
- end
- local fullname=(lucname and environment.luafile(lucname)) or ""
- if fullname~="" then
- if trace_locating then
- report_lua("loading %a",fullname)
- end
- chunk=loadfile(fullname)
- end
- if chunk then
- chunk()
- if version then
- local v=version
- if modules and modules[filename] then
- v=modules[filename].version
- elseif versions and versions[filename] then
- v=versions[filename]
- end
- if v==version then
- return true
- else
- if trace_locating then
- report_lua("version mismatch for %a, lua version %a, luc version %a",filename,v,version)
- end
- environment.loadluafile(filename)
- end
- else
- return true
- end
- end
- fullname=(luaname and environment.luafile(luaname)) or ""
- if fullname~="" then
- if trace_locating then
- report_lua("loading %a",fullname)
- end
- chunk=loadfile(fullname)
- if not chunk then
- if trace_locating then
- report_lua("unknown file %a",filename)
- end
- else
- chunk()
- return true
- end
- end
- return false
-end
-environment.filenames=setmetatable({},{
- __index=function(t,k)
- local v=environment.files[k]
- if v then
- return (gsub(v,"%.+$",""))
- end
- end,
- __newindex=function(t,k)
- end,
- __len=function(t)
- return #environment.files
- end,
-} )
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-zip"] = package.loaded["util-zip"] or true
-
--- original size: 19496, stripped down to: 10858
-
-if not modules then modules={} end modules ['util-zip']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,tostring,tonumber=type,tostring,tonumber
-local sort=table.sort
-local find,format,sub,gsub=string.find,string.format,string.sub,string.gsub
-local osdate,ostime,osclock=os.date,os.time,os.clock
-local ioopen=io.open
-local loaddata,savedata=io.loaddata,io.savedata
-local filejoin,isdir,dirname,mkdirs=file.join,lfs.isdir,file.dirname,dir.mkdirs
-local files=utilities.files
-local openfile=files.open
-local closefile=files.close
-local readstring=files.readstring
-local readcardinal2=files.readcardinal2le
-local readcardinal4=files.readcardinal4le
-local setposition=files.setposition
-local getposition=files.getposition
-local band=bit32.band
-local rshift=bit32.rshift
-local lshift=bit32.lshift
-local decompress,expandsize,calculatecrc
- local zlibdecompress=zlib.decompress
- local zlibexpandsize=zlib.expandsize
- local zlibchecksum=zlib.crc32
- decompress=function(source)
- return zlibdecompress(source,-15)
- end
- expandsize=zlibexpandsize and function(source,targetsize)
- return zlibexpandsize(source,targetsize,-15)
- end or decompress
- calculatecrc=function(buffer,initial)
- return zlibchecksum(initial or 0,buffer)
- end
-local zipfiles={}
-utilities.zipfiles=zipfiles
-local openzipfile,closezipfile,unzipfile,foundzipfile,getziphash,getziplist do
- function openzipfile(name)
- return {
- name=name,
- handle=openfile(name,0),
- }
- end
- local function collect(z)
- if not z.list then
- local list={}
- local hash={}
- local position=0
- local index=0
- local handle=z.handle
- while true do
- setposition(handle,position)
- local signature=readstring(handle,4)
- if signature=="PK\3\4" then
- local version=readcardinal2(handle)
- local flag=readcardinal2(handle)
- local method=readcardinal2(handle)
- local filetime=readcardinal2(handle)
- local filedate=readcardinal2(handle)
- local crc32=readcardinal4(handle)
- local compressed=readcardinal4(handle)
- local uncompressed=readcardinal4(handle)
- local namelength=readcardinal2(handle)
- local extralength=readcardinal2(handle)
- local filename=readstring(handle,namelength)
- local descriptor=band(flag,8)~=0
- local encrypted=band(flag,1)~=0
- local acceptable=method==0 or method==8
- local skipped=0
- local size=0
- if encrypted then
- size=readcardinal2(handle)
- skipbytes(size)
- skipped=skipped+size+2
- skipbytes(8)
- skipped=skipped+8
- size=readcardinal2(handle)
- skipbytes(size)
- skipped=skipped+size+2
- size=readcardinal4(handle)
- skipbytes(size)
- skipped=skipped+size+4
- size=readcardinal2(handle)
- skipbytes(size)
- skipped=skipped+size+2
- end
- position=position+30+namelength+extralength+skipped
- if descriptor then
- setposition(handle,position+compressed)
- crc32=readcardinal4(handle)
- compressed=readcardinal4(handle)
- uncompressed=readcardinal4(handle)
- end
- if acceptable then
- index=index+1
- local data={
- filename=filename,
- index=index,
- position=position,
- method=method,
- compressed=compressed,
- uncompressed=uncompressed,
- crc32=crc32,
- encrypted=encrypted,
- }
- hash[filename]=data
- list[index]=data
- else
- end
- position=position+compressed
- else
- break
- end
- z.list=list
- z.hash=hash
- end
- end
- end
- function getziplist(z)
- local list=z.list
- if not list then
- collect(z)
- end
- return z.list
- end
- function getziphash(z)
- local hash=z.hash
- if not hash then
- collect(z)
- end
- return z.hash
- end
- function foundzipfile(z,name)
- return getziphash(z)[name]
- end
- function closezipfile(z)
- local f=z.handle
- if f then
- closefile(f)
- z.handle=nil
- end
- end
- function unzipfile(z,filename,check)
- local hash=z.hash
- if not hash then
- hash=zipfiles.hash(z)
- end
- local data=hash[filename]
- if not data then
- end
- if data then
- local handle=z.handle
- local position=data.position
- local compressed=data.compressed
- if compressed>0 then
- setposition(handle,position)
- local result=readstring(handle,compressed)
- if data.method==8 then
- if expandsize then
- result=expandsize(result,data.uncompressed)
- else
- result=decompress(result)
- end
- end
- if check and data.crc32~=calculatecrc(result) then
- print("checksum mismatch")
- return ""
- end
- return result
- else
- return ""
- end
- end
- end
- zipfiles.open=openzipfile
- zipfiles.close=closezipfile
- zipfiles.unzip=unzipfile
- zipfiles.hash=getziphash
- zipfiles.list=getziplist
- zipfiles.found=foundzipfile
-end
-if xzip then
- local writecardinal1=files.writebyte
- local writecardinal2=files.writecardinal2le
- local writecardinal4=files.writecardinal4le
- local logwriter=logs.writer
- local globpattern=dir.globpattern
- local compress=xzip.compress
- local checksum=xzip.crc32
- local function fromdostime(dostime,dosdate)
- return ostime {
- year=rshift(dosdate,9)+1980,
- month=band(rshift(dosdate,5),0x0F),
- day=band((dosdate ),0x1F),
- hour=band(rshift(dostime,11) ),
- min=band(rshift(dostime,5),0x3F),
- sec=band((dostime ),0x1F),
- }
- end
- local function todostime(time)
- local t=osdate("*t",time)
- return
- lshift(t.year-1980,9)+lshift(t.month,5)+t.day,
- lshift(t.hour,11)+lshift(t.min,5)+rshift(t.sec,1)
- end
- local function openzip(filename,level,comment,verbose)
- local f=ioopen(filename,"wb")
- if f then
- return {
- filename=filename,
- handle=f,
- list={},
- level=tonumber(level) or 3,
- comment=tostring(comment),
- verbose=verbose,
- uncompressed=0,
- compressed=0,
- }
- end
- end
- local function writezip(z,name,data,level,time)
- local f=z.handle
- local list=z.list
- local level=tonumber(level) or z.level or 3
- local method=8
- local zipped=compress(data,level)
- local checksum=checksum(data)
- local verbose=z.verbose
- if not zipped then
- method=0
- zipped=data
- end
- local start=f:seek()
- local compressed=#zipped
- local uncompressed=#data
- z.compressed=z.compressed+compressed
- z.uncompressed=z.uncompressed+uncompressed
- if verbose then
- local pct=100*compressed/uncompressed
- if pct>=100 then
- logwriter(format("%10i %s",uncompressed,name))
- else
- logwriter(format("%10i %02.1f %s",uncompressed,pct,name))
- end
- end
- f:write("\x50\x4b\x03\x04")
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,method)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal4(f,checksum)
- writecardinal4(f,compressed)
- writecardinal4(f,uncompressed)
- writecardinal2(f,#name)
- writecardinal2(f,0)
- f:write(name)
- f:write(zipped)
- list[#list+1]={ #zipped,#data,name,checksum,start,time or 0 }
- end
- local function closezip(z)
- local f=z.handle
- local list=z.list
- local comment=z.comment
- local verbose=z.verbose
- local count=#list
- local start=f:seek()
- for i=1,count do
- local l=list[i]
- local compressed=l[1]
- local uncompressed=l[2]
- local name=l[3]
- local checksum=l[4]
- local start=l[5]
- local time=l[6]
- local date,time=todostime(time)
- f:write('\x50\x4b\x01\x02')
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,8)
- writecardinal2(f,time)
- writecardinal2(f,date)
- writecardinal4(f,checksum)
- writecardinal4(f,compressed)
- writecardinal4(f,uncompressed)
- writecardinal2(f,#name)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal4(f,0)
- writecardinal4(f,start)
- f:write(name)
- end
- local stop=f:seek()
- local size=stop-start
- f:write('\x50\x4b\x05\x06')
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,count)
- writecardinal2(f,count)
- writecardinal4(f,size)
- writecardinal4(f,start)
- if type(comment)=="string" and comment~="" then
- writecardinal2(f,#comment)
- f:write(comment)
- else
- writecardinal2(f,0)
- end
- if verbose then
- local compressed=z.compressed
- local uncompressed=z.uncompressed
- local filename=z.filename
- local pct=100*compressed/uncompressed
- logwriter("")
- if pct>=100 then
- logwriter(format("%10i %s",uncompressed,filename))
- else
- logwriter(format("%10i %02.1f %s",uncompressed,pct,filename))
- end
- end
- f:close()
- end
- local function zipdir(zipname,path,level,verbose)
- if type(zipname)=="table" then
- verbose=zipname.verbose
- level=zipname.level
- path=zipname.path
- zipname=zipname.zipname
- end
- if not zipname or zipname=="" then
- return
- end
- if not path or path=="" then
- path="."
- end
- if not isdir(path) then
- return
- end
- path=gsub(path,"\\+","/")
- path=gsub(path,"/+","/")
- local list={}
- local count=0
- globpattern(path,"",true,function(name,size,time)
- count=count+1
- list[count]={ name,time }
- end)
- sort(list,function(a,b)
- return a[1]<b[1]
- end)
- local zipf=openzip(zipname,level,comment,verbose)
- if zipf then
- local p=#path+2
- for i=1,count do
- local li=list[i]
- local name=li[1]
- local time=li[2]
- local data=loaddata(name)
- local name=sub(name,p,#name)
- writezip(zipf,name,data,level,time,verbose)
- end
- closezip(zipf)
- end
- end
- local function unzipdir(zipname,path,verbose)
- if type(zipname)=="table" then
- verbose=zipname.verbose
- path=zipname.path
- zipname=zipname.zipname
- end
- if not zipname or zipname=="" then
- return
- end
- if not path or path=="" then
- path="."
- end
- local z=openzipfile(zipname)
- if z then
- local list=getziplist(z)
- if list then
- local total=0
- local count=#list
- local step=number.idiv(count,10)
- local done=0
- local steps=verbose=="steps"
- local time=steps and osclock()
- for i=1,count do
- local l=list[i]
- local n=l.filename
- local d=unzipfile(z,n)
- if d then
- local p=filejoin(path,n)
- if mkdirs(dirname(p)) then
- if steps then
- total=total+#d
- done=done+1
- if done>=step then
- done=0
- logwriter(format("%4i files of %4i done, %10i bytes, %0.3f seconds",i,count,total,osclock()-time))
- end
- elseif verbose then
- logwriter(n)
- end
- savedata(p,d)
- end
- else
- logwriter(format("problem with file %s",n))
- end
- end
- if steps then
- logwriter(format("%4i files of %4i done, %10i bytes, %0.3f seconds",count,count,total,osclock()-time))
- end
- closezipfile(z)
- return true
- else
- closezipfile(z)
- end
- end
- end
- zipfiles.zipdir=zipdir
- zipfiles.unzipdir=unzipdir
-end
-zipfiles.gunzipfile=gzip.load
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-tab"] = package.loaded["lxml-tab"] or true
-
--- original size: 61808, stripped down to: 36227
-
-if not modules then modules={} end modules ['lxml-tab']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local trace_entities=false trackers.register("xml.entities",function(v) trace_entities=v end)
-local report_xml=logs and logs.reporter("xml","core") or function(...) print(string.format(...)) end
-if lpeg.setmaxstack then lpeg.setmaxstack(1000) end
-xml=xml or {}
-local xml=xml
-local concat,remove,insert=table.concat,table.remove,table.insert
-local type,next,setmetatable,getmetatable,tonumber,rawset,select=type,next,setmetatable,getmetatable,tonumber,rawset,select
-local lower,find,match,gsub=string.lower,string.find,string.match,string.gsub
-local sort=table.sort
-local utfchar=utf.char
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local P,S,R,C,V,C,Cs=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.V,lpeg.C,lpeg.Cs
-local formatters=string.formatters
-do
-xml.xmlns=xml.xmlns or {}
-local check=P(false)
-local parse=check
-function xml.registerns(namespace,pattern)
- check=check+C(P(lower(pattern)))/namespace
- parse=P { P(check)+1*V(1) }
-end
-function xml.checkns(namespace,url)
- local ns=lpegmatch(parse,lower(url))
- if ns and namespace~=ns then
- xml.xmlns[namespace]=ns
- end
-end
-function xml.resolvens(url)
- return lpegmatch(parse,lower(url)) or ""
-end
-end
-local nsremap,resolvens=xml.xmlns,xml.resolvens
-local stack,level,top,at,xmlnms,errorstr
-local entities,parameters
-local strip,utfize,resolve,cleanup,resolve_predefined,unify_predefined
-local dcache,hcache,acache
-local mt,dt,nt
-local currentfilename,currentline,linenumbers
-local grammar_parsed_text_one
-local grammar_parsed_text_two
-local grammar_unparsed_text
-local handle_hex_entity
-local handle_dec_entity
-local handle_any_entity_dtd
-local handle_any_entity_text
-local function preparexmlstate(settings)
- if settings then
- linenumbers=settings.linenumbers
- stack={}
- level=0
- top={}
- at={}
- mt={}
- dt={}
- nt=0
- xmlns={}
- errorstr=nil
- strip=settings.strip_cm_and_dt
- utfize=settings.utfize_entities
- resolve=settings.resolve_entities
- resolve_predefined=settings.resolve_predefined_entities
- unify_predefined=settings.unify_predefined_entities
- cleanup=settings.text_cleanup
- entities=settings.entities or {}
- currentfilename=settings.currentresource
- currentline=1
- parameters={}
- reported_at_errors={}
- dcache={}
- hcache={}
- acache={}
- if utfize==nil then
- settings.utfize_entities=true
- utfize=true
- end
- if resolve_predefined==nil then
- settings.resolve_predefined_entities=true
- resolve_predefined=true
- end
- else
- linenumbers=false
- stack=nil
- level=nil
- top=nil
- at=nil
- mt=nil
- dt=nil
- nt=nil
- xmlns=nil
- errorstr=nil
- strip=nil
- utfize=nil
- resolve=nil
- resolve_predefined=nil
- unify_predefined=nil
- cleanup=nil
- entities=nil
- parameters=nil
- reported_at_errors=nil
- dcache=nil
- hcache=nil
- acache=nil
- currentfilename=nil
- currentline=1
- end
-end
-local function initialize_mt(root)
- mt={ __index=root }
-end
-function xml.setproperty(root,k,v)
- getmetatable(root).__index[k]=v
-end
-function xml.checkerror(top,toclose)
- return ""
-end
-local checkns=xml.checkns
-local function add_attribute(namespace,tag,value)
- if cleanup and value~="" then
- value=cleanup(value)
- end
- if tag=="xmlns" then
- xmlns[#xmlns+1]=resolvens(value)
- at[tag]=value
- elseif namespace=="" then
- at[tag]=value
- elseif namespace=="xmlns" then
- checkns(tag,value)
- at["xmlns:"..tag]=value
- else
- at[namespace..":"..tag]=value
- end
-end
-local function add_empty(spacing,namespace,tag)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- local resolved=namespace=="" and xmlns[#xmlns] or nsremap[namespace] or namespace
- top=stack[level]
- dt=top.dt
- nt=#dt+1
- local t=linenumbers and {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt={},
- ni=nt,
- cf=currentfilename,
- cl=currentline,
- __p__=top,
- } or {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt={},
- ni=nt,
- __p__=top,
- }
- dt[nt]=t
- setmetatable(t,mt)
- if at.xmlns then
- remove(xmlns)
- end
- at={}
-end
-local function add_begin(spacing,namespace,tag)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- local resolved=namespace=="" and xmlns[#xmlns] or nsremap[namespace] or namespace
- dt={}
- top=linenumbers and {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt=dt,
- ni=nil,
- cf=currentfilename,
- cl=currentline,
- __p__=stack[level],
- } or {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt=dt,
- ni=nil,
- __p__=stack[level],
- }
- setmetatable(top,mt)
- nt=0
- level=level+1
- stack[level]=top
- at={}
-end
-local function add_end(spacing,namespace,tag)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- local toclose=stack[level]
- level=level-1
- top=stack[level]
- if level<1 then
- errorstr=formatters["unable to close %s %s"](tag,xml.checkerror(top,toclose) or "")
- report_xml(errorstr)
- elseif toclose.tg~=tag then
- errorstr=formatters["unable to close %s with %s %s"](toclose.tg,tag,xml.checkerror(top,toclose) or "")
- report_xml(errorstr)
- end
- dt=top.dt
- nt=#dt+1
- dt[nt]=toclose
- toclose.ni=nt
- if toclose.at.xmlns then
- remove(xmlns)
- end
-end
-local function add_text(text)
- if text=="" then
- return
- end
- if cleanup then
- if nt>0 then
- local s=dt[nt]
- if type(s)=="string" then
- dt[nt]=s..cleanup(text)
- else
- nt=nt+1
- dt[nt]=cleanup(text)
- end
- else
- nt=1
- dt[1]=cleanup(text)
- end
- else
- if nt>0 then
- local s=dt[nt]
- if type(s)=="string" then
- dt[nt]=s..text
- else
- nt=nt+1
- dt[nt]=text
- end
- else
- nt=1
- dt[1]=text
- end
- end
-end
-local function add_special(what,spacing,text)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- if strip and (what=="@cm@" or what=="@dt@") then
- else
- nt=nt+1
- dt[nt]=linenumbers and {
- special=true,
- ns="",
- tg=what,
- ni=nil,
- dt={ text },
- cf=currentfilename,
- cl=currentline,
- } or {
- special=true,
- ns="",
- tg=what,
- ni=nil,
- dt={ text },
- }
- end
-end
-local function set_message(txt)
- errorstr="garbage at the end of the file: "..gsub(txt,"([ \n\r\t]*)","")
-end
-local function attribute_value_error(str)
- if not reported_at_errors[str] then
- report_xml("invalid attribute value %a",str)
- reported_at_errors[str]=true
- at._error_=str
- end
- return str
-end
-local function attribute_specification_error(str)
- if not reported_at_errors[str] then
- report_xml("invalid attribute specification %a",str)
- reported_at_errors[str]=true
- at._error_=str
- end
- return str
-end
-do
- local badentity="&"
- xml.placeholders={
- unknown_dec_entity=function(str) return str=="" and badentity or formatters["&%s;"](str) end,
- unknown_hex_entity=function(str) return formatters["&#x%s;"](str) end,
- unknown_any_entity=function(str) return formatters["&#x%s;"](str) end,
- }
- local function fromhex(s)
- local n=tonumber(s,16)
- if n then
- return utfchar(n)
- else
- return formatters["h:%s"](s),true
- end
- end
- local function fromdec(s)
- local n=tonumber(s)
- if n then
- return utfchar(n)
- else
- return formatters["d:%s"](s),true
- end
- end
- local p_rest=(1-P(";"))^0
- local p_many=P(1)^0
- local parsedentity=P("&#")*(P("x")*(p_rest/fromhex)+(p_rest/fromdec))*P(";")*P(-1)+P ("#")*(P("x")*(p_many/fromhex)+(p_many/fromdec))
- xml.parsedentitylpeg=parsedentity
- local predefined_unified={
- [38]="&amp;",
- [42]="&quot;",
- [47]="&apos;",
- [74]="&lt;",
- [76]="&gt;",
- }
- local predefined_simplified={
- [38]="&",amp="&",
- [42]='"',quot='"',
- [47]="'",apos="'",
- [74]="<",lt="<",
- [76]=">",gt=">",
- }
- local nofprivates=0xF0000
- local privates_u={
- [ [[&]] ]="&amp;",
- [ [["]] ]="&quot;",
- [ [[']] ]="&apos;",
- [ [[<]] ]="&lt;",
- [ [[>]] ]="&gt;",
- }
- local privates_p={
- }
- local privates_s={
- [ [["]] ]="&U+22;",
- [ [[#]] ]="&U+23;",
- [ [[$]] ]="&U+24;",
- [ [[%]] ]="&U+25;",
- [ [[&]] ]="&U+26;",
- [ [[']] ]="&U+27;",
- [ [[<]] ]="&U+3C;",
- [ [[>]] ]="&U+3E;",
- [ [[\]] ]="&U+5C;",
- [ [[{]] ]="&U+7B;",
- [ [[|]] ]="&U+7C;",
- [ [[}]] ]="&U+7D;",
- [ [[~]] ]="&U+7E;",
- }
- local privates_x={
- [ [["]] ]="&U+22;",
- [ [[#]] ]="&U+23;",
- [ [[$]] ]="&U+24;",
- [ [[%]] ]="&U+25;",
- [ [[']] ]="&U+27;",
- [ [[\]] ]="&U+5C;",
- [ [[{]] ]="&U+7B;",
- [ [[|]] ]="&U+7C;",
- [ [[}]] ]="&U+7D;",
- [ [[~]] ]="&U+7E;",
- }
- local privates_n={
- }
- local escaped=utf.remapper(privates_u,"dynamic")
- local unprivatized=utf.remapper(privates_p,"dynamic")
- local unspecialized=utf.remapper(privates_s,"dynamic")
- local despecialized=utf.remapper(privates_x,"dynamic")
- xml.unprivatized=unprivatized
- xml.unspecialized=unspecialized
- xml.despecialized=despecialized
- xml.escaped=escaped
- local function unescaped(s)
- local p=privates_n[s]
- if not p then
- nofprivates=nofprivates+1
- p=utfchar(nofprivates)
- privates_n[s]=p
- s="&"..s..";"
- privates_u[p]=s
- privates_p[p]=s
- privates_s[p]=s
- end
- return p
- end
- xml.privatetoken=unescaped
- xml.privatecodes=privates_n
- xml.specialcodes=privates_s
- function xml.addspecialcode(key,value)
- privates_s[key]=value or "&"..s..";"
- end
- handle_hex_entity=function(str)
- local h=hcache[str]
- if not h then
- local n=tonumber(str,16)
- h=unify_predefined and predefined_unified[n]
- if h then
- if trace_entities then
- report_xml("utfize, converting hex entity &#x%s; into %a",str,h)
- end
- elseif utfize then
- h=(n and utfchar(n)) or xml.unknown_hex_entity(str) or ""
- if not n then
- report_xml("utfize, ignoring hex entity &#x%s;",str)
- elseif trace_entities then
- report_xml("utfize, converting hex entity &#x%s; into %a",str,h)
- end
- else
- if trace_entities then
- report_xml("found entity &#x%s;",str)
- end
- h="&#x"..str..";"
- end
- hcache[str]=h
- end
- return h
- end
- handle_dec_entity=function(str)
- local d=dcache[str]
- if not d then
- local n=tonumber(str)
- d=unify_predefined and predefined_unified[n]
- if d then
- if trace_entities then
- report_xml("utfize, converting dec entity &#%s; into %a",str,d)
- end
- elseif utfize then
- d=(n and utfchar(n)) or placeholders.unknown_dec_entity(str) or ""
- if not n then
- report_xml("utfize, ignoring dec entity &#%s;",str)
- elseif trace_entities then
- report_xml("utfize, converting dec entity &#%s; into %a",str,d)
- end
- else
- if trace_entities then
- report_xml("found entity &#%s;",str)
- end
- d="&#"..str..";"
- end
- dcache[str]=d
- end
- return d
- end
- handle_any_entity_dtd=function(str)
- if resolve then
- local a=resolve_predefined and predefined_simplified[str]
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to predefined %a",str,a)
- end
- else
- if type(resolve)=="function" then
- a=resolve(str,entities) or entities[str]
- else
- a=entities[str]
- end
- if a then
- if type(a)=="function" then
- if trace_entities then
- report_xml("expanding entity &%s; to function call",str)
- end
- a=a(str) or ""
- end
- a=lpegmatch(parsedentity,a) or a
- if trace_entities then
- report_xml("resolving entity &%s; to internal %a",str,a)
- end
- else
- local unknown_any_entity=placeholders.unknown_any_entity
- if unknown_any_entity then
- a=unknown_any_entity(str) or ""
- end
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to external %s",str,a)
- end
- else
- if trace_entities then
- report_xml("keeping entity &%s;",str)
- end
- if str=="" then
- a=badentity
- else
- a="&"..str..";"
- end
- end
- end
- end
- return a
- else
- local a=acache[str]
- if not a then
- a=resolve_predefined and predefined_simplified[str]
- if a then
- acache[str]=a
- if trace_entities then
- report_xml("entity &%s; becomes %a",str,a)
- end
- elseif str=="" then
- if trace_entities then
- report_xml("invalid entity &%s;",str)
- end
- a=badentity
- acache[str]=a
- else
- if trace_entities then
- report_xml("entity &%s; is made private",str)
- end
- a=unescaped(str)
- acache[str]=a
- end
- end
- return a
- end
- end
- handle_any_entity_text=function(str)
- if resolve then
- local a=resolve_predefined and predefined_simplified[str]
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to predefined %a",str,a)
- end
- else
- if type(resolve)=="function" then
- a=resolve(str,entities) or entities[str]
- else
- a=entities[str]
- end
- if a then
- if type(a)=="function" then
- if trace_entities then
- report_xml("expanding entity &%s; to function call",str)
- end
- a=a(str) or ""
- end
- a=lpegmatch(grammar_parsed_text_two,a) or a
- if type(a)=="number" then
- return ""
- else
- a=lpegmatch(parsedentity,a) or a
- if trace_entities then
- report_xml("resolving entity &%s; to internal %a",str,a)
- end
- end
- if trace_entities then
- report_xml("resolving entity &%s; to internal %a",str,a)
- end
- else
- local unknown_any_entity=placeholders.unknown_any_entity
- if unknown_any_entity then
- a=unknown_any_entity(str) or ""
- end
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to external %s",str,a)
- end
- else
- if trace_entities then
- report_xml("keeping entity &%s;",str)
- end
- if str=="" then
- a=badentity
- else
- a="&"..str..";"
- end
- end
- end
- end
- return a
- else
- local a=acache[str]
- if not a then
- a=resolve_predefined and predefined_simplified[str]
- if a then
- acache[str]=a
- if trace_entities then
- report_xml("entity &%s; becomes %a",str,a)
- end
- elseif str=="" then
- if trace_entities then
- report_xml("invalid entity &%s;",str)
- end
- a=badentity
- acache[str]=a
- else
- if trace_entities then
- report_xml("entity &%s; is made private",str)
- end
- a=unescaped(str)
- acache[str]=a
- end
- end
- return a
- end
- end
- local p_rest=(1-P(";"))^1
- local spec={
- [0x23]="\\Ux{23}",
- [0x24]="\\Ux{24}",
- [0x25]="\\Ux{25}",
- [0x5C]="\\Ux{5C}",
- [0x7B]="\\Ux{7B}",
- [0x7C]="\\Ux{7C}",
- [0x7D]="\\Ux{7D}",
- [0x7E]="\\Ux{7E}",
- }
- local hash=table.setmetatableindex(spec,function(t,k)
- local v=utfchar(k)
- t[k]=v
- return v
- end)
- local function fromuni(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["u:%s"](s),true
- end
- end
- local function fromhex(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["h:%s"](s),true
- end
- end
- local function fromdec(s)
- local n=tonumber(s)
- if n then
- return hash[n]
- else
- return formatters["d:%s"](s),true
- end
- end
- local reparsedentity=P("U+")*(p_rest/fromuni)+P("#")*(
- P("x")*(p_rest/fromhex)+p_rest/fromdec
- )
- local hash=table.setmetatableindex(function(t,k)
- local v=utfchar(k)
- t[k]=v
- return v
- end)
- local function fromuni(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["u:%s"](s),true
- end
- end
- local function fromhex(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["h:%s"](s),true
- end
- end
- local function fromdec(s)
- local n=tonumber(s)
- if n then
- return hash[n]
- else
- return formatters["d:%s"](s),true
- end
- end
- local unescapedentity=P("U+")*(p_rest/fromuni)+P("#")*(
- P("x")*(p_rest/fromhex)+p_rest/fromdec
- )
- xml.reparsedentitylpeg=reparsedentity
- xml.unescapedentitylpeg=unescapedentity
-end
-local escaped=xml.escaped
-local unescaped=xml.unescaped
-local placeholders=xml.placeholders
-local function handle_end_entity(str)
- report_xml("error in entity, %a found without ending %a",str,";")
- return str
-end
-local function handle_crap_error(chr)
- report_xml("error in parsing, unexpected %a found ",chr)
- add_text(chr)
- return chr
-end
-local function handlenewline()
- currentline=currentline+1
-end
-local spacetab=S(' \t')
-local space=S(' \r\n\t')
-local newline=lpegpatterns.newline/handlenewline
-local anything=P(1)
-local open=P('<')
-local close=P('>')
-local squote=S("'")
-local dquote=S('"')
-local equal=P('=')
-local slash=P('/')
-local colon=P(':')
-local semicolon=P(';')
-local ampersand=P('&')
-local valid_0=R("\128\255")
-local valid_1=R('az','AZ')+S('_')+valid_0
-local valid_2=valid_1+R('09')+S('-.')
-local valid=valid_1*valid_2^0
-local name_yes=C(valid^1)*colon*C(valid^1)
-local name_nop=C(P(true))*C(valid^1)
-local name=name_yes+name_nop
-local utfbom=lpegpatterns.utfbom
-local spacing=C(space^0)
-local space_nl=spacetab+newline
-local spacing_nl=Cs((space_nl)^0)
-local anything_nl=newline+P(1)
-local function weirdentity(k,v)
- if trace_entities then
- report_xml("registering %s entity %a as %a","weird",k,v)
- end
- parameters[k]=v
-end
-local function normalentity(k,v)
- if trace_entities then
- report_xml("registering %s entity %a as %a","normal",k,v)
- end
- entities[k]=v
-end
-local function systementity(k,v,n)
- if trace_entities then
- report_xml("registering %s entity %a as %a","system",k,v)
- end
- entities[k]=v
-end
-local function publicentity(k,v,n)
- if trace_entities then
- report_xml("registering %s entity %a as %a","public",k,v)
- end
- entities[k]=v
-end
-local function entityfile(pattern,k,v,n)
- if n then
- local okay,data
- local loadbinfile=resolvers and resolvers.loadbinfile
- if loadbinfile then
- okay,data=loadbinfile(n)
- else
- data=io.loaddata(n)
- okay=data and data~=""
- end
- if okay then
- if trace_entities then
- report_xml("loading public entities %a as %a from %a",k,v,n)
- end
- lpegmatch(pattern,data)
- return
- end
- end
- report_xml("ignoring public entities %a as %a from %a",k,v,n)
-end
-local function install(spacenewline,spacing,anything)
- local anyentitycontent=(1-open-semicolon-space-close-ampersand)^0
- local hexentitycontent=R("AF","af","09")^1
- local decentitycontent=R("09")^1
- local parsedentity=P("#")/""*(
- P("x")/""*(hexentitycontent/handle_hex_entity)+(decentitycontent/handle_dec_entity)
- )+(anyentitycontent/handle_any_entity_dtd)
- local parsedentity_text=P("#")/""*(
- P("x")/""*(hexentitycontent/handle_hex_entity)+(decentitycontent/handle_dec_entity)
- )+(anyentitycontent/handle_any_entity_text)
- local entity=(ampersand/"")*parsedentity*(semicolon/"")+ampersand*(anyentitycontent/handle_end_entity)
- local entity_text=(ampersand/"")*parsedentity_text*(semicolon/"")+ampersand*(anyentitycontent/handle_end_entity)
- local text_unparsed=Cs((anything-open)^1)
- local text_parsed=(Cs((anything-open-ampersand)^1)/add_text+Cs(entity_text)/add_text)^1
- local somespace=(spacenewline)^1
- local optionalspace=(spacenewline)^0
- local value=(squote*Cs((entity+(anything-squote))^0)*squote)+(dquote*Cs((entity+(anything-dquote))^0)*dquote)
- local endofattributes=slash*close+close
- local whatever=space*name*optionalspace*equal
- local wrongvalue=Cs(P(entity+(1-space-endofattributes))^1)/attribute_value_error
- local attributevalue=value+wrongvalue
- local attribute=(somespace*name*optionalspace*equal*optionalspace*attributevalue)/add_attribute
- local attributes=(attribute+somespace^-1*(((anything-endofattributes)^1)/attribute_specification_error))^0
- local parsedtext=text_parsed
- local unparsedtext=text_unparsed/add_text
- local balanced=P { "["*((anything-S"[]")+V(1))^0*"]" }
- local emptyelement=(spacing*open*name*attributes*optionalspace*slash*close)/add_empty
- local beginelement=(spacing*open*name*attributes*optionalspace*close)/add_begin
- local endelement=(spacing*open*slash*name*optionalspace*close)/add_end
- local begincomment=open*P("!--")
- local endcomment=P("--")*close
- local begininstruction=open*P("?")
- local endinstruction=P("?")*close
- local begincdata=open*P("![CDATA[")
- local endcdata=P("]]")*close
- local someinstruction=C((anything-endinstruction)^0)
- local somecomment=C((anything-endcomment )^0)
- local somecdata=C((anything-endcdata )^0)
- local begindoctype=open*P("!DOCTYPE")
- local enddoctype=close
- local beginset=P("[")
- local endset=P("]")
- local wrdtypename=C((anything-somespace-P(";"))^1)
- local doctypename=C((anything-somespace-close)^0)
- local elementdoctype=optionalspace*P("<!ELEMENT")*(anything-close)^0*close
- local basiccomment=begincomment*((anything-endcomment)^0)*endcomment
- local weirdentitytype=P("%")*(somespace*doctypename*somespace*value)/weirdentity
- local normalentitytype=(doctypename*somespace*value)/normalentity
- local publicentitytype=(doctypename*somespace*P("PUBLIC")*somespace*value)/publicentity
- local systementitytype=(doctypename*somespace*P("SYSTEM")*somespace*value*somespace*P("NDATA")*somespace*doctypename)/systementity
- local entitydoctype=optionalspace*P("<!ENTITY")*somespace*(systementitytype+publicentitytype+normalentitytype+weirdentitytype)*optionalspace*close
- local publicentityfile=(doctypename*somespace*P("PUBLIC")*somespace*value*(somespace*value)^0)/function(...)
- entityfile(entitydoctype,...)
- end
- local function weirdresolve(s)
- lpegmatch(entitydoctype,parameters[s])
- end
- local function normalresolve(s)
- lpegmatch(entitydoctype,entities[s])
- end
- local entityresolve=P("%")*(wrdtypename/weirdresolve )*P(";")+P("&")*(wrdtypename/normalresolve)*P(";")
- entitydoctype=entitydoctype+entityresolve
- local doctypeset=beginset*optionalspace*P(elementdoctype+entitydoctype+entityresolve+basiccomment+space)^0*optionalspace*endset
- local definitiondoctype=doctypename*somespace*doctypeset
- local publicdoctype=doctypename*somespace*P("PUBLIC")*somespace*value*somespace*value*somespace*doctypeset
- local systemdoctype=doctypename*somespace*P("SYSTEM")*somespace*value*somespace*doctypeset
- local simpledoctype=(anything-close)^1
- local somedoctype=C((somespace*(
-publicentityfile+publicdoctype+systemdoctype+definitiondoctype+simpledoctype)*optionalspace)^0)
- local instruction=(spacing*begininstruction*someinstruction*endinstruction)/function(...) add_special("@pi@",...) end
- local comment=(spacing*begincomment*somecomment*endcomment )/function(...) add_special("@cm@",...) end
- local cdata=(spacing*begincdata*somecdata*endcdata )/function(...) add_special("@cd@",...) end
- local doctype=(spacing*begindoctype*somedoctype*enddoctype )/function(...) add_special("@dt@",...) end
- local crap_parsed=anything-beginelement-endelement-emptyelement-begininstruction-begincomment-begincdata-ampersand
- local crap_unparsed=anything-beginelement-endelement-emptyelement-begininstruction-begincomment-begincdata
- local parsedcrap=Cs((crap_parsed^1+entity_text)^1)/handle_crap_error
- local parsedcrap=Cs((crap_parsed^1+entity_text)^1)/handle_crap_error
- local unparsedcrap=Cs((crap_unparsed )^1)/handle_crap_error
- local trailer=space^0*(text_unparsed/set_message)^0
- local grammar_parsed_text_one=P { "preamble",
- preamble=utfbom^0*instruction^0*(doctype+comment+instruction)^0,
- }
- local grammar_parsed_text_two=P { "followup",
- followup=V("parent")*trailer,
- parent=beginelement*V("children")^0*endelement,
- children=parsedtext+V("parent")+emptyelement+comment+cdata+instruction+parsedcrap,
- }
- local grammar_unparsed_text=P { "preamble",
- preamble=utfbom^0*instruction^0*(doctype+comment+instruction)^0*V("parent")*trailer,
- parent=beginelement*V("children")^0*endelement,
- children=unparsedtext+V("parent")+emptyelement+comment+cdata+instruction+unparsedcrap,
- }
- return grammar_parsed_text_one,grammar_parsed_text_two,grammar_unparsed_text
-end
-local
- grammar_parsed_text_one_nop,
- grammar_parsed_text_two_nop,
- grammar_unparsed_text_nop=install(space,spacing,anything)
-local
- grammar_parsed_text_one_yes,
- grammar_parsed_text_two_yes,
- grammar_unparsed_text_yes=install(space_nl,spacing_nl,anything_nl)
-local function _xmlconvert_(data,settings,detail)
- settings=settings or {}
- preparexmlstate(settings)
- if settings.linenumbers then
- grammar_parsed_text_one=grammar_parsed_text_one_yes
- grammar_parsed_text_two=grammar_parsed_text_two_yes
- grammar_unparsed_text=grammar_unparsed_text_yes
- else
- grammar_parsed_text_one=grammar_parsed_text_one_nop
- grammar_parsed_text_two=grammar_parsed_text_two_nop
- grammar_unparsed_text=grammar_unparsed_text_nop
- end
- local preprocessor=settings.preprocessor
- if data and data~="" and type(preprocessor)=="function" then
- data=preprocessor(data,settings) or data
- end
- if settings.parent_root then
- mt=getmetatable(settings.parent_root)
- else
- initialize_mt(top)
- end
- level=level+1
- stack[level]=top
- top.dt={}
- dt=top.dt
- nt=0
- if not data or data=="" then
- errorstr="empty xml file"
- elseif data==true then
- errorstr=detail or "problematic xml file"
- elseif utfize or resolve then
- local m=lpegmatch(grammar_parsed_text_one,data)
- if m then
- m=lpegmatch(grammar_parsed_text_two,data,m)
- end
- if m then
- else
- errorstr="invalid xml file - parsed text"
- end
- elseif type(data)=="string" then
- if lpegmatch(grammar_unparsed_text,data) then
- errorstr=""
- else
- errorstr="invalid xml file - unparsed text"
- end
- else
- errorstr="invalid xml file - no text at all"
- end
- local result
- if errorstr and errorstr~="" then
- result={ dt={ { ns="",tg="error",dt={ errorstr },at={},er=true } } }
- setmetatable(result,mt)
- setmetatable(result.dt[1],mt)
- setmetatable(stack,mt)
- local errorhandler=settings.error_handler
- if errorhandler==false then
- else
- errorhandler=errorhandler or xml.errorhandler
- if errorhandler then
- local currentresource=settings.currentresource
- if currentresource and currentresource~="" then
- xml.errorhandler(formatters["load error in [%s]: %s"](currentresource,errorstr),currentresource)
- else
- xml.errorhandler(formatters["load error: %s"](errorstr))
- end
- end
- end
- else
- result=stack[1]
- end
- if not settings.no_root then
- result={ special=true,ns="",tg='@rt@',dt=result.dt,at={},entities=entities,settings=settings }
- setmetatable(result,mt)
- local rdt=result.dt
- for k=1,#rdt do
- local v=rdt[k]
- if type(v)=="table" and not v.special then
- result.ri=k
- v.__p__=result
- break
- end
- end
- end
- if errorstr and errorstr~="" then
- result.error=true
- else
- errorstr=nil
- end
- result.statistics={
- errormessage=errorstr,
- entities={
- decimals=dcache,
- hexadecimals=hcache,
- names=acache,
- intermediates=parameters,
- }
- }
- preparexmlstate()
- return result
-end
-local function xmlconvert(data,settings)
- local ok,result=pcall(function() return _xmlconvert_(data,settings) end)
- if ok then
- return result
- elseif type(result)=="string" then
- return _xmlconvert_(true,settings,result)
- else
- return _xmlconvert_(true,settings)
- end
-end
-xml.convert=xmlconvert
-function xml.inheritedconvert(data,xmldata,cleanup)
- local settings=xmldata.settings
- if settings then
- settings.parent_root=xmldata
- end
- local xc=xmlconvert(data,settings)
- if cleanup then
- local x=xc.dt
- if x then
- x=x[1]
- if x and x.tg=="@pi@" then
- local dt=x.dt
- local pi=dt and dt[1]
- if type(pi)=="string" and find(pi,"^xml") then
- remove(dt,1)
- end
- end
- end
- end
- return xc
-end
-function xml.is_valid(root)
- return root and root.dt and root.dt[1] and type(root.dt[1])=="table" and not root.dt[1].er
-end
-function xml.package(tag,attributes,data)
- local ns,tg=match(tag,"^(.-):?([^:]+)$")
- local t={ ns=ns,tg=tg,dt=data or "",at=attributes or {} }
- setmetatable(t,mt)
- return t
-end
-function xml.is_valid(root)
- return root and not root.error
-end
-xml.errorhandler=report_xml
-function xml.load(filename,settings)
- local data=""
- if type(filename)=="string" then
- local f=io.open(filename,'r')
- if f then
- data=f:read("*all")
- f:close()
- end
- elseif filename then
- data=filename:read("*all")
- end
- if settings then
- settings.currentresource=filename
- local result=xmlconvert(data,settings)
- settings.currentresource=nil
- return result
- else
- return xmlconvert(data,{ currentresource=filename })
- end
-end
-local no_root={ no_root=true }
-function xml.toxml(data)
- if type(data)=="string" then
- local root={ xmlconvert(data,no_root) }
- return (#root>1 and root) or root[1]
- else
- return data
- end
-end
-local function copy(old,p)
- if old then
- local new={}
- for k,v in next,old do
- local t=type(v)=="table"
- if k=="at" then
- local t={}
- for k,v in next,v do
- t[k]=v
- end
- new[k]=t
- elseif k=="dt" then
- v.__p__=nil
- local t={}
- for i=1,#v do
- local vi=v[i]
- if type(vi)=="table" then
- t[i]=copy(vi,new)
- else
- t[i]=vi
- end
- end
- new[k]=t
- t.__p__=p
- else
- new[k]=v
- end
- end
- local mt=getmetatable(old)
- if mt then
- setmetatable(new,mt)
- end
- return new
- else
- return {}
- end
-end
-xml.copy=copy
-function xml.checkbom(root)
- if root.ri then
- local dt=root.dt
- for k=1,#dt do
- local v=dt[k]
- if type(v)=="table" and v.special and v.tg=="@pi@" and find(v.dt[1],"xml.*version=") then
- return
- end
- end
- insert(dt,1,{ special=true,ns="",tg="@pi@",dt={ "xml version='1.0' standalone='yes'" } } )
- insert(dt,2,"\n" )
- end
-end
-local f_attribute=formatters['%s=%q']
-local function verbose_element(e,handlers,escape)
- local handle=handlers.handle
- local serialize=handlers.serialize
- local ens,etg,eat,edt,ern=e.ns,e.tg,e.at,e.dt,e.rn
- local ats=eat and next(eat) and {}
- if ats then
- local n=0
- for k in next,eat do
- n=n+1
- ats[n]=k
- end
- if n==1 then
- local k=ats[1]
- ats=f_attribute(k,escaped(eat[k]))
- else
- sort(ats)
- for i=1,n do
- local k=ats[i]
- ats[i]=f_attribute(k,escaped(eat[k]))
- end
- ats=concat(ats," ")
- end
- end
- if ern and trace_entities and ern~=ens then
- ens=ern
- end
- local n=edt and #edt
- if ens~="" then
- if n and n>0 then
- if ats then
- handle("<",ens,":",etg," ",ats,">")
- else
- handle("<",ens,":",etg,">")
- end
- for i=1,n do
- local e=edt[i]
- if type(e)=="string" then
- handle(escaped(e))
- else
- serialize(e,handlers)
- end
- end
- handle("</",ens,":",etg,">")
- else
- if ats then
- handle("<",ens,":",etg," ",ats,"/>")
- else
- handle("<",ens,":",etg,"/>")
- end
- end
- else
- if n and n>0 then
- if ats then
- handle("<",etg," ",ats,">")
- else
- handle("<",etg,">")
- end
- for i=1,n do
- local e=edt[i]
- if type(e)=="string" then
- handle(escaped(e))
- else
- serialize(e,handlers)
- end
- end
- handle("</",etg,">")
- else
- if ats then
- handle("<",etg," ",ats,"/>")
- else
- handle("<",etg,"/>")
- end
- end
- end
-end
-local function verbose_pi(e,handlers)
- handlers.handle("<?",e.dt[1],"?>")
-end
-local function verbose_comment(e,handlers)
- handlers.handle("<!--",e.dt[1],"-->")
-end
-local function verbose_cdata(e,handlers)
- handlers.handle("<![CDATA[",e.dt[1],"]]>")
-end
-local function verbose_doctype(e,handlers)
- handlers.handle("<!DOCTYPE",e.dt[1],">")
-end
-local function verbose_root(e,handlers)
- handlers.serialize(e.dt,handlers)
-end
-local function verbose_text(e,handlers)
- handlers.handle(escaped(e))
-end
-local function verbose_document(e,handlers)
- local serialize=handlers.serialize
- local functions=handlers.functions
- for i=1,#e do
- local ei=e[i]
- if type(ei)=="string" then
- functions["@tx@"](ei,handlers)
- else
- serialize(ei,handlers)
- end
- end
-end
-local function serialize(e,handlers,...)
- if e then
- local initialize=handlers.initialize
- local finalize=handlers.finalize
- local functions=handlers.functions
- if initialize then
- local state=initialize(...)
- if not state==true then
- return state
- end
- end
- local etg=e.tg
- if etg then
- (functions[etg] or functions["@el@"])(e,handlers)
- else
- functions["@dc@"](e,handlers)
- end
- if finalize then
- return finalize()
- end
- end
-end
-local function xserialize(e,handlers)
- if e then
- local functions=handlers.functions
- local etg=e.tg
- if etg then
- (functions[etg] or functions["@el@"])(e,handlers)
- else
- functions["@dc@"](e,handlers)
- end
- end
-end
-local handlers={}
-local function newhandlers(settings)
- local t=table.copy(handlers[settings and settings.parent or "verbose"] or {})
- if settings then
- for k,v in next,settings do
- if type(v)=="table" then
- local tk=t[k] if not tk then tk={} t[k]=tk end
- for kk,vv in next,v do
- tk[kk]=vv
- end
- else
- t[k]=v
- end
- end
- if settings.name then
- handlers[settings.name]=t
- end
- end
- utilities.storage.mark(t)
- return t
-end
-local nofunction=function() end
-function xml.sethandlersfunction(handler,name,fnc)
- handler.functions[name]=fnc or nofunction
-end
-function xml.gethandlersfunction(handler,name)
- return handler.functions[name]
-end
-function xml.gethandlers(name)
- return handlers[name]
-end
-newhandlers {
- name="verbose",
- initialize=false,
- finalize=false,
- serialize=xserialize,
- handle=print,
- functions={
- ["@dc@"]=verbose_document,
- ["@dt@"]=verbose_doctype,
- ["@rt@"]=verbose_root,
- ["@el@"]=verbose_element,
- ["@pi@"]=verbose_pi,
- ["@cm@"]=verbose_comment,
- ["@cd@"]=verbose_cdata,
- ["@tx@"]=verbose_text,
- }
-}
-local result
-local xmlfilehandler=newhandlers {
- name="file",
- initialize=function(name)
- result=io.open(name,"wb")
- return result
- end,
- finalize=function()
- result:close()
- return true
- end,
- handle=function(...)
- result:write(...)
- end,
-}
-function xml.save(root,name)
- serialize(root,xmlfilehandler,name)
-end
-local result,r,threshold={},0,512
-local xmlstringhandler=newhandlers {
- name="string",
- initialize=function()
- r=0
- return result
- end,
- finalize=function()
- local done=concat(result,"",1,r)
- r=0
- if r>threshold then
- result={}
- end
- return done
- end,
- handle=function(...)
- for i=1,select("#",...) do
- r=r+1
- result[r]=select(i,...)
- end
- end,
-}
-local function xmltostring(root)
- if not root then
- return ""
- elseif type(root)=="string" then
- return root
- else
- return serialize(root,xmlstringhandler) or ""
- end
-end
-local function __tostring(root)
- return (root and xmltostring(root)) or ""
-end
-initialize_mt=function(root)
- mt={ __tostring=__tostring,__index=root }
-end
-xml.defaulthandlers=handlers
-xml.newhandlers=newhandlers
-xml.serialize=serialize
-xml.tostring=xmltostring
-local function xmlstring(e,handle)
- if not handle or (e.special and e.tg~="@rt@") then
- elseif e.tg then
- local edt=e.dt
- if edt then
- for i=1,#edt do
- xmlstring(edt[i],handle)
- end
- end
- else
- handle(e)
- end
-end
-xml.string=xmlstring
-function xml.settings(e)
- while e do
- local s=e.settings
- if s then
- return s
- else
- e=e.__p__
- end
- end
- return nil
-end
-function xml.root(e)
- local r=e
- while e do
- e=e.__p__
- if e then
- r=e
- end
- end
- return r
-end
-function xml.parent(root)
- return root.__p__
-end
-function xml.body(root)
- return root.ri and root.dt[root.ri] or root
-end
-function xml.name(root)
- if not root then
- return ""
- end
- local ns=root.ns
- local tg=root.tg
- if ns=="" then
- return tg
- else
- return ns..":"..tg
- end
-end
-function xml.erase(dt,k)
- if dt then
- if k then
- dt[k]=""
- else for k=1,#dt do
- dt[1]={ "" }
- end end
- end
-end
-function xml.assign(dt,k,root)
- if dt and k then
- dt[k]=type(root)=="table" and xml.body(root) or root
- return dt[k]
- else
- return xml.body(root)
- end
-end
-function xml.tocdata(e,wrapper)
- local whatever=type(e)=="table" and xmltostring(e.dt) or e or ""
- if wrapper then
- whatever=formatters["<%s>%s</%s>"](wrapper,whatever,wrapper)
- end
- local t={ special=true,ns="",tg="@cd@",at={},rn="",dt={ whatever },__p__=e }
- setmetatable(t,getmetatable(e))
- e.dt={ t }
-end
-function xml.makestandalone(root)
- if root.ri then
- local dt=root.dt
- for k=1,#dt do
- local v=dt[k]
- if type(v)=="table" and v.special and v.tg=="@pi@" then
- local txt=v.dt[1]
- if find(txt,"xml.*version=") then
- v.dt[1]=txt.." standalone='yes'"
- break
- end
- end
- end
- end
- return root
-end
-function xml.kind(e)
- local dt=e and e.dt
- if dt then
- local n=#dt
- if n==1 then
- local d=dt[1]
- if d.special then
- local tg=d.tg
- if tg=="@cd@" then
- return "cdata"
- elseif tg=="@cm" then
- return "comment"
- elseif tg=="@pi@" then
- return "instruction"
- elseif tg=="@dt@" then
- return "declaration"
- end
- elseif type(d)=="string" then
- return "text"
- end
- return "element"
- elseif n>0 then
- return "mixed"
- end
- end
- return "empty"
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-lpt"] = package.loaded["lxml-lpt"] or true
-
--- original size: 54667, stripped down to: 31258
-
-if not modules then modules={} end modules ['lxml-lpt']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local concat,remove,insert=table.concat,table.remove,table.insert
-local type,next,tonumber,tostring,setmetatable,load,select=type,next,tonumber,tostring,setmetatable,load,select
-local format,upper,lower,gmatch,gsub,find,rep=string.format,string.upper,string.lower,string.gmatch,string.gsub,string.find,string.rep
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local setmetatableindex=table.setmetatableindex
-local formatters=string.formatters
-local trace_lpath=false
-local trace_lparse=false
-local trace_lprofile=false
-local report_lpath=logs.reporter("xml","lpath")
-if trackers then
- trackers.register("xml.path",function(v)
- trace_lpath=v
- end)
- trackers.register("xml.parse",function(v)
- trace_lparse=v
- end)
- trackers.register("xml.profile",function(v)
- trace_lpath=v
- trace_lparse=v
- trace_lprofile=v
- end)
-end
-local xml=xml
-local lpathcalls=0 function xml.lpathcalls () return lpathcalls end
-local lpathcached=0 function xml.lpathcached() return lpathcached end
-xml.functions=xml.functions or {}
-local functions=xml.functions
-xml.expressions=xml.expressions or {}
-local expressions=xml.expressions
-xml.finalizers=xml.finalizers or {}
-local finalizers=xml.finalizers
-xml.specialhandler=xml.specialhandler or {}
-local specialhandler=xml.specialhandler
-lpegpatterns.xml=lpegpatterns.xml or {}
-local xmlpatterns=lpegpatterns.xml
-finalizers.xml=finalizers.xml or {}
-finalizers.tex=finalizers.tex or {}
-local function fallback (t,name)
- local fn=finalizers[name]
- if fn then
- t[name]=fn
- else
- report_lpath("unknown sub finalizer %a",name)
- fn=function() end
- end
- return fn
-end
-setmetatableindex(finalizers.xml,fallback)
-setmetatableindex(finalizers.tex,fallback)
-xml.defaultprotocol="xml"
-local apply_axis={}
-apply_axis['root']=function(list)
- local collected={}
- for l=1,#list do
- local ll=list[l]
- local rt=ll
- while ll do
- ll=ll.__p__
- if ll then
- rt=ll
- end
- end
- collected[l]=rt
- end
- return collected
-end
-apply_axis['self']=function(list)
- return list
-end
-apply_axis['child']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local dt=ll.dt
- if dt then
- local n=#dt
- if n==0 then
- ll.en=0
- elseif n==1 then
- local dk=dt[1]
- if dk.tg then
- c=c+1
- collected[c]=dk
- dk.ni=1
- dk.ei=1
- ll.en=1
- end
- else
- local en=0
- for k=1,#dt do
- local dk=dt[k]
- if dk.tg then
- c=c+1
- en=en+1
- collected[c]=dk
- dk.ni=k
- dk.ei=en
- end
- end
- ll.en=en
- end
- end
- end
- return collected
-end
-local function collect(list,collected,c)
- local dt=list.dt
- if dt then
- local n=#dt
- if n==0 then
- list.en=0
- elseif n==1 then
- local dk=dt[1]
- if dk.tg then
- c=c+1
- collected[c]=dk
- dk.ni=1
- dk.ei=1
- c=collect(dk,collected,c)
- list.en=1
- else
- list.en=0
- end
- else
- local en=0
- for k=1,n do
- local dk=dt[k]
- if dk.tg then
- c=c+1
- en=en+1
- collected[c]=dk
- dk.ni=k
- dk.ei=en
- c=collect(dk,collected,c)
- end
- end
- list.en=en
- end
- end
- return c
-end
-apply_axis['descendant']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- c=collect(list[l],collected,c)
- end
- return collected
-end
-local function collect(list,collected,c)
- local dt=list.dt
- if dt then
- local n=#dt
- if n==0 then
- list.en=0
- elseif n==1 then
- local dk=dt[1]
- if dk.tg then
- c=c+1
- collected[c]=dk
- dk.ni=1
- dk.ei=1
- c=collect(dk,collected,c)
- list.en=1
- end
- else
- local en=0
- for k=1,#dt do
- local dk=dt[k]
- if dk.tg then
- c=c+1
- en=en+1
- collected[c]=dk
- dk.ni=k
- dk.ei=en
- c=collect(dk,collected,c)
- end
- end
- list.en=en
- end
- end
- return c
-end
-apply_axis['descendant-or-self']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- if ll.special~=true then
- c=c+1
- collected[c]=ll
- end
- c=collect(ll,collected,c)
- end
- return collected
-end
-apply_axis['ancestor']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- while ll do
- ll=ll.__p__
- if ll then
- c=c+1
- collected[c]=ll
- end
- end
- end
- return collected
-end
-apply_axis['ancestor-or-self']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- c=c+1
- collected[c]=ll
- while ll do
- ll=ll.__p__
- if ll then
- c=c+1
- collected[c]=ll
- end
- end
- end
- return collected
-end
-apply_axis['parent']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local pl=list[l].__p__
- if pl then
- c=c+1
- collected[c]=pl
- end
- end
- return collected
-end
-apply_axis['attribute']=function(list)
- return {}
-end
-apply_axis['namespace']=function(list)
- return {}
-end
-apply_axis['following']=function(list)
- return {}
-end
-apply_axis['preceding']=function(list)
- return {}
-end
-apply_axis['following-sibling']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local p=ll.__p__
- local d=p.dt
- for i=ll.ni+1,#d do
- local di=d[i]
- if type(di)=="table" then
- c=c+1
- collected[c]=di
- end
- end
- end
- return collected
-end
-apply_axis['preceding-sibling']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local p=ll.__p__
- local d=p.dt
- for i=1,ll.ni-1 do
- local di=d[i]
- if type(di)=="table" then
- c=c+1
- collected[c]=di
- end
- end
- end
- return collected
-end
-apply_axis['reverse-sibling']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local p=ll.__p__
- local d=p.dt
- for i=ll.ni-1,1,-1 do
- local di=d[i]
- if type(di)=="table" then
- c=c+1
- collected[c]=di
- end
- end
- end
- return collected
-end
-apply_axis['auto-descendant-or-self']=apply_axis['descendant-or-self']
-apply_axis['auto-descendant']=apply_axis['descendant']
-apply_axis['auto-child']=apply_axis['child']
-apply_axis['auto-self']=apply_axis['self']
-apply_axis['initial-child']=apply_axis['child']
-local function apply_nodes(list,directive,nodes)
- local maxn=#nodes
- if maxn==3 then
- local nns=nodes[2]
- local ntg=nodes[3]
- if not nns and not ntg then
- if directive then
- return list
- else
- return {}
- end
- else
- local collected={}
- local c=0
- local m=0
- local p=nil
- if not nns then
- for l=1,#list do
- local ll=list[l]
- local ltg=ll.tg
- if ltg then
- if directive then
- if ntg==ltg then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif ntg~=ltg then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- elseif not ntg then
- for l=1,#list do
- local ll=list[l]
- local lns=ll.rn or ll.ns
- if lns then
- if directive then
- if lns==nns then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif lns~=nns then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- else
- for l=1,#list do
- local ll=list[l]
- local ltg=ll.tg
- if ltg then
- local lns=ll.rn or ll.ns
- local ok=ltg==ntg and lns==nns
- if directive then
- if ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif not ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- end
- return collected
- end
- else
- local collected={}
- local c=0
- local m=0
- local p=nil
- for l=1,#list do
- local ll=list[l]
- local ltg=ll.tg
- if ltg then
- local lns=ll.rn or ll.ns
- local ok=false
- for n=1,maxn,3 do
- local nns=nodes[n+1]
- local ntg=nodes[n+2]
- ok=(not ntg or ltg==ntg) and (not nns or lns==nns)
- if ok then
- break
- end
- end
- if directive then
- if ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif not ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- return collected
- end
-end
-local quit_expression=false
-local function apply_expression(list,expression,order)
- local collected={}
- local c=0
- quit_expression=false
- for l=1,#list do
- local ll=list[l]
- if expression(list,ll,l,order) then
- c=c+1
- collected[c]=ll
- end
- if quit_expression then
- break
- end
- end
- return collected
-end
-local function apply_selector(list,specification)
- if xml.applyselector then
- apply_selector=xml.applyselector
- return apply_selector(list,specification)
- else
- return list
- end
-end
-local P,V,C,Cs,Cc,Ct,R,S,Cg,Cb=lpeg.P,lpeg.V,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Ct,lpeg.R,lpeg.S,lpeg.Cg,lpeg.Cb
-local spaces=S(" \n\r\t\f")^0
-local lp_space=S(" \n\r\t\f")
-local lp_any=P(1)
-local lp_noequal=P("!=")/"~="+P("<=")+P(">=")+P("==")
-local lp_doequal=P("=")/"=="
-local lp_or=P("|")/" or "
-local lp_and=P("&")/" and "
-local builtin={
- text="(ll.dt[1] or '')",
- content="ll.dt",
- name="((ll.ns~='' and ll.ns..':'..ll.tg) or ll.tg)",
- tag="ll.tg",
- position="l",
- firstindex="1",
- firstelement="1",
- first="1",
- lastindex="(#ll.__p__.dt or 1)",
- lastelement="(ll.__p__.en or 1)",
- last="#list",
- list="list",
- self="ll",
- rootposition="order",
- order="order",
- element="(ll.ei or 1)",
- index="(ll.ni or 1)",
- match="(ll.mi or 1)",
- namespace="ll.ns",
- ns="ll.ns",
-}
-local lp_builtin=lpeg.utfchartabletopattern(builtin)/builtin*((spaces*P("(")*spaces*P(")"))/"")
-local lp_attribute=(P("@")+P("attribute::"))/""*Cc("(ll.at and ll.at['")*((R("az","AZ")+S("-_:"))^1)*Cc("'])")
-local lp_fastpos_p=P("+")^0*R("09")^1*P(-1)/"l==%0"
-local lp_fastpos_n=P("-")*R("09")^1*P(-1)/"(%0<0 and (#list+%0+1==l))"
-local lp_fastpos=lp_fastpos_n+lp_fastpos_p
-local lp_reserved=C("and")+C("or")+C("not")+C("div")+C("mod")+C("true")+C("false")
-local lp_lua_function=Cs((R("az","AZ","__")^1*(P(".")*R("az","AZ","__")^1)^1)*("("))/"%0"
-local lp_function=C(R("az","AZ","__")^1)*P("(")/function(t)
- if expressions[t] then
- return "expr."..t.."("
- else
- return "expr.error("
- end
-end
-local lparent=P("(")
-local rparent=P(")")
-local noparent=1-(lparent+rparent)
-local nested=P{lparent*(noparent+V(1))^0*rparent}
-local value=P(lparent*C((noparent+nested)^0)*rparent)
-local lp_child=Cc("expr.child(ll,'")*R("az","AZ")*R("az","AZ","--","__")^0*Cc("')")
-local lp_number=S("+-")*R("09")^1
-local lp_string=Cc("'")*R("az","AZ","--","__")^1*Cc("'")
-local lp_content=(P("'")*(1-P("'"))^0*P("'")+P('"')*(1-P('"'))^0*P('"'))
-local cleaner
-local lp_special=(C(P("name")+P("text")+P("tag")+P("count")+P("child")))*value/function(t,s)
- if expressions[t] then
- s=s and s~="" and lpegmatch(cleaner,s)
- if s and s~="" then
- return "expr."..t.."(ll,"..s..")"
- else
- return "expr."..t.."(ll)"
- end
- else
- return "expr.error("..t..")"
- end
-end
-local content=lp_builtin+lp_attribute+lp_special+lp_noequal+lp_doequal+lp_or+lp_and+lp_reserved+lp_lua_function+lp_function+lp_content+
- lp_child+lp_any
-local converter=Cs (
- lp_fastpos+(P { lparent*(V(1))^0*rparent+content } )^0
-)
-cleaner=Cs ((
- lp_reserved+lp_number+lp_string+1 )^1 )
-local template_e=[[
- local expr = xml.expressions
- return function(list,ll,l,order)
- return %s
- end
-]]
-local template_f_y=[[
- local finalizer = xml.finalizers['%s']['%s']
- return function(collection)
- return finalizer(collection,%s)
- end
-]]
-local template_f_n=[[
- return xml.finalizers['%s']['%s']
-]]
-local register_last_match={ kind="axis",axis="last-match" }
-local register_self={ kind="axis",axis="self" }
-local register_parent={ kind="axis",axis="parent" }
-local register_descendant={ kind="axis",axis="descendant" }
-local register_child={ kind="axis",axis="child" }
-local register_descendant_or_self={ kind="axis",axis="descendant-or-self" }
-local register_root={ kind="axis",axis="root" }
-local register_ancestor={ kind="axis",axis="ancestor" }
-local register_ancestor_or_self={ kind="axis",axis="ancestor-or-self" }
-local register_attribute={ kind="axis",axis="attribute" }
-local register_namespace={ kind="axis",axis="namespace" }
-local register_following={ kind="axis",axis="following" }
-local register_following_sibling={ kind="axis",axis="following-sibling" }
-local register_preceding={ kind="axis",axis="preceding" }
-local register_preceding_sibling={ kind="axis",axis="preceding-sibling" }
-local register_reverse_sibling={ kind="axis",axis="reverse-sibling" }
-local register_auto_descendant_or_self={ kind="axis",axis="auto-descendant-or-self" }
-local register_auto_descendant={ kind="axis",axis="auto-descendant" }
-local register_auto_self={ kind="axis",axis="auto-self" }
-local register_auto_child={ kind="axis",axis="auto-child" }
-local register_initial_child={ kind="axis",axis="initial-child" }
-local register_all_nodes={ kind="nodes",nodetest=true,nodes={ true,false,false } }
-local skip={}
-local function errorrunner_e(str,cnv)
- if not skip[str] then
- report_lpath("error in expression: %s => %s",str,cnv)
- skip[str]=cnv or str
- end
- return false
-end
-local function errorrunner_f(str,arg)
- report_lpath("error in finalizer: %s(%s)",str,arg or "")
- return false
-end
-local function register_nodes(nodetest,nodes)
- return { kind="nodes",nodetest=nodetest,nodes=nodes }
-end
-local function register_selector(specification)
- return { kind="selector",specification=specification }
-end
-local function register_expression(expression)
- local converted=lpegmatch(converter,expression)
- local wrapped=format(template_e,converted)
- local runner=load(wrapped)
- runner=(runner and runner()) or function() errorrunner_e(expression,converted) end
- return { kind="expression",expression=expression,converted=converted,evaluator=runner }
-end
-local function register_finalizer(protocol,name,arguments)
- local runner
- if arguments and arguments~="" then
- runner=load(format(template_f_y,protocol or xml.defaultprotocol,name,arguments))
- else
- runner=load(format(template_f_n,protocol or xml.defaultprotocol,name))
- end
- runner=(runner and runner()) or function() errorrunner_f(name,arguments) end
- return { kind="finalizer",name=name,arguments=arguments,finalizer=runner }
-end
-local expression=P { "ex",
- ex="["*C((V("sq")+V("dq")+(1-S("[]"))+V("ex"))^0)*"]",
- sq="'"*(1-S("'"))^0*"'",
- dq='"'*(1-S('"'))^0*'"',
-}
-local arguments=P { "ar",
- ar="("*Cs((V("sq")+V("dq")+V("nq")+P(1-P(")")))^0)*")",
- nq=((1-S("),'\""))^1)/function(s) return format("%q",s) end,
- sq=P("'")*(1-P("'"))^0*P("'"),
- dq=P('"')*(1-P('"'))^0*P('"'),
-}
-local function register_error(str)
- return { kind="error",error=format("unparsed: %s",str) }
-end
-local special_1=P("*")*Cc(register_auto_descendant)*Cc(register_all_nodes)
-local special_2=P("/")*Cc(register_auto_self)
-local special_3=P("")*Cc(register_auto_self)
-local no_nextcolon=P(-1)+#(1-P(":"))
-local no_nextlparent=P(-1)+#(1-P("("))
-local pathparser=Ct { "patterns",
- patterns=spaces*V("protocol")*spaces*(
- (V("special")*spaces*P(-1) )+(V("initial")*spaces*V("step")*spaces*(P("/")*spaces*V("step")*spaces)^0 )
- ),
- protocol=Cg(V("letters"),"protocol")*P("://")+Cg(Cc(nil),"protocol"),
- step=((V("shortcuts")+V("selector")+P("/")+V("axis"))*spaces*V("nodes")^0+V("error"))*spaces*V("expressions")^0*spaces*V("finalizer")^0,
- axis=V("last_match")+V("descendant")+V("child")+V("parent")+V("self")+V("root")+V("ancestor")+V("descendant_or_self")+V("following_sibling")+V("following")+V("reverse_sibling")+V("preceding_sibling")+V("preceding")+V("ancestor_or_self")+#(1-P(-1))*Cc(register_auto_child),
- special=special_1+special_2+special_3,
- initial=(P("/")*spaces*Cc(register_initial_child))^-1,
- error=(P(1)^1)/register_error,
- shortcuts_a=V("s_descendant_or_self")+V("s_descendant")+V("s_child")+V("s_parent")+V("s_self")+V("s_root")+V("s_ancestor")+V("s_lastmatch"),
- shortcuts=V("shortcuts_a")*(spaces*"/"*spaces*V("shortcuts_a"))^0,
- s_descendant_or_self=(P("***/")+P("/"))*Cc(register_descendant_or_self),
- s_descendant=P("**")*Cc(register_descendant),
- s_child=P("*")*no_nextcolon*Cc(register_child),
- s_parent=P("..")*Cc(register_parent),
- s_self=P("." )*Cc(register_self),
- s_root=P("^^")*Cc(register_root),
- s_ancestor=P("^")*Cc(register_ancestor),
- s_lastmatch=P("=")*Cc(register_last_match),
- descendant=P("descendant::")*Cc(register_descendant),
- child=P("child::")*Cc(register_child),
- parent=P("parent::")*Cc(register_parent),
- self=P("self::")*Cc(register_self),
- root=P('root::')*Cc(register_root),
- ancestor=P('ancestor::')*Cc(register_ancestor),
- descendant_or_self=P('descendant-or-self::')*Cc(register_descendant_or_self),
- ancestor_or_self=P('ancestor-or-self::')*Cc(register_ancestor_or_self),
- following=P('following::')*Cc(register_following),
- following_sibling=P('following-sibling::')*Cc(register_following_sibling),
- preceding=P('preceding::')*Cc(register_preceding),
- preceding_sibling=P('preceding-sibling::')*Cc(register_preceding_sibling),
- reverse_sibling=P('reverse-sibling::')*Cc(register_reverse_sibling),
- last_match=P('last-match::')*Cc(register_last_match),
- selector=P("{")*C((1-P("}"))^1)*P("}")/register_selector,
- nodes=(V("nodefunction")*spaces*P("(")*V("nodeset")*P(")")+V("nodetest")*V("nodeset"))/register_nodes,
- expressions=expression/register_expression,
- letters=R("az")^1,
- name=(1-S("/[]()|:*!"))^1,
- negate=P("!")*Cc(false),
- nodefunction=V("negate")+P("not")*Cc(false)+Cc(true),
- nodetest=V("negate")+Cc(true),
- nodename=(V("negate")+Cc(true))*spaces*((V("wildnodename")*P(":")*V("wildnodename"))+(Cc(false)*V("wildnodename"))),
- wildnodename=(C(V("name"))+P("*")*Cc(false))*no_nextlparent,
- nodeset=spaces*Ct(V("nodename")*(spaces*P("|")*spaces*V("nodename"))^0)*spaces,
- finalizer=(Cb("protocol")*P("/")^-1*C(V("name"))*arguments*P(-1))/register_finalizer,
-}
-xmlpatterns.pathparser=pathparser
-local cache={}
-local function nodesettostring(set,nodetest)
- local t={}
- for i=1,#set,3 do
- local directive,ns,tg=set[i],set[i+1],set[i+2]
- if not ns or ns=="" then ns="*" end
- if not tg or tg=="" then tg="*" end
- tg=(tg=="@rt@" and "[root]") or format("%s:%s",ns,tg)
- t[#t+1]=(directive and tg) or format("not(%s)",tg)
- end
- if nodetest==false then
- return format("not(%s)",concat(t,"|"))
- else
- return concat(t,"|")
- end
-end
-local function tagstostring(list)
- if #list==0 then
- return "no elements"
- else
- local t={}
- for i=1,#list do
- local li=list[i]
- local ns=li.ns
- local tg=li.tg
- if not ns or ns=="" then ns="*" end
- if not tg or tg=="" then tg="*" end
- t[i]=(tg=="@rt@" and "[root]") or format("%s:%s",ns,tg)
- end
- return concat(t," ")
- end
-end
-xml.nodesettostring=nodesettostring
-local lpath
-local function lshow(parsed)
- if type(parsed)=="string" then
- parsed=lpath(parsed)
- end
- report_lpath("%s://%s => %s",parsed.protocol or xml.defaultprotocol,parsed.pattern,
- table.serialize(parsed,false))
-end
-xml.lshow=lshow
-local function add_comment(p,str)
- local pc=p.comment
- if not pc then
- p.comment={ str }
- else
- pc[#pc+1]=str
- end
-end
-lpath=function (pattern)
- lpathcalls=lpathcalls+1
- if type(pattern)=="table" then
- return pattern
- else
- local parsed=cache[pattern]
- if parsed then
- lpathcached=lpathcached+1
- else
- parsed=lpegmatch(pathparser,pattern)
- if parsed then
- parsed.pattern=pattern
- local np=#parsed
- if np==0 then
- parsed={ pattern=pattern,register_self,state="parsing error" }
- report_lpath("parsing error in pattern: %s",pattern)
- lshow(parsed)
- else
- local pi=parsed[1]
- if pi.axis=="auto-child" then
- if false then
- add_comment(parsed,"auto-child replaced by auto-descendant-or-self")
- parsed[1]=register_auto_descendant_or_self
- else
- add_comment(parsed,"auto-child replaced by auto-descendant")
- parsed[1]=register_auto_descendant
- end
- elseif pi.axis=="initial-child" and np>1 and parsed[2].axis then
- add_comment(parsed,"initial-child removed")
- remove(parsed,1)
- end
- local np=#parsed
- if np>1 then
- local pnp=parsed[np]
- if pnp.kind=="nodes" and pnp.nodetest==true then
- local nodes=pnp.nodes
- if nodes[1]==true and nodes[2]==false and nodes[3]==false then
- add_comment(parsed,"redundant final wildcard filter removed")
- remove(parsed,np)
- end
- end
- end
- end
- else
- parsed={ pattern=pattern }
- end
- cache[pattern]=parsed
- if trace_lparse and not trace_lprofile then
- lshow(parsed)
- end
- end
- return parsed
- end
-end
-xml.lpath=lpath
-do
- local profiled={}
- xml.profiled=profiled
- local lastmatch=nil
- local keepmatch=nil
- if directives then
- directives.register("xml.path.keeplastmatch",function(v)
- keepmatch=v
- lastmatch=nil
- end)
- end
- apply_axis["last-match"]=function()
- return lastmatch or {}
- end
- local function profiled_apply(list,parsed,nofparsed,order)
- local p=profiled[parsed.pattern]
- if p then
- p.tested=p.tested+1
- else
- p={ tested=1,matched=0,finalized=0 }
- profiled[parsed.pattern]=p
- end
- local collected=list
- for i=1,nofparsed do
- local pi=parsed[i]
- local kind=pi.kind
- if kind=="axis" then
- collected=apply_axis[pi.axis](collected)
- elseif kind=="nodes" then
- collected=apply_nodes(collected,pi.nodetest,pi.nodes)
- elseif kind=="expression" then
- collected=apply_expression(collected,pi.evaluator,order)
- elseif kind=="selector" then
- collected=apply_selector(collected,pi.specification)
- elseif kind=="finalizer" then
- collected=pi.finalizer(collected)
- p.matched=p.matched+1
- p.finalized=p.finalized+1
- return collected
- end
- if not collected or #collected==0 then
- local pn=i<nofparsed and parsed[nofparsed]
- if pn and pn.kind=="finalizer" then
- collected=pn.finalizer(collected)
- p.finalized=p.finalized+1
- return collected
- end
- return nil
- end
- end
- if collected then
- p.matched=p.matched+1
- end
- return collected
- end
- local function traced_apply(list,parsed,nofparsed,order)
- if trace_lparse then
- lshow(parsed)
- end
- report_lpath("collecting: %s",parsed.pattern)
- report_lpath("root tags : %s",tagstostring(list))
- report_lpath("order : %s",order or "unset")
- local collected=list
- for i=1,nofparsed do
- local pi=parsed[i]
- local kind=pi.kind
- if kind=="axis" then
- collected=apply_axis[pi.axis](collected)
- report_lpath("% 10i : ax : %s",(collected and #collected) or 0,pi.axis)
- elseif kind=="nodes" then
- collected=apply_nodes(collected,pi.nodetest,pi.nodes)
- report_lpath("% 10i : ns : %s",(collected and #collected) or 0,nodesettostring(pi.nodes,pi.nodetest))
- elseif kind=="expression" then
- collected=apply_expression(collected,pi.evaluator,order)
- report_lpath("% 10i : ex : %s -> %s",(collected and #collected) or 0,pi.expression,pi.converted)
- elseif kind=="selector" then
- collected=apply_selector(collected,pi.specification)
- report_lpath("% 10i : se : %s ",(collected and #collected) or 0,pi.specification)
- elseif kind=="finalizer" then
- collected=pi.finalizer(collected)
- report_lpath("% 10i : fi : %s : %s(%s)",(type(collected)=="table" and #collected) or 0,parsed.protocol or xml.defaultprotocol,pi.name,pi.arguments or "")
- return collected
- end
- if not collected or #collected==0 then
- local pn=i<nofparsed and parsed[nofparsed]
- if pn and pn.kind=="finalizer" then
- collected=pn.finalizer(collected)
- report_lpath("% 10i : fi : %s : %s(%s)",(type(collected)=="table" and #collected) or 0,parsed.protocol or xml.defaultprotocol,pn.name,pn.arguments or "")
- return collected
- end
- return nil
- end
- end
- return collected
- end
- local function normal_apply(list,parsed,nofparsed,order)
- local collected=list
- for i=1,nofparsed do
- local pi=parsed[i]
- local kind=pi.kind
- if kind=="axis" then
- local axis=pi.axis
- if axis~="self" then
- collected=apply_axis[axis](collected)
- end
- elseif kind=="nodes" then
- collected=apply_nodes(collected,pi.nodetest,pi.nodes)
- elseif kind=="expression" then
- collected=apply_expression(collected,pi.evaluator,order)
- elseif kind=="selector" then
- collected=apply_selector(collected,pi.specification)
- elseif kind=="finalizer" then
- return pi.finalizer(collected)
- end
- if not collected or #collected==0 then
- local pf=i<nofparsed and parsed[nofparsed].finalizer
- if pf then
- return pf(collected)
- end
- return nil
- end
- end
- return collected
- end
- local apply=normal_apply
- if trackers then
- trackers.register("xml.path,xml.parse,xml.profile",function()
- if trace_lprofile then
- apply=profiled_apply
- elseif trace_lpath then
- apply=traced_apply
- else
- apply=normal_apply
- end
- end)
- end
- function xml.applylpath(list,pattern)
- if not list then
- lastmatch=nil
- return
- end
- local parsed=cache[pattern]
- if parsed then
- lpathcalls=lpathcalls+1
- lpathcached=lpathcached+1
- elseif type(pattern)=="table" then
- lpathcalls=lpathcalls+1
- parsed=pattern
- else
- parsed=lpath(pattern) or pattern
- end
- if not parsed then
- lastmatch=nil
- return
- end
- local nofparsed=#parsed
- if nofparsed==0 then
- lastmatch=nil
- return
- end
- local collected=apply({ list },parsed,nofparsed,list.mi)
- lastmatch=keepmatch and collected or nil
- return collected
- end
- function xml.lastmatch()
- return lastmatch
- end
- local stack={}
- function xml.pushmatch()
- insert(stack,lastmatch)
- end
- function xml.popmatch()
- lastmatch=remove(stack)
- end
-end
-local applylpath=xml.applylpath
-function xml.filter(root,pattern)
- return applylpath(root,pattern)
-end
-expressions.child=function(e,pattern)
- return applylpath(e,pattern)
-end
-expressions.count=function(e,pattern)
- local collected=applylpath(e,pattern)
- return pattern and (collected and #collected) or 0
-end
-expressions.attribute=function(e,name,value)
- if type(e)=="table" and name then
- local a=e.at
- if a then
- local v=a[name]
- if value then
- return v==value
- else
- return v
- end
- end
- end
- return nil
-end
-expressions.oneof=function(s,...)
- for i=1,select("#",...) do
- if s==select(i,...) then
- return true
- end
- end
- return false
-end
-expressions.error=function(str)
- xml.errorhandler(format("unknown function in lpath expression: %s",tostring(str or "?")))
- return false
-end
-expressions.undefined=function(s)
- return s==nil
-end
-expressions.quit=function(s)
- if s or s==nil then
- quit_expression=true
- end
- return true
-end
-expressions.print=function(...)
- print(...)
- return true
-end
-expressions.find=find
-expressions.upper=upper
-expressions.lower=lower
-expressions.number=tonumber
-expressions.boolean=toboolean
-function expressions.contains(str,pattern)
- local t=type(str)
- if t=="string" then
- if find(str,pattern) then
- return true
- end
- elseif t=="table" then
- for i=1,#str do
- local d=str[i]
- if type(d)=="string" and find(d,pattern) then
- return true
- end
- end
- end
- return false
-end
-function expressions.idstring(str)
- return type(str)=="string" and gsub(str,"^#","") or ""
-end
-local function traverse(root,pattern,handle)
- local collected=applylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local r=e.__p__
- handle(r,r.dt,e.ni)
- end
- end
-end
-local function selection(root,pattern,handle)
- local collected=applylpath(root,pattern)
- if collected then
- if handle then
- for c=1,#collected do
- handle(collected[c])
- end
- else
- return collected
- end
- end
-end
-xml.traverse=traverse
-xml.selection=selection
-local function dofunction(collected,fnc,...)
- if collected then
- local f=functions[fnc]
- if f then
- for c=1,#collected do
- f(collected[c],...)
- end
- else
- report_lpath("unknown function %a",fnc)
- end
- end
-end
-finalizers.xml["function"]=dofunction
-finalizers.tex["function"]=dofunction
-expressions.text=function(e,n)
- local rdt=e.__p__.dt
- return rdt and rdt[n] or ""
-end
-expressions.name=function(e,n)
- local found=false
- n=tonumber(n) or 0
- if n==0 then
- found=type(e)=="table" and e
- elseif n<0 then
- local d=e.__p__.dt
- local k=e.ni
- for i=k-1,1,-1 do
- local di=d[i]
- if type(di)=="table" then
- if n==-1 then
- found=di
- break
- else
- n=n+1
- end
- end
- end
- else
- local d=e.__p__.dt
- local k=e.ni
- for i=k+1,#d,1 do
- local di=d[i]
- if type(di)=="table" then
- if n==1 then
- found=di
- break
- else
- n=n-1
- end
- end
- end
- end
- if found then
- local ns=found.rn or found.ns or ""
- local tg=found.tg
- if ns~="" then
- return ns..":"..tg
- else
- return tg
- end
- else
- return ""
- end
-end
-expressions.tag=function(e,n)
- if not e then
- return ""
- else
- local found=false
- n=tonumber(n) or 0
- if n==0 then
- found=(type(e)=="table") and e
- elseif n<0 then
- local d=e.__p__.dt
- local k=e.ni
- for i=k-1,1,-1 do
- local di=d[i]
- if type(di)=="table" then
- if n==-1 then
- found=di
- break
- else
- n=n+1
- end
- end
- end
- else
- local d=e.__p__.dt
- local k=e.ni
- for i=k+1,#d,1 do
- local di=d[i]
- if type(di)=="table" then
- if n==1 then
- found=di
- break
- else
- n=n-1
- end
- end
- end
- end
- return (found and found.tg) or ""
- end
-end
-local dummy=function() end
-function xml.elements(root,pattern,reverse)
- local collected=applylpath(root,pattern)
- if not collected then
- return dummy
- end
- local n=#collected
- if n==0 then
- return dummy
- end
- if reverse then
- local c=n+1
- return function()
- if c>1 then
- c=c-1
- local e=collected[c]
- local r=e.__p__
- return r,r.dt,e.ni
- end
- end
- else
- local c=0
- return function()
- if c<n then
- c=c+1
- local e=collected[c]
- local r=e.__p__
- return r,r.dt,e.ni
- end
- end
- end
-end
-function xml.collected(root,pattern,reverse)
- local collected=applylpath(root,pattern)
- if not collected then
- return dummy
- end
- local n=#collected
- if n==0 then
- return dummy
- end
- if reverse then
- local c=n+1
- return function()
- if c>1 then
- c=c-1
- return collected[c]
- end
- end
- else
- local c=0
- return function()
- if c<n then
- c=c+1
- return collected[c]
- end
- end
- end
-end
-function xml.inspect(collection,pattern)
- pattern=pattern or "."
- for e in xml.collected(collection,pattern or ".") do
- report_lpath("pattern: %s\n\n%s\n",pattern,xml.tostring(e))
- end
-end
-local function split(e)
- local dt=e.dt
- if dt then
- for i=1,#dt do
- local dti=dt[i]
- if type(dti)=="string" then
- dti=gsub(dti,"^[\n\r]*(.-)[\n\r]*","%1")
- dti=gsub(dti,"[\n\r]+","\n\n")
- dt[i]=dti
- else
- split(dti)
- end
- end
- end
- return e
-end
-function xml.finalizers.paragraphs(c)
- for i=1,#c do
- split(c[i])
- end
- return c
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-mis"] = package.loaded["lxml-mis"] or true
-
--- original size: 3574, stripped down to: 1808
-
-if not modules then modules={} end modules ['lxml-mis']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local xml,lpeg,string=xml,lpeg,string
-local type=type
-local concat=table.concat
-local format,gsub,match=string.format,string.gsub,string.match
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local P,S,R,C,V,Cc,Cs=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.V,lpeg.Cc,lpeg.Cs
-lpegpatterns.xml=lpegpatterns.xml or {}
-local xmlpatterns=lpegpatterns.xml
-local function xmlgsub(t,old,new)
- local dt=t.dt
- if dt then
- for k=1,#dt do
- local v=dt[k]
- if type(v)=="string" then
- dt[k]=gsub(v,old,new)
- else
- xmlgsub(v,old,new)
- end
- end
- end
-end
-function xml.stripleadingspaces(dk,d,k)
- if d and k then
- local dkm=d[k-1]
- if dkm and type(dkm)=="string" then
- local s=match(dkm,"\n(%s+)")
- xmlgsub(dk,"\n"..rep(" ",#s),"\n")
- end
- end
-end
-local normal=(1-S("<&>"))^0
-local special=P("<")/"&lt;"+P(">")/"&gt;"+P("&")/"&amp;"
-local escaped=Cs(normal*(special*normal)^0)
-local normal=(1-S"&")^0
-local special=P("&lt;")/"<"+P("&gt;")/">"+P("&amp;")/"&"
-local unescaped=Cs(normal*(special*normal)^0)
-local cleansed=Cs(((P("<")*(1-P(">"))^0*P(">"))/""+1)^0)
-xmlpatterns.escaped=escaped
-xmlpatterns.unescaped=unescaped
-xmlpatterns.cleansed=cleansed
-function xml.escaped (str) return lpegmatch(escaped,str) end
-function xml.unescaped(str) return lpegmatch(unescaped,str) end
-function xml.cleansed (str) return lpegmatch(cleansed,str) end
-function xml.fillin(root,pattern,str,check)
- local e=xml.first(root,pattern)
- if e then
- local n=#e.dt
- if not check or n==0 or (n==1 and e.dt[1]=="") then
- e.dt={ str }
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-aux"] = package.loaded["lxml-aux"] or true
-
--- original size: 33708, stripped down to: 20953
-
-if not modules then modules={} end modules ['lxml-aux']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local trace_manipulations=false trackers.register("lxml.manipulations",function(v) trace_manipulations=v end)
-local trace_inclusions=false trackers.register("lxml.inclusions",function(v) trace_inclusions=v end)
-local report_xml=logs.reporter("xml")
-local xml=xml
-local xmlcopy,xmlname=xml.copy,xml.name
-local xmlinheritedconvert=xml.inheritedconvert
-local xmlapplylpath=xml.applylpath
-local type,next,setmetatable,getmetatable=type,next,setmetatable,getmetatable
-local insert,remove,fastcopy,concat=table.insert,table.remove,table.fastcopy,table.concat
-local gmatch,gsub,format,find,strip,match=string.gmatch,string.gsub,string.format,string.find,string.strip,string.match
-local utfbyte=utf.byte
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local striplinepatterns=utilities.strings.striplinepatterns
-local function report(what,pattern,c,e)
- report_xml("%s element %a, root %a, position %a, index %a, pattern %a",what,xmlname(e),xmlname(e.__p__),c,e.ni,pattern)
-end
-local function withelements(e,handle,depth)
- if e and handle then
- local edt=e.dt
- if edt then
- depth=depth or 0
- for i=1,#edt do
- local e=edt[i]
- if type(e)=="table" then
- handle(e,depth)
- withelements(e,handle,depth+1)
- end
- end
- end
- end
-end
-xml.withelements=withelements
-function xml.withelement(e,n,handle)
- if e and n~=0 and handle then
- local edt=e.dt
- if edt then
- if n>0 then
- for i=1,#edt do
- local ei=edt[i]
- if type(ei)=="table" then
- if n==1 then
- handle(ei)
- return
- else
- n=n-1
- end
- end
- end
- elseif n<0 then
- for i=#edt,1,-1 do
- local ei=edt[i]
- if type(ei)=="table" then
- if n==-1 then
- handle(ei)
- return
- else
- n=n+1
- end
- end
- end
- end
- end
- end
-end
-function xml.each(root,pattern,handle,reverse)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- if handle then
- if reverse then
- for c=#collected,1,-1 do
- handle(collected[c])
- end
- else
- for c=1,#collected do
- handle(collected[c])
- end
- end
- end
- return collected
- end
-end
-function xml.processattributes(root,pattern,handle)
- local collected=xmlapplylpath(root,pattern)
- if collected and handle then
- for c=1,#collected do
- handle(collected[c].at)
- end
- end
- return collected
-end
-function xml.collect(root,pattern)
- return xmlapplylpath(root,pattern)
-end
-function xml.collecttexts(root,pattern,flatten)
- local collected=xmlapplylpath(root,pattern)
- if collected and flatten then
- local xmltostring=xml.tostring
- for c=1,#collected do
- collected[c]=xmltostring(collected[c].dt)
- end
- end
- return collected or {}
-end
-function xml.collect_tags(root,pattern,nonamespace)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- local t={}
- local n=0
- for c=1,#collected do
- local e=collected[c]
- local ns=e.ns
- local tg=e.tg
- n=n+1
- if nonamespace then
- t[n]=tg
- elseif ns=="" then
- t[n]=tg
- else
- t[n]=ns..":"..tg
- end
- end
- return t
- end
-end
-local no_root={ no_root=true }
-local function redo_ni(d)
- for k=1,#d do
- local dk=d[k]
- if type(dk)=="table" then
- dk.ni=k
- end
- end
-end
-xml.reindex=redo_ni
-local function xmltoelement(whatever,root)
- if not whatever then
- return nil
- end
- local element
- if type(whatever)=="string" then
- element=xmlinheritedconvert(whatever,root,true)
- else
- element=whatever
- end
- if element.error then
- return whatever
- end
- if element then
- end
- return element
-end
-xml.toelement=xmltoelement
-local function copiedelement(element,newparent)
- if type(element)~="string" then
- element=xmlcopy(element).dt
- if newparent and type(element)=="table" then
- for i=1,#element do
- local e=element[i]
- if type(e)=="table" then
- e.__p__=newparent
- end
- end
- end
- end
- return element
-end
-function xml.delete(root,pattern)
- if not pattern or pattern=="" then
- local p=root.__p__
- if p then
- if trace_manipulations then
- report('deleting',"--",c,root)
- end
- local d=p.dt
- remove(d,root.ni)
- redo_ni(d)
- end
- else
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local p=e.__p__
- if p then
- if trace_manipulations then
- report('deleting',pattern,c,e)
- end
- local d=p.dt
- local ni=e.ni
- if ni<=#d then
- if false then
- p.dt[ni]=""
- else
- remove(d,ni)
- redo_ni(d)
- end
- else
- end
- end
- end
- end
- end
-end
-function xml.wipe(root,pattern)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local p=e.__p__
- if p then
- local d=p.dt
- local ni=e.ni
- if ni<=#d then
- local dt=e.dt
- if #dt==1 then
- local d1=dt[1]
- if type(d1)=="string" and match(d1,"^%s*$") then
- if trace_manipulations then
- report('wiping',pattern,c,e)
- end
- remove(d,ni)
- redo_ni(d)
- end
- end
- end
- end
- end
- end
-end
-function xml.replace(root,pattern,whatever)
- local element=root and xmltoelement(whatever,root)
- local collected=element and xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local p=e.__p__
- if p then
- if trace_manipulations then
- report('replacing',pattern,c,e)
- end
- local d=p.dt
- local n=e.ni
- local t=copiedelement(element,p)
- if type(t)=="table" then
- d[n]=t[1]
- for i=2,#t do
- n=n+1
- insert(d,n,t[i])
- end
- else
- d[n]=t
- end
- redo_ni(d)
- end
- end
- end
-end
-local function wrap(e,wrapper)
- local t={
- rn=e.rn,
- tg=e.tg,
- ns=e.ns,
- at=e.at,
- dt=e.dt,
- __p__=e,
- }
- setmetatable(t,getmetatable(e))
- e.rn=wrapper.rn or e.rn or ""
- e.tg=wrapper.tg or e.tg or ""
- e.ns=wrapper.ns or e.ns or ""
- e.at=fastcopy(wrapper.at)
- e.dt={ t }
-end
-function xml.wrap(root,pattern,whatever)
- if whatever then
- local wrapper=xmltoelement(whatever,root)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- if trace_manipulations then
- report('wrapping',pattern,c,e)
- end
- wrap(e,wrapper)
- end
- end
- else
- wrap(root,xmltoelement(pattern))
- end
-end
-local function inject_element(root,pattern,whatever,prepend)
- local element=root and xmltoelement(whatever,root)
- local collected=element and xmlapplylpath(root,pattern)
- local function inject_e(e)
- local r=e.__p__
- local d=r.dt
- local k=e.ni
- local rri=r.ri
- local edt=(rri and d[rri].dt) or (d and d[k] and d[k].dt)
- if edt then
- local be,af
- local cp=copiedelement(element,e)
- if prepend then
- be,af=cp,edt
- else
- be,af=edt,cp
- end
- local bn=#be
- for i=1,#af do
- bn=bn+1
- be[bn]=af[i]
- end
- if rri then
- r.dt[rri].dt=be
- else
- d[k].dt=be
- end
- redo_ni(d)
- end
- end
- if not collected then
- elseif collected.tg then
- inject_e(collected)
- else
- for c=1,#collected do
- inject_e(collected[c])
- end
- end
-end
-local function insert_element(root,pattern,whatever,before)
- local element=root and xmltoelement(whatever,root)
- local collected=element and xmlapplylpath(root,pattern)
- local function insert_e(e)
- local r=e.__p__
- local d=r.dt
- local k=e.ni
- if not before then
- k=k+1
- end
- insert(d,k,copiedelement(element,r))
- redo_ni(d)
- end
- if not collected then
- elseif collected.tg then
- insert_e(collected)
- else
- for c=1,#collected do
- insert_e(collected[c])
- end
- end
-end
-xml.insert_element=insert_element
-xml.insertafter=insert_element
-xml.insertbefore=function(r,p,e) insert_element(r,p,e,true) end
-xml.injectafter=inject_element
-xml.injectbefore=function(r,p,e) inject_element(r,p,e,true) end
-local function include(xmldata,pattern,attribute,recursive,loaddata,level)
- pattern=pattern or 'include'
- loaddata=loaddata or io.loaddata
- local collected=xmlapplylpath(xmldata,pattern)
- if collected then
- if not level then
- level=1
- end
- for c=1,#collected do
- local ek=collected[c]
- local name=nil
- local ekdt=ek.dt
- if ekdt then
- local ekat=ek.at
- local ekrt=ek.__p__
- if ekrt then
- local epdt=ekrt.dt
- if not attribute or attribute=="" then
- name=(type(ekdt)=="table" and ekdt[1]) or ekdt
- end
- if not name then
- for a in gmatch(attribute or "href","([^|]+)") do
- name=ekat[a]
- if name then
- break
- end
- end
- end
- local data=nil
- if name and name~="" then
- local d,n=loaddata(name)
- data=d or ""
- name=n or name
- if trace_inclusions then
- report_xml("including %s bytes from %a at level %s by pattern %a and attribute %a (%srecursing)",#data,name,level,pattern,attribute or "",recursive and "" or "not ")
- end
- end
- if not data or data=="" then
- epdt[ek.ni]=""
- elseif ekat["parse"]=="text" then
- epdt[ek.ni]=xml.escaped(data)
- else
- local settings=xmldata.settings
- local savedresource=settings.currentresource
- settings.currentresource=name
- local xi=xmlinheritedconvert(data,xmldata,true)
- if not xi then
- epdt[ek.ni]=""
- else
- if recursive then
- include(xi,pattern,attribute,recursive,loaddata,level+1)
- end
- local child=xml.body(xi)
- child.__p__=ekrt
- child.__f__=name
- child.cf=name
- epdt[ek.ni]=child
- local settings=xmldata.settings
- local inclusions=settings and settings.inclusions
- if inclusions then
- inclusions[#inclusions+1]=name
- elseif settings then
- settings.inclusions={ name }
- else
- settings={ inclusions={ name } }
- xmldata.settings=settings
- end
- if child.er then
- local badinclusions=settings.badinclusions
- if badinclusions then
- badinclusions[#badinclusions+1]=name
- else
- settings.badinclusions={ name }
- end
- end
- end
-settings.currentresource=savedresource
- end
- end
- end
- end
- end
-end
-xml.include=include
-function xml.inclusion(e,default)
- while e do
- local f=e.__f__
- if f then
- return f
- else
- e=e.__p__
- end
- end
- return default
-end
-local function getinclusions(key,e,sorted)
- while e do
- local settings=e.settings
- if settings then
- local inclusions=settings[key]
- if inclusions then
- inclusions=table.unique(inclusions)
- if sorted then
- table.sort(inclusions)
- end
- return inclusions
- else
- e=e.__p__
- end
- else
- e=e.__p__
- end
- end
-end
-function xml.inclusions(e,sorted)
- return getinclusions("inclusions",e,sorted)
-end
-function xml.badinclusions(e,sorted)
- return getinclusions("badinclusions",e,sorted)
-end
-local b_collapser=lpegpatterns.b_collapser
-local m_collapser=lpegpatterns.m_collapser
-local e_collapser=lpegpatterns.e_collapser
-local x_collapser=lpegpatterns.x_collapser
-local b_stripper=lpegpatterns.b_stripper
-local m_stripper=lpegpatterns.m_stripper
-local e_stripper=lpegpatterns.e_stripper
-local x_stripper=lpegpatterns.x_stripper
-local function stripelement(e,nolines,anywhere,everything)
- local edt=e.dt
- if edt then
- local n=#edt
- if n==0 then
- return e
- elseif everything then
- local t={}
- local m=0
- for i=1,n do
- local str=edt[i]
- if type(str)~="string" then
- m=m+1
- t[m]=str
- elseif str~="" then
- str=lpegmatch(x_collapser,str)
- if str~="" then
- m=m+1
- t[m]=str
- end
- end
- end
- e.dt=t
- elseif anywhere then
- local t={}
- local m=0
- for i=1,n do
- local str=edt[i]
- if type(str)~="string" then
- m=m+1
- t[m]=str
- elseif str~="" then
- if nolines then
- str=lpegmatch((i==1 and b_collapser) or (i==m and e_collapser) or m_collapser,str)
- else
- str=lpegmatch((i==1 and b_stripper) or (i==m and e_stripper) or m_stripper,str)
- end
- if str~="" then
- m=m+1
- t[m]=str
- end
- end
- end
- e.dt=t
- else
- local str=edt[1]
- if type(str)=="string" then
- if str~="" then
- str=lpegmatch(nolines and b_collapser or b_stripper,str)
- end
- if str=="" then
- remove(edt,1)
- n=n-1
- else
- edt[1]=str
- end
- end
- if n>0 then
- str=edt[n]
- if type(str)=="string" then
- if str=="" then
- remove(edt)
- else
- str=lpegmatch(nolines and e_collapser or e_stripper,str)
- if str=="" then
- remove(edt)
- else
- edt[n]=str
- end
- end
- end
- end
- end
- end
- return e
-end
-xml.stripelement=stripelement
-function xml.strip(root,pattern,nolines,anywhere,everything)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for i=1,#collected do
- stripelement(collected[i],nolines,anywhere,everything)
- end
- end
-end
-local function compactelement(e)
- local edt=e.dt
- if edt then
- for e=1,#edt do
- local str=edt[e]
- if type(str)=="string" and not find(str,"%S") then
- edt[e]=""
- end
- end
- end
- return e
-end
-xml.compactelement=compactelement
-local function renamespace(root,oldspace,newspace)
- local ndt=#root.dt
- for i=1,ndt or 0 do
- local e=root[i]
- if type(e)=="table" then
- if e.ns==oldspace then
- e.ns=newspace
- if e.rn then
- e.rn=newspace
- end
- end
- local edt=e.dt
- if edt then
- renamespace(edt,oldspace,newspace)
- end
- end
- end
-end
-xml.renamespace=renamespace
-function xml.remaptag(root,pattern,newtg)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- collected[c].tg=newtg
- end
- end
-end
-function xml.remapnamespace(root,pattern,newns)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- collected[c].ns=newns
- end
- end
-end
-function xml.checknamespace(root,pattern,newns)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- if (not e.rn or e.rn=="") and e.ns=="" then
- e.rn=newns
- end
- end
- end
-end
-function xml.remapname(root,pattern,newtg,newns,newrn)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- e.tg,e.ns,e.rn=newtg,newns,newrn
- end
- end
-end
-function xml.cdatatotext(e)
- local dt=e.dt
- if #dt==1 then
- local first=dt[1]
- if first.tg=="@cd@" then
- e.dt=first.dt
- end
- else
- end
-end
-function xml.texttocdata(e)
- local dt=e.dt
- local s=xml.tostring(dt)
- e.tg="@cd@"
- e.special=true
- e.ns=""
- e.rn=""
- e.dt={ s }
- e.at=nil
-end
-function xml.elementtocdata(e)
- local dt=e.dt
- local s=xml.tostring(e)
- e.tg="@cd@"
- e.special=true
- e.ns=""
- e.rn=""
- e.dt={ s }
- e.at=nil
-end
-xml.builtinentities=table.tohash { "amp","quot","apos","lt","gt" }
-local entities=characters and characters.entities or nil
-local builtinentities=xml.builtinentities
-function xml.addentitiesdoctype(root,option)
- if not entities then
- require("char-ent")
- entities=characters.entities
- end
- if entities and root and root.tg=="@rt@" and root.statistics then
- local list={}
- local hexify=option=="hexadecimal"
- for k,v in table.sortedhash(root.statistics.entities.names) do
- if not builtinentities[k] then
- local e=entities[k]
- if not e then
- e=format("[%s]",k)
- elseif hexify then
- e=format("&#%05X;",utfbyte(k))
- end
- list[#list+1]=format(" <!ENTITY %s %q >",k,e)
- end
- end
- local dt=root.dt
- local n=dt[1].tg=="@pi@" and 2 or 1
- if #list>0 then
- insert(dt,n,{ "\n" })
- insert(dt,n,{
- tg="@dt@",
- dt={ format("Something [\n%s\n] ",concat(list)) },
- ns="",
- special=true,
- })
- insert(dt,n,{ "\n\n" })
- else
- end
- end
-end
-xml.all=xml.each
-xml.insert=xml.insertafter
-xml.inject=xml.injectafter
-xml.after=xml.insertafter
-xml.before=xml.insertbefore
-xml.process=xml.each
-xml.obsolete=xml.obsolete or {}
-local obsolete=xml.obsolete
-xml.strip_whitespace=xml.strip obsolete.strip_whitespace=xml.strip
-xml.collect_elements=xml.collect obsolete.collect_elements=xml.collect
-xml.delete_element=xml.delete obsolete.delete_element=xml.delete
-xml.replace_element=xml.replace obsolete.replace_element=xml.replace
-xml.each_element=xml.each obsolete.each_element=xml.each
-xml.process_elements=xml.process obsolete.process_elements=xml.process
-xml.insert_element_after=xml.insertafter obsolete.insert_element_after=xml.insertafter
-xml.insert_element_before=xml.insertbefore obsolete.insert_element_before=xml.insertbefore
-xml.inject_element_after=xml.injectafter obsolete.inject_element_after=xml.injectafter
-xml.inject_element_before=xml.injectbefore obsolete.inject_element_before=xml.injectbefore
-xml.process_attributes=xml.processattributes obsolete.process_attributes=xml.processattributes
-xml.collect_texts=xml.collecttexts obsolete.collect_texts=xml.collecttexts
-xml.inject_element=xml.inject obsolete.inject_element=xml.inject
-xml.remap_tag=xml.remaptag obsolete.remap_tag=xml.remaptag
-xml.remap_name=xml.remapname obsolete.remap_name=xml.remapname
-xml.remap_namespace=xml.remapnamespace obsolete.remap_namespace=xml.remapnamespace
-function xml.cdata(e)
- if e then
- local dt=e.dt
- if dt and #dt==1 then
- local first=dt[1]
- return first.tg=="@cd@" and first.dt[1] or ""
- end
- end
- return ""
-end
-function xml.finalizers.xml.cdata(collected)
- if collected then
- local e=collected[1]
- if e then
- local dt=e.dt
- if dt and #dt==1 then
- local first=dt[1]
- return first.tg=="@cd@" and first.dt[1] or ""
- end
- end
- end
- return ""
-end
-function xml.insertcomment(e,str,n)
- insert(e.dt,n or 1,{
- tg="@cm@",
- ns="",
- special=true,
- at={},
- dt={ str },
- })
-end
-function xml.insertcdata(e,str,n)
- insert(e.dt,n or 1,{
- tg="@cd@",
- ns="",
- special=true,
- at={},
- dt={ str },
- })
-end
-function xml.setcomment(e,str,n)
- e.dt={ {
- tg="@cm@",
- ns="",
- special=true,
- at={},
- dt={ str },
- } }
-end
-function xml.setcdata(e,str)
- e.dt={ {
- tg="@cd@",
- ns="",
- special=true,
- at={},
- dt={ str },
- } }
-end
-function xml.separate(x,pattern)
- local collected=xmlapplylpath(x,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local d=e.dt
- if d==x then
- report_xml("warning: xml.separate changes root")
- x=d
- end
- local t={ "\n" }
- local n=1
- local i=1
- local nd=#d
- while i<=nd do
- while i<=nd do
- local di=d[i]
- if type(di)=="string" then
- if di=="\n" or find(di,"^%s+$") then
- i=i+1
- else
- d[i]=strip(di)
- break
- end
- else
- break
- end
- end
- if i>nd then
- break
- end
- t[n+1]="\n"
- t[n+2]=d[i]
- t[n+3]="\n"
- n=n+3
- i=i+1
- end
- t[n+1]="\n"
- setmetatable(t,getmetatable(d))
- e.dt=t
- end
- end
- return x
-end
-local helpers=xml.helpers or {}
-xml.helpers=helpers
-local function normal(e,action)
- local edt=e.dt
- if edt then
- for i=1,#edt do
- local str=edt[i]
- if type(str)=="string" and str~="" then
- edt[i]=action(str)
- end
- end
- end
-end
-local function recurse(e,action)
- local edt=e.dt
- if edt then
- for i=1,#edt do
- local str=edt[i]
- if type(str)~="string" then
- recurse(str,action)
- elseif str~="" then
- edt[i]=action(str)
- end
- end
- end
-end
-function helpers.recursetext(collected,action,recursive)
- if recursive then
- for i=1,#collected do
- recurse(collected[i],action)
- end
- else
- for i=1,#collected do
- normal(collected[i],action)
- end
- end
-end
-local specials={
- ["@rt@"]="root",
- ["@pi@"]="instruction",
- ["@cm@"]="comment",
- ["@dt@"]="declaration",
- ["@cd@"]="cdata",
-}
-local function convert(x,strip,flat)
- local ns=x.ns
- local tg=x.tg
- local at=x.at
- local dt=x.dt
- local node=flat and {
- [0]=(not x.special and (ns~="" and ns..":"..tg or tg)) or nil,
- } or {
- _namespace=ns~="" and ns or nil,
- _tag=not x.special and tg or nil,
- _type=specials[tg] or "_element",
- }
- if at then
- for k,v in next,at do
- node[k]=v
- end
- end
- local n=0
- for i=1,#dt do
- local di=dt[i]
- if type(di)=="table" then
- if flat and di.special then
- else
- di=convert(di,strip,flat)
- if di then
- n=n+1
- node[n]=di
- end
- end
- elseif strip then
- di=lpegmatch(strip,di)
- if di~="" then
- n=n+1
- node[n]=di
- end
- else
- n=n+1
- node[n]=di
- end
- end
- if next(node) then
- return node
- end
-end
-function xml.totable(x,strip,flat)
- if type(x)=="table" then
- if strip then
- strip=striplinepatterns[strip]
- end
- return convert(x,strip,flat)
- end
-end
-function xml.rename(e,namespace,name,attributes)
- if type(e)~="table" or not e.tg then
- return
- end
- if type(name)=="table" then
- attributes=name
- name=namespace
- namespace=""
- elseif type(name)~="string" then
- attributes={}
- name=namespace
- namespace=""
- end
- if type(attributes)~="table" then
- attributes={}
- end
- e.ns=namespace
- e.rn=namespace
- e.tg=name
- e.at=attributes
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-xml"] = package.loaded["lxml-xml"] or true
-
--- original size: 11096, stripped down to: 7702
-
-if not modules then modules={} end modules ['lxml-xml']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local tonumber,next=tonumber,next
-local concat=table.concat
-local find,lower,upper=string.find,string.lower,string.upper
-local xml=xml
-local finalizers=xml.finalizers.xml
-local xmlfilter=xml.filter
-local xmltostring=xml.tostring
-local xmlserialize=xml.serialize
-local xmlcollected=xml.collected
-local xmlnewhandlers=xml.newhandlers
-local reparsedentity=xml.reparsedentitylpeg
-local unescapedentity=xml.unescapedentitylpeg
-local parsedentity=reparsedentity
-local function first(collected)
- return collected and collected[1]
-end
-local function last(collected)
- return collected and collected[#collected]
-end
-local function all(collected)
- return collected
-end
-local reverse=table.reversed
-local function attribute(collected,name)
- if collected and #collected>0 then
- local at=collected[1].at
- return at and at[name]
- end
-end
-local function att(id,name)
- local at=id.at
- return at and at[name]
-end
-local function count(collected)
- return collected and #collected or 0
-end
-local function position(collected,n)
- if not collected then
- return 0
- end
- local nc=#collected
- if nc==0 then
- return 0
- end
- n=tonumber(n) or 0
- if n<0 then
- return collected[nc+n+1]
- elseif n>0 then
- return collected[n]
- else
- return collected[1].mi or 0
- end
-end
-local function match(collected)
- return collected and #collected>0 and collected[1].mi or 0
-end
-local function index(collected)
- return collected and #collected>0 and collected[1].ni or 0
-end
-local function attributes(collected,arguments)
- if collected and #collected>0 then
- local at=collected[1].at
- if arguments then
- return at[arguments]
- elseif next(at) then
- return at
- end
- end
-end
-local function chainattribute(collected,arguments)
- if collected and #collected>0 then
- local e=collected[1]
- while e do
- local at=e.at
- if at then
- local a=at[arguments]
- if a then
- return a
- end
- else
- break
- end
- e=e.__p__
- end
- end
- return ""
-end
-local function raw(collected)
- if collected and #collected>0 then
- local e=collected[1] or collected
- return e and xmltostring(e) or ""
- else
- return ""
- end
-end
-local xmltexthandler=xmlnewhandlers {
- name="string",
- initialize=function()
- result={}
- return result
- end,
- finalize=function()
- return concat(result)
- end,
- handle=function(...)
- result[#result+1]=concat {... }
- end,
- escape=false,
-}
-local function xmltotext(root)
- local dt=root.dt
- if not dt then
- return ""
- end
- local nt=#dt
- if nt==0 then
- return ""
- elseif nt==1 and type(dt[1])=="string" then
- return dt[1]
- else
- return xmlserialize(root,xmltexthandler) or ""
- end
-end
-function xml.serializetotext(root)
- return root and xmlserialize(root,xmltexthandler) or ""
-end
-local function text(collected)
- if collected then
- local e=collected[1] or collected
- return e and xmltotext(e) or ""
- else
- return ""
- end
-end
-local function texts(collected)
- if not collected then
- return {}
- end
- local nc=#collected
- if nc==0 then
- return {}
- end
- local t,n={},0
- for c=1,nc do
- local e=collected[c]
- if e and e.dt then
- n=n+1
- t[n]=e.dt
- end
- end
- return t
-end
-local function tag(collected,n)
- if not collected then
- return
- end
- local nc=#collected
- if nc==0 then
- return
- end
- local c
- if n==0 or not n then
- c=collected[1]
- elseif n>1 then
- c=collected[n]
- else
- c=collected[nc-n+1]
- end
- return c and c.tg
-end
-local function name(collected,n)
- if not collected then
- return
- end
- local nc=#collected
- if nc==0 then
- return
- end
- local c
- if n==0 or not n then
- c=collected[1]
- elseif n>1 then
- c=collected[n]
- else
- c=collected[nc-n+1]
- end
- if not c then
- elseif c.ns=="" then
- return c.tg
- else
- return c.ns..":"..c.tg
- end
-end
-local function tags(collected,nonamespace)
- if not collected then
- return
- end
- local nc=#collected
- if nc==0 then
- return
- end
- local t,n={},0
- for c=1,nc do
- local e=collected[c]
- local ns,tg=e.ns,e.tg
- n=n+1
- if nonamespace or ns=="" then
- t[n]=tg
- else
- t[n]=ns..":"..tg
- end
- end
- return t
-end
-local function empty(collected,spacesonly)
- if not collected then
- return true
- end
- local nc=#collected
- if nc==0 then
- return true
- end
- for c=1,nc do
- local e=collected[c]
- if e then
- local edt=e.dt
- if edt then
- local n=#edt
- if n==1 then
- local edk=edt[1]
- local typ=type(edk)
- if typ=="table" then
- return false
- elseif edk~="" then
- return false
- elseif spacesonly and not find(edk,"%S") then
- return false
- end
- elseif n>1 then
- return false
- end
- end
- end
- end
- return true
-end
-finalizers.first=first
-finalizers.last=last
-finalizers.all=all
-finalizers.reverse=reverse
-finalizers.elements=all
-finalizers.default=all
-finalizers.attribute=attribute
-finalizers.att=att
-finalizers.count=count
-finalizers.position=position
-finalizers.match=match
-finalizers.index=index
-finalizers.attributes=attributes
-finalizers.chainattribute=chainattribute
-finalizers.text=text
-finalizers.texts=texts
-finalizers.tag=tag
-finalizers.name=name
-finalizers.tags=tags
-finalizers.empty=empty
-function xml.first(id,pattern)
- return first(xmlfilter(id,pattern))
-end
-function xml.last(id,pattern)
- return last(xmlfilter(id,pattern))
-end
-function xml.count(id,pattern)
- return count(xmlfilter(id,pattern))
-end
-function xml.attribute(id,pattern,a,default)
- return attribute(xmlfilter(id,pattern),a,default)
-end
-function xml.raw(id,pattern)
- if pattern then
- return raw(xmlfilter(id,pattern))
- else
- return raw(id)
- end
-end
-function xml.text(id,pattern)
- if pattern then
- local collected=xmlfilter(id,pattern)
- return collected and #collected>0 and xmltotext(collected[1]) or ""
- elseif id then
- return xmltotext(id) or ""
- else
- return ""
- end
-end
-function xml.pure(id,pattern)
- if pattern then
- local collected=xmlfilter(id,pattern)
- if collected and #collected>0 then
- parsedentity=unescapedentity
- local s=collected and #collected>0 and xmltotext(collected[1]) or ""
- parsedentity=reparsedentity
- return s
- else
- return ""
- end
- else
- parsedentity=unescapedentity
- local s=xmltotext(id) or ""
- parsedentity=reparsedentity
- return s
- end
-end
-xml.content=text
-function xml.position(id,pattern,n)
- return position(xmlfilter(id,pattern),n)
-end
-function xml.match(id,pattern)
- return match(xmlfilter(id,pattern))
-end
-function xml.empty(id,pattern,spacesonly)
- return empty(xmlfilter(id,pattern),spacesonly)
-end
-xml.all=xml.filter
-xml.index=xml.position
-xml.found=xml.filter
-local function totable(x)
- local t={}
- for e in xmlcollected(x[1] or x,"/*") do
- t[e.tg]=xmltostring(e.dt) or ""
- end
- return next(t) and t or nil
-end
-xml.table=totable
-finalizers.table=totable
-local function textonly(e,t)
- if e then
- local edt=e.dt
- if edt then
- for i=1,#edt do
- local e=edt[i]
- if type(e)=="table" then
- textonly(e,t)
- else
- t[#t+1]=e
- end
- end
- end
- end
- return t
-end
-function xml.textonly(e)
- return concat(textonly(e,{}))
-end
-function finalizers.lowerall(collected)
- for c=1,#collected do
- local e=collected[c]
- if not e.special then
- e.tg=lower(e.tg)
- local eat=e.at
- if eat then
- local t={}
- for k,v in next,eat do
- t[lower(k)]=v
- end
- e.at=t
- end
- end
- end
-end
-function finalizers.upperall(collected)
- for c=1,#collected do
- local e=collected[c]
- if not e.special then
- e.tg=upper(e.tg)
- local eat=e.at
- if eat then
- local t={}
- for k,v in next,eat do
- t[upper(k)]=v
- end
- e.at=t
- end
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-xml"] = package.loaded["trac-xml"] or true
-
--- original size: 6407, stripped down to: 4640
-
-if not modules then modules={} end modules ['trac-xml']={
- version=1.001,
- comment="companion to trac-log.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local formatters=string.formatters
-local reporters=logs.reporters
-local xmlserialize=xml.serialize
-local xmlcollected=xml.collected
-local xmltext=xml.text
-local xmlfirst=xml.first
-local function showhelp(specification,...)
- local root=xml.convert(specification.helpinfo or "")
- if not root then
- return
- end
- local xs=xml.gethandlers("string")
- xml.sethandlersfunction(xs,"short",function(e,handler) xmlserialize(e.dt,handler) end)
- xml.sethandlersfunction(xs,"ref",function(e,handler) handler.handle("--"..e.at.name) end)
- local wantedcategories=select("#",...)==0 and true or table.tohash {... }
- local nofcategories=xml.count(root,"/application/flags/category")
- local report=specification.report
- for category in xmlcollected(root,"/application/flags/category") do
- local categoryname=category.at.name or ""
- if wantedcategories==true or wantedcategories[categoryname] then
- if nofcategories>1 then
- report("%s options:",categoryname)
- report()
- end
- for subcategory in xmlcollected(category,"/subcategory") do
- for flag in xmlcollected(subcategory,"/flag") do
- local name=flag.at.name
- local value=flag.at.value
- local short=xmltext(xmlfirst(flag,"/short"))
- if value then
- report("--%-20s %s",formatters["%s=%s"](name,value),short)
- else
- report("--%-20s %s",name,short)
- end
- end
- report()
- end
- end
- end
- for category in xmlcollected(root,"/application/examples/category") do
- local title=xmltext(xmlfirst(category,"/title"))
- if title and title~="" then
- report()
- report(title)
- report()
- end
- for subcategory in xmlcollected(category,"/subcategory") do
- for example in xmlcollected(subcategory,"/example") do
- local command=xmltext(xmlfirst(example,"/command"))
- local comment=xmltext(xmlfirst(example,"/comment"))
- report(command)
- end
- report()
- end
- end
- for comment in xmlcollected(root,"/application/comments/comment") do
- local comment=xmltext(comment)
- report()
- report(comment)
- report()
- end
-end
-local reporthelp=reporters.help
-local exporthelp=reporters.export
-local function xmlfound(t)
- local helpinfo=t.helpinfo
- if type(helpinfo)=="table" then
- return false
- end
- if type(helpinfo)~="string" then
- helpinfo="Warning: no helpinfo found."
- t.helpinfo=helpinfo
- return false
- end
- if string.find(helpinfo,".xml$") then
- local ownscript=environment.ownscript
- local helpdata=false
- if ownscript then
- local helpfile=file.join(file.pathpart(ownscript),helpinfo)
- helpdata=io.loaddata(helpfile)
- if helpdata=="" then
- helpdata=false
- end
- end
- if not helpdata then
- local helpfile=resolvers.findfile(helpinfo,"tex")
- helpdata=helpfile and io.loaddata(helpfile)
- end
- if helpdata and helpdata~="" then
- helpinfo=helpdata
- else
- helpinfo=formatters["Warning: help file %a is not found."](helpinfo)
- end
- end
- t.helpinfo=helpinfo
- return string.find(t.helpinfo,"^<%?xml") and true or false
-end
-function reporters.help(t,...)
- if xmlfound(t) then
- showhelp(t,...)
- else
- reporthelp(t,...)
- end
-end
-function reporters.export(t,methods,filename)
- if not xmlfound(t) then
- return exporthelp(t)
- end
- if not methods or methods=="" then
- methods=environment.arguments["exporthelp"]
- end
- if not filename or filename=="" then
- filename=environment.files[1]
- end
- dofile(resolvers.findfile("trac-exp.lua","tex"))
- local exporters=logs.exporters
- if not exporters or not methods then
- return exporthelp(t)
- end
- if methods=="all" then
- methods=table.keys(exporters)
- elseif type(methods)=="string" then
- methods=utilities.parsers.settings_to_array(methods)
- else
- return exporthelp(t)
- end
- if type(filename)~="string" or filename=="" then
- filename=false
- elseif file.pathpart(filename)=="" then
- t.report("export file %a will not be saved on the current path (safeguard)",filename)
- return
- end
- for i=1,#methods do
- local method=methods[i]
- local exporter=exporters[method]
- if exporter then
- local result=exporter(t,method)
- if result and result~="" then
- if filename then
- local fullname=file.replacesuffix(filename,method)
- t.report("saving export in %a",fullname)
- dir.mkdirs(file.pathpart(fullname))
- io.savedata(fullname,result)
- else
- reporters.lines(t,result)
- end
- else
- t.report("no output from exporter %a",method)
- end
- else
- t.report("unknown exporter %a",method)
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-ini"] = package.loaded["data-ini"] or true
-
--- original size: 10947, stripped down to: 7176
-
-if not modules then modules={} end modules ['data-ini']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local next,type,getmetatable,rawset=next,type,getmetatable,rawset
-local gsub,find,gmatch,char=string.gsub,string.find,string.gmatch,string.char
-local filedirname,filebasename,filejoin=file.dirname,file.basename,file.join
-local ostype,osname,osuname,ossetenv,osgetenv=os.type,os.name,os.uname,os.setenv,os.getenv
-local sortedpairs=table.sortedpairs
-local P,S,R,C,Cs,Cc,lpegmatch=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.match
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local trace_expansions=false trackers.register("resolvers.expansions",function(v) trace_expansions=v end)
-local report_initialization=logs.reporter("resolvers","initialization")
-resolvers=resolvers or {}
-local resolvers=resolvers
-texconfig.kpse_init=false
-texconfig.shell_escape='t'
-if not (environment and environment.default_texmfcnf) and kpse and kpse.default_texmfcnf then
- local default_texmfcnf=kpse.default_texmfcnf()
- default_texmfcnf=gsub(default_texmfcnf,"$SELFAUTOLOC","selfautoloc:")
- default_texmfcnf=gsub(default_texmfcnf,"$SELFAUTODIR","selfautodir:")
- default_texmfcnf=gsub(default_texmfcnf,"$SELFAUTOPARENT","selfautoparent:")
- default_texmfcnf=gsub(default_texmfcnf,"$HOME","home:")
- environment.default_texmfcnf=default_texmfcnf
-end
-kpse={ original=kpse }
-setmetatable(kpse,{
- __index=function(kp,name)
- report_initialization("fatal error: kpse library is accessed (key: %s)",name)
- os.exit()
- end
-} )
-do
- local osfontdir=osgetenv("OSFONTDIR")
- if osfontdir and osfontdir~="" then
- elseif osname=="windows" then
- ossetenv("OSFONTDIR","c:/windows/fonts//")
- elseif osname=="macosx" then
- ossetenv("OSFONTDIR","$HOME/Library/Fonts//;/Library/Fonts//;/System/Library/Fonts//")
- end
-end
-if not environment.homedir then
- local oldhome=osgetenv('HOME')
- local homedir=osgetenv(ostype=="windows" and 'USERPROFILE' or 'HOME') or ''
- if not homedir or homedir=="" then
- homedir=char(127)
- end
- homedir=file.collapsepath(homedir)
- ossetenv("HOME",homedir)
- ossetenv("USERPROFILE",homedir)
- environment.oldhome=oldhome
- environment.homedir=homedir
-end
-do
- local args=environment.originalarguments or arg
- if not environment.ownmain then
- environment.ownmain=status and string.match(string.lower(status.banner),"this is ([%a]+)") or "luatex"
- end
- local ownbin=environment.ownbin or args[-2] or arg[-2] or args[-1] or arg[-1] or arg[0] or "luatex"
- local ownpath=environment.ownpath or os.selfdir
- ownbin=file.collapsepath(ownbin)
- ownpath=file.collapsepath(ownpath)
- if not ownpath or ownpath=="" or ownpath=="unset" then
- ownpath=args[-1] or arg[-1]
- ownpath=ownpath and filedirname(gsub(ownpath,"\\","/"))
- if not ownpath or ownpath=="" then
- ownpath=args[-0] or arg[-0]
- ownpath=ownpath and filedirname(gsub(ownpath,"\\","/"))
- end
- local binary=ownbin
- if not ownpath or ownpath=="" then
- ownpath=ownpath and filedirname(binary)
- end
- if not ownpath or ownpath=="" then
- if os.binsuffix~="" then
- binary=file.replacesuffix(binary,os.binsuffix)
- end
- local path=osgetenv("PATH")
- if path then
- for p in gmatch(path,"[^"..io.pathseparator.."]+") do
- local b=filejoin(p,binary)
- if lfs.isfile(b) then
- local olddir=lfs.currentdir()
- if lfs.chdir(p) then
- local pp=lfs.currentdir()
- if trace_locating and p~=pp then
- report_initialization("following symlink %a to %a",p,pp)
- end
- ownpath=pp
- lfs.chdir(olddir)
- else
- if trace_locating then
- report_initialization("unable to check path %a",p)
- end
- ownpath=p
- end
- break
- end
- end
- end
- end
- if not ownpath or ownpath=="" then
- ownpath="."
- report_initialization("forcing fallback to ownpath %a",ownpath)
- elseif trace_locating then
- report_initialization("using ownpath %a",ownpath)
- end
- end
- environment.ownbin=ownbin
- environment.ownpath=ownpath
-end
-resolvers.ownpath=environment.ownpath
-function resolvers.getownpath()
- return environment.ownpath
-end
-do
- local ownpath=environment.ownpath or dir.current()
- if ownpath then
- ossetenv('SELFAUTOLOC',file.collapsepath(ownpath))
- ossetenv('SELFAUTODIR',file.collapsepath(ownpath.."/.."))
- ossetenv('SELFAUTOPARENT',file.collapsepath(ownpath.."/../.."))
- else
- report_initialization("error: unable to locate ownpath")
- os.exit()
- end
-end
-local texos=environment.texos or osgetenv("TEXOS")
-local texmfos=environment.texmfos or osgetenv('SELFAUTODIR')
-if not texos or texos=="" then
- texos=file.basename(texmfos)
-end
-ossetenv('TEXMFOS',texmfos)
-ossetenv('TEXOS',texos)
-ossetenv('SELFAUTOSYSTEM',os.platform)
-environment.texos=texos
-environment.texmfos=texmfos
-local texroot=environment.texroot or osgetenv("TEXROOT")
-if not texroot or texroot=="" then
- texroot=osgetenv('SELFAUTOPARENT')
- ossetenv('TEXROOT',texroot)
-end
-environment.texroot=file.collapsepath(texroot)
-local prefixes=utilities.storage.allocate()
-resolvers.prefixes=prefixes
-local resolved={}
-local abstract={}
-local dynamic={}
-function resolvers.resetresolve(str)
- resolved,abstract={},{}
-end
-function resolvers.allprefixes(separator)
- local all=table.sortedkeys(prefixes)
- if separator then
- for i=1,#all do
- all[i]=all[i]..":"
- end
- end
- return all
-end
-local function _resolve_(method,target)
- local action=prefixes[method]
- if action then
- return action(target)
- else
- return method..":"..target
- end
-end
-function resolvers.unresolve(str)
- return abstract[str] or str
-end
-function resolvers.setdynamic(str)
- dynamic[str]=true
-end
-local pattern=Cs((C(R("az")^2)*P(":")*C((1-S(" \"\';,"))^1)/_resolve_+P(1))^0)
-local prefix=C(R("az")^2)*P(":")
-local target=C((1-S(" \"\';,"))^1)
-local notarget=(#S(";,")+P(-1))*Cc("")
-local p_resolve=Cs(((prefix*(target+notarget))/_resolve_+P(1))^0)
-local p_simple=prefix*P(-1)
-local function resolve(str)
- if type(str)=="table" then
- local res={}
- for i=1,#str do
- res[i]=resolve(str[i])
- end
- return res
- end
- local res=resolved[str]
- if res then
- return res
- end
- local simple=lpegmatch(p_simple,str)
- local action=prefixes[simple]
- if action then
- local res=action(res)
- if not dynamic[simple] then
- resolved[simple]=res
- abstract[res]=simple
- end
- return res
- end
- res=lpegmatch(p_resolve,str)
- resolved[str]=res
- abstract[res]=str
- return res
-end
-resolvers.resolve=resolve
-if type(osuname)=="function" then
- for k,v in next,osuname() do
- if not prefixes[k] then
- prefixes[k]=function() return v end
- end
- end
-end
-if ostype=="unix" then
- local pattern
- local function makepattern(t,k,v)
- if t then
- rawset(t,k,v)
- end
- local colon=P(":")
- for k,v in sortedpairs(prefixes) do
- if p then
- p=P(k)+p
- else
- p=P(k)
- end
- end
- pattern=Cs((p*colon+colon/";"+P(1))^0)
- end
- makepattern()
- table.setmetatablenewindex(prefixes,makepattern)
- function resolvers.repath(str)
- return lpegmatch(pattern,str)
- end
-else
- function resolvers.repath(str)
- return str
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-exp"] = package.loaded["data-exp"] or true
-
--- original size: 18179, stripped down to: 10432
-
-if not modules then modules={} end modules ['data-exp']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local format,find,gmatch,lower,char,sub=string.format,string.find,string.gmatch,string.lower,string.char,string.sub
-local concat,sort=table.concat,table.sort
-local sortedkeys=table.sortedkeys
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local Ct,Cs,Cc,Carg,P,C,S=lpeg.Ct,lpeg.Cs,lpeg.Cc,lpeg.Carg,lpeg.P,lpeg.C,lpeg.S
-local type,next=type,next
-local isdir=lfs.isdir
-local collapsepath,joinpath,basename=file.collapsepath,file.join,file.basename
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local trace_expansions=false trackers.register("resolvers.expansions",function(v) trace_expansions=v end)
-local trace_globbing=true trackers.register("resolvers.globbing",function(v) trace_globbing=v end)
-local report_expansions=logs.reporter("resolvers","expansions")
-local report_globbing=logs.reporter("resolvers","globbing")
-local resolvers=resolvers
-local resolveprefix=resolvers.resolve
-local function f_both(a,b)
- local t,n={},0
- for sb in gmatch(b,"[^,]+") do
- for sa in gmatch(a,"[^,]+") do
- n=n+1;t[n]=sa..sb
- end
- end
- return concat(t,",")
-end
-local comma=P(",")
-local nocomma=(1-comma)^1
-local docomma=comma^1/","
-local before=Cs((nocomma*Carg(1)+docomma)^0)
-local after=Cs((Carg(1)*nocomma+docomma)^0)
-local both=Cs(((C(nocomma)*Carg(1))/function(a,b) return lpegmatch(before,b,1,a) end+docomma)^0)
-local function f_first (a,b) return lpegmatch(after,b,1,a) end
-local function f_second(a,b) return lpegmatch(before,a,1,b) end
-local function f_both (a,b) return lpegmatch(both,b,1,a) end
-local left=P("{")
-local right=P("}")
-local var=P((1-S("{}" ))^0)
-local set=P((1-S("{},"))^0)
-local other=P(1)
-local l_first=Cs((Cc("{")*(C(set)*left*C(var)*right/f_first)*Cc("}")+other )^0 )
-local l_second=Cs((Cc("{")*(left*C(var)*right*C(set)/f_second)*Cc("}")+other )^0 )
-local l_both=Cs((Cc("{")*(left*C(var)*right*left*C(var)*right/f_both)*Cc("}")+other )^0 )
-local l_rest=Cs((left*var*(left/"")*var*(right/"")*var*right+other )^0 )
-local stripper_1=lpeg.stripper ("{}@")
-local replacer_1=lpeg.replacer { { ",}",",@}" },{ "{,","{@," },}
-local function splitpathexpr(str,newlist,validate)
- if trace_expansions then
- report_expansions("expanding variable %a",str)
- end
- local t,ok,done=newlist or {},false,false
- local n=#t
- str=lpegmatch(replacer_1,str)
- repeat
- local old=str
- repeat
- local old=str
- str=lpegmatch(l_first,str)
- until old==str
- repeat
- local old=str
- str=lpegmatch(l_second,str)
- until old==str
- repeat
- local old=str
- str=lpegmatch(l_both,str)
- until old==str
- repeat
- local old=str
- str=lpegmatch(l_rest,str)
- until old==str
- until old==str
- str=lpegmatch(stripper_1,str)
- if validate then
- for s in gmatch(str,"[^,]+") do
- s=validate(s)
- if s then
- n=n+1
- t[n]=s
- end
- end
- else
- for s in gmatch(str,"[^,]+") do
- n=n+1
- t[n]=s
- end
- end
- if trace_expansions then
- for k=1,#t do
- report_expansions("% 4i: %s",k,t[k])
- end
- end
- return t
-end
-local function validate(s)
- s=collapsepath(s)
- return s~="" and not find(s,"^!*unset/*$") and s
-end
-resolvers.validatedpath=validate
-function resolvers.expandedpathfromlist(pathlist)
- local newlist={}
- for k=1,#pathlist do
- splitpathexpr(pathlist[k],newlist,validate)
- end
- return newlist
-end
-local usedhomedir=nil
-local donegation=(P("!")/"" )^0
-local doslashes=(P("\\")/"/"+1)^0
-local function expandedhome()
- if not usedhomedir then
- usedhomedir=lpegmatch(Cs(donegation*doslashes),environment.homedir or "")
- if usedhomedir=="~" or usedhomedir=="" or not isdir(usedhomedir) then
- if trace_expansions then
- report_expansions("no home dir set, ignoring dependent path using current path")
- end
- usedhomedir="."
- end
- end
- return usedhomedir
-end
-local dohome=((P("~")+P("$HOME")+P("%HOME%"))/expandedhome)^0
-local cleanup=Cs(donegation*dohome*doslashes)
-resolvers.cleanpath=function(str)
- return str and lpegmatch(cleanup,str) or ""
-end
-local expandhome=P("~")/"$HOME"
-local dodouble=P('"')/""*(expandhome+(1-P('"')))^0*P('"')/""
-local dosingle=P("'")/""*(expandhome+(1-P("'")))^0*P("'")/""
-local dostring=(expandhome+1 )^0
-local stripper=Cs(
- lpegpatterns.unspacer*(dosingle+dodouble+dostring)*lpegpatterns.unspacer
-)
-function resolvers.checkedvariable(str)
- return type(str)=="string" and lpegmatch(stripper,str) or str
-end
-local cache={}
-local splitter=lpeg.tsplitat(";")
-local backslashswapper=lpeg.replacer("\\","/")
-local function splitconfigurationpath(str)
- if str then
- local found=cache[str]
- if not found then
- if str=="" then
- found={}
- else
- local split=lpegmatch(splitter,lpegmatch(backslashswapper,str))
- found={}
- local noffound=0
- for i=1,#split do
- local s=split[i]
- if not find(s,"^{*unset}*") then
- noffound=noffound+1
- found[noffound]=s
- end
- end
- if trace_expansions then
- report_expansions("splitting path specification %a",str)
- for k=1,noffound do
- report_expansions("% 4i: %s",k,found[k])
- end
- end
- cache[str]=found
- end
- end
- return found
- end
-end
-resolvers.splitconfigurationpath=splitconfigurationpath
-function resolvers.splitpath(str)
- if type(str)=='table' then
- return str
- else
- return splitconfigurationpath(str)
- end
-end
-function resolvers.joinpath(str)
- if type(str)=='table' then
- return joinpath(str)
- else
- return str
- end
-end
-local attributes,directory=lfs.attributes,lfs.dir
-local weird=P(".")^1+lpeg.anywhere(S("~`!#$%^&*()={}[]:;\"\'||<>,?\n\r\t"))
-local lessweird=P(".")^1+lpeg.anywhere(S("~`#$%^&*:;\"\'||<>,?\n\r\t"))
-local timer={}
-local scanned={}
-local nofscans=0
-local scancache={}
-local fullcache={}
-local nofsharedscans=0
-local addcasecraptoo=true
-local function scan(files,remap,spec,path,n,m,r,onlyone,tolerant)
- local full=path=="" and spec or (spec..path..'/')
- local dirlist={}
- local nofdirs=0
- local pattern=tolerant and lessweird or weird
- local filelist={}
- local noffiles=0
- for name,mode in directory(full) do
- if not lpegmatch(pattern,name) then
- if not mode then
- mode=attributes(full..name,"mode")
- end
- if mode=="file" then
- n=n+1
- noffiles=noffiles+1
- filelist[noffiles]=name
- elseif mode=="directory" then
- m=m+1
- nofdirs=nofdirs+1
- if path~="" then
- dirlist[nofdirs]=path.."/"..name
- else
- dirlist[nofdirs]=name
- end
- end
- end
- end
- if noffiles>0 then
- sort(filelist)
- for i=1,noffiles do
- local name=filelist[i]
- local lower=lower(name)
- local paths=files[lower]
- if paths then
- if onlyone then
- else
- if name~=lower then
- local rl=remap[lower]
- if not rl then
- remap[lower]=name
- r=r+1
- elseif trace_globbing and rl~=name then
- report_globbing("confusing filename, name: %a, lower: %a, already: %a",name,lower,rl)
- end
- if addcasecraptoo then
- local paths=files[name]
- if not paths then
- files[name]=path
- elseif type(paths)=="string" then
- files[name]={ paths,path }
- else
- paths[#paths+1]=path
- end
- end
- end
- if type(paths)=="string" then
- files[lower]={ paths,path }
- else
- paths[#paths+1]=path
- end
- end
- else
- files[lower]=path
- if name~=lower then
- local rl=remap[lower]
- if not rl then
- remap[lower]=name
- r=r+1
- elseif trace_globbing and rl~=name then
- report_globbing("confusing filename, name: %a, lower: %a, already: %a",name,lower,rl)
- end
- end
- end
- end
- end
- if nofdirs>0 then
- sort(dirlist)
- for i=1,nofdirs do
- files,remap,n,m,r=scan(files,remap,spec,dirlist[i],n,m,r,onlyonce,tolerant)
- end
- end
- scancache[sub(full,1,-2)]=files
- return files,remap,n,m,r
-end
-local function scanfiles(path,branch,usecache,onlyonce,tolerant)
- local realpath=resolveprefix(path)
- if usecache then
- local content=fullcache[realpath]
- if content then
- if trace_locating then
- report_expansions("using cached scan of path %a, branch %a",path,branch or path)
- end
- nofsharedscans=nofsharedscans+1
- return content
- end
- end
- statistics.starttiming(timer)
- if trace_locating then
- report_expansions("scanning path %a, branch %a",path,branch or path)
- end
- local content
- if isdir(realpath) then
- local files,remap,n,m,r=scan({},{},realpath..'/',"",0,0,0,onlyonce,tolerant)
- content={
- metadata={
- path=path,
- files=n,
- directories=m,
- remappings=r,
- },
- files=files,
- remap=remap,
- }
- if trace_locating then
- report_expansions("%s files found on %s directories with %s uppercase remappings",n,m,r)
- end
- else
- content={
- metadata={
- path=path,
- files=0,
- directories=0,
- remappings=0,
- },
- files={},
- remap={},
- }
- if trace_locating then
- report_expansions("invalid path %a",realpath)
- end
- end
- if usecache then
- scanned[#scanned+1]=realpath
- fullcache[realpath]=content
- end
- nofscans=nofscans+1
- statistics.stoptiming(timer)
- return content
-end
-resolvers.scanfiles=scanfiles
-function resolvers.simplescanfiles(path,branch,usecache)
- return scanfiles(path,branch,usecache,true,true)
-end
-function resolvers.scandata()
- table.sort(scanned)
- return {
- n=nofscans,
- shared=nofsharedscans,
- time=statistics.elapsedtime(timer),
- paths=scanned,
- }
-end
-function resolvers.get_from_content(content,path,name)
- if not content then
- return
- end
- local files=content.files
- if not files then
- return
- end
- local remap=content.remap
- if not remap then
- return
- end
- if name then
- local used=lower(name)
- return path,remap[used] or used
- else
- local name=path
- local used=lower(name)
- local path=files[used]
- if path then
- return path,remap[used] or used
- end
- end
-end
-local nothing=function() end
-function resolvers.filtered_from_content(content,pattern)
- if content and type(pattern)=="string" then
- local pattern=lower(pattern)
- local files=content.files
- local remap=content.remap
- if files and remap then
- local f=sortedkeys(files)
- local n=#f
- local i=0
- local function iterator()
- while i<n do
- i=i+1
- local k=f[i]
- if find(k,pattern) then
- return files[k],remap and remap[k] or k
- end
- end
- end
- return iterator
- end
- end
- return nothing
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-env"] = package.loaded["data-env"] or true
-
--- original size: 9501, stripped down to: 6411
-
-if not modules then modules={} end modules ['data-env']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local lower,gsub=string.lower,string.gsub
-local next,rawget=next,rawget
-local resolvers=resolvers
-local allocate=utilities.storage.allocate
-local setmetatableindex=table.setmetatableindex
-local suffixonly=file.suffixonly
-local formats=allocate()
-local suffixes=allocate()
-local dangerous=allocate()
-local suffixmap=allocate()
-local usertypes=allocate()
-resolvers.formats=formats
-resolvers.suffixes=suffixes
-resolvers.dangerous=dangerous
-resolvers.suffixmap=suffixmap
-resolvers.usertypes=usertypes
-local luasuffixes=utilities.lua.suffixes
-local relations=allocate {
- core={
- ofm={
- names={ "ofm","omega font metric","omega font metrics" },
- variable='OFMFONTS',
- suffixes={ 'ofm','tfm' },
- },
- ovf={
- names={ "ovf","omega virtual font","omega virtual fonts" },
- variable='OVFFONTS',
- suffixes={ 'ovf','vf' },
- },
- tfm={
- names={ "tfm","tex font metric","tex font metrics" },
- variable='TFMFONTS',
- suffixes={ 'tfm' },
- },
- vf={
- names={ "vf","virtual font","virtual fonts" },
- variable='VFFONTS',
- suffixes={ 'vf' },
- },
- otf={
- names={ "otf","opentype","opentype font","opentype fonts"},
- variable='OPENTYPEFONTS',
- suffixes={ 'otf' },
- },
- ttf={
- names={ "ttf","truetype","truetype font","truetype fonts","truetype collection","truetype collections","truetype dictionary","truetype dictionaries" },
- variable='TTFONTS',
- suffixes={ 'ttf','ttc','dfont' },
- },
- afm={
- names={ "afm","adobe font metric","adobe font metrics" },
- variable="AFMFONTS",
- suffixes={ "afm" },
- },
- pfb={
- names={ "pfb","type1","type 1","type1 font","type 1 font","type1 fonts","type 1 fonts" },
- variable='T1FONTS',
- suffixes={ 'pfb','pfa' },
- },
- fea={
- names={ "fea","font feature","font features","font feature file","font feature files" },
- variable='FONTFEATURES',
- suffixes={ 'fea' },
- },
- cid={
- names={ "cid","cid map","cid maps","cid file","cid files" },
- variable='FONTCIDMAPS',
- suffixes={ 'cid','cidmap' },
- },
- fmt={
- names={ "fmt","format","tex format" },
- variable='TEXFORMATS',
- suffixes={ 'fmt' },
- },
- mem={
- names={ 'mem',"metapost format" },
- variable='MPMEMS',
- suffixes={ 'mem' },
- },
- mp={
- names={ "mp" },
- variable='MPINPUTS',
- suffixes=CONTEXTLMTXMODE>0
- and { 'mp','mpxl','mpvi','mpiv','mpii' }
- or { 'mp','mpvi','mpiv','mpii' },
- usertype=true,
- },
- tex={
- names={ "tex" },
- variable='TEXINPUTS',
- suffixes={ "tex","mkiv","mkvi","mkxl","mklx","mkii","cld","lfg","xml" },
- usertype=true,
- },
- icc={
- names={ "icc","icc profile","icc profiles" },
- variable='ICCPROFILES',
- suffixes={ 'icc' },
- },
- texmfscripts={
- names={ "texmfscript","texmfscripts","script","scripts" },
- variable='TEXMFSCRIPTS',
- suffixes={ 'lua','rb','pl','py' },
- },
- lua={
- names={ "lua" },
- variable='LUAINPUTS',
- suffixes={ luasuffixes.lua,luasuffixes.luc,luasuffixes.tma,luasuffixes.tmc },
- usertype=true,
- },
- lib={
- names={ "lib" },
- variable='CLUAINPUTS',
- suffixes=os.libsuffix and { os.libsuffix } or { 'dll','so' },
- },
- bib={
- names={ 'bib' },
- variable='BIBINPUTS',
- suffixes={ 'bib' },
- usertype=true,
- },
- bst={
- names={ 'bst' },
- variable='BSTINPUTS',
- suffixes={ 'bst' },
- usertype=true,
- },
- fontconfig={
- names={ 'fontconfig','fontconfig file','fontconfig files' },
- variable='FONTCONFIG_PATH',
- },
- pk={
- names={ "pk" },
- variable='PKFONTS',
- suffixes={ 'pk' },
- },
- },
- obsolete={
- enc={
- names={ "enc","enc files","enc file","encoding files","encoding file" },
- variable='ENCFONTS',
- suffixes={ 'enc' },
- },
- map={
- names={ "map","map files","map file" },
- variable='TEXFONTMAPS',
- suffixes={ 'map' },
- },
- lig={
- names={ "lig files","lig file","ligature file","ligature files" },
- variable='LIGFONTS',
- suffixes={ 'lig' },
- },
- opl={
- names={ "opl" },
- variable='OPLFONTS',
- suffixes={ 'opl' },
- },
- ovp={
- names={ "ovp" },
- variable='OVPFONTS',
- suffixes={ 'ovp' },
- },
- },
- kpse={
- base={
- names={ 'base',"metafont format" },
- variable='MFBASES',
- suffixes={ 'base','bas' },
- },
- cmap={
- names={ 'cmap','cmap files','cmap file' },
- variable='CMAPFONTS',
- suffixes={ 'cmap' },
- },
- cnf={
- names={ 'cnf' },
- suffixes={ 'cnf' },
- },
- web={
- names={ 'web' },
- suffixes={ 'web','ch' }
- },
- cweb={
- names={ 'cweb' },
- suffixes={ 'w','web','ch' },
- },
- gf={
- names={ 'gf' },
- suffixes={ '<resolution>gf' },
- },
- mf={
- names={ 'mf' },
- variable='MFINPUTS',
- suffixes={ 'mf' },
- },
- mft={
- names={ 'mft' },
- suffixes={ 'mft' },
- },
- pk={
- names={ 'pk' },
- suffixes={ '<resolution>pk' },
- },
- },
-}
-resolvers.relations=relations
-function resolvers.updaterelations()
- for category,categories in next,relations do
- for name,relation in next,categories do
- local rn=relation.names
- local rv=relation.variable
- if rn and rv then
- local rs=relation.suffixes
- local ru=relation.usertype
- for i=1,#rn do
- local rni=lower(gsub(rn[i]," ",""))
- formats[rni]=rv
- if rs then
- suffixes[rni]=rs
- for i=1,#rs do
- local rsi=rs[i]
- suffixmap[rsi]=rni
- end
- end
- end
- if ru then
- usertypes[name]=true
- end
- end
- end
- end
-end
-resolvers.updaterelations()
-local function simplified(t,k)
- return k and rawget(t,lower(gsub(k," ",""))) or nil
-end
-setmetatableindex(formats,simplified)
-setmetatableindex(suffixes,simplified)
-setmetatableindex(suffixmap,simplified)
-function resolvers.suffixofformat(str)
- local s=suffixes[str]
- return s and s[1] or ""
-end
-function resolvers.suffixofformat(str)
- return suffixes[str] or {}
-end
-for name,format in next,formats do
- dangerous[name]=true
-end
-dangerous.tex=nil
-function resolvers.formatofvariable(str)
- return formats[str] or ''
-end
-function resolvers.formatofsuffix(str)
- return suffixmap[suffixonly(str)] or 'tex'
-end
-function resolvers.variableofformat(str)
- return formats[str] or ''
-end
-function resolvers.variableofformatorsuffix(str)
- local v=formats[str]
- if v then
- return v
- end
- v=suffixmap[suffixonly(str)]
- if v then
- return formats[v]
- end
- return ''
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-tmp"] = package.loaded["data-tmp"] or true
-
--- original size: 16409, stripped down to: 11591
-
-if not modules then modules={} end modules ['data-tmp']={
- version=1.100,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local next,type=next,type
-local pcall,loadfile,collectgarbage=pcall,loadfile,collectgarbage
-local format,lower,gsub=string.format,string.lower,string.gsub
-local concat,serialize,fastserialize,serializetofile=table.concat,table.serialize,table.fastserialize,table.tofile
-local mkdirs,expanddirname,isdir,isfile=dir.mkdirs,dir.expandname,lfs.isdir,lfs.isfile
-local is_writable,is_readable=file.is_writable,file.is_readable
-local collapsepath,joinfile,addsuffix,dirname=file.collapsepath,file.join,file.addsuffix,file.dirname
-local savedata=file.savedata
-local formatters=string.formatters
-local osexit,osdate,osuuid=os.exit,os.date,os.uuid
-local removefile=os.remove
-local md5hex=md5.hex
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local trace_cache=false trackers.register("resolvers.cache",function(v) trace_cache=v end)
-local report_caches=logs.reporter("resolvers","caches")
-local report_resolvers=logs.reporter("resolvers","caching")
-local resolvers=resolvers
-local cleanpath=resolvers.cleanpath
-local resolvepath=resolvers.resolve
-local luautilities=utilities.lua
-do
- local directive_cleanup=false directives.register("system.compile.cleanup",function(v) directive_cleanup=v end)
- local directive_strip=false directives.register("system.compile.strip",function(v) directive_strip=v end)
- local compilelua=luautilities.compile
- function luautilities.compile(luafile,lucfile,cleanup,strip)
- if cleanup==nil then cleanup=directive_cleanup end
- if strip==nil then strip=directive_strip end
- return compilelua(luafile,lucfile,cleanup,strip)
- end
-end
-caches=caches or {}
-local caches=caches
-local writable=nil
-local readables={}
-local usedreadables={}
-local compilelua=luautilities.compile
-local luasuffixes=luautilities.suffixes
-caches.base=caches.base or "luatex-cache"
-caches.more=caches.more or "context"
-caches.defaults={ "TMPDIR","TEMPDIR","TMP","TEMP","HOME","HOMEPATH" }
-local direct_cache=false
-local fast_cache=false
-local cache_tree=false
-directives.register("system.caches.direct",function(v) direct_cache=true end)
-directives.register("system.caches.fast",function(v) fast_cache=true end)
-local function configfiles()
- return concat(resolvers.configurationfiles(),";")
-end
-local function hashed(tree)
- tree=gsub(tree,"[\\/]+$","")
- tree=lower(tree)
- local hash=md5hex(tree)
- if trace_cache or trace_locating then
- report_caches("hashing tree %a, hash %a",tree,hash)
- end
- return hash
-end
-local function treehash()
- local tree=configfiles()
- if not tree or tree=="" then
- return false
- else
- return hashed(tree)
- end
-end
-caches.hashed=hashed
-caches.treehash=treehash
-caches.configfiles=configfiles
-local function identify()
- local texmfcaches=resolvers.cleanpathlist("TEXMFCACHE")
- if texmfcaches then
- for k=1,#texmfcaches do
- local cachepath=texmfcaches[k]
- if cachepath~="" then
- cachepath=resolvepath(cachepath)
- cachepath=cleanpath(cachepath)
- cachepath=collapsepath(cachepath)
- local valid=isdir(cachepath)
- if valid then
- if is_readable(cachepath) then
- readables[#readables+1]=cachepath
- if not writable and is_writable(cachepath) then
- writable=cachepath
- end
- end
- elseif not writable then
- local cacheparent=dirname(cachepath)
- if is_writable(cacheparent) then
- mkdirs(cachepath)
- if isdir(cachepath) and is_writable(cachepath) then
- report_caches("path %a created",cachepath)
- writable=cachepath
- readables[#readables+1]=cachepath
- end
- end
- end
- end
- end
- end
- local texmfcaches=caches.defaults
- if texmfcaches then
- for k=1,#texmfcaches do
- local cachepath=texmfcaches[k]
- cachepath=resolvers.expansion(cachepath)
- if cachepath~="" then
- cachepath=resolvepath(cachepath)
- cachepath=cleanpath(cachepath)
- local valid=isdir(cachepath)
- if valid and is_readable(cachepath) then
- if not writable and is_writable(cachepath) then
- readables[#readables+1]=cachepath
- writable=cachepath
- break
- end
- end
- end
- end
- end
- if not writable then
- report_caches("fatal error: there is no valid writable cache path defined")
- osexit()
- elseif #readables==0 then
- report_caches("fatal error: there is no valid readable cache path defined")
- osexit()
- end
- writable=expanddirname(cleanpath(writable))
- local base=caches.base
- local more=caches.more
- local tree=cache_tree or treehash()
- if tree then
- cache_tree=tree
- writable=mkdirs(writable,base,more,tree)
- for i=1,#readables do
- readables[i]=joinfile(readables[i],base,more,tree)
- end
- else
- writable=mkdirs(writable,base,more)
- for i=1,#readables do
- readables[i]=joinfile(readables[i],base,more)
- end
- end
- if trace_cache then
- for i=1,#readables do
- report_caches("using readable path %a (order %s)",readables[i],i)
- end
- report_caches("using writable path %a",writable)
- end
- identify=function()
- return writable,readables
- end
- return writable,readables
-end
-function caches.usedpaths(separator)
- local writable,readables=identify()
- if #readables>1 then
- local result={}
- local done={}
- for i=1,#readables do
- local readable=readables[i]
- if readable==writable then
- done[readable]=true
- result[#result+1]=formatters["readable+writable: %a"](readable)
- elseif usedreadables[i] then
- done[readable]=true
- result[#result+1]=formatters["readable: %a"](readable)
- end
- end
- if not done[writable] then
- result[#result+1]=formatters["writable: %a"](writable)
- end
- return concat(result,separator or " | ")
- else
- return writable or "?"
- end
-end
-local r_cache={}
-local w_cache={}
-local function getreadablepaths(...)
- local tags={... }
- local hash=concat(tags,"/")
- local done=r_cache[hash]
- if not done then
- local writable,readables=identify()
- if #tags>0 then
- done={}
- for i=1,#readables do
- done[i]=joinfile(readables[i],...)
- end
- else
- done=readables
- end
- r_cache[hash]=done
- end
- return done
-end
-local function getwritablepath(...)
- local tags={... }
- local hash=concat(tags,"/")
- local done=w_cache[hash]
- if not done then
- local writable,readables=identify()
- if #tags>0 then
- done=mkdirs(writable,...)
- else
- done=writable
- end
- w_cache[hash]=done
- end
- return done
-end
-local function setfirstwritablefile(filename,...)
- local wr=getwritablepath(...)
- local fullname=joinfile(wr,filename)
- return fullname,wr
-end
-local function setluanames(path,name)
- return
- format("%s/%s.%s",path,name,luasuffixes.tma),
- format("%s/%s.%s",path,name,luasuffixes.tmc)
-end
-local function getfirstreadablefile(filename,...)
- local fullname,path=setfirstwritablefile(filename,...)
- if is_readable(fullname) then
- return fullname,path
- end
- local rd=getreadablepaths(...)
- for i=1,#rd do
- local path=rd[i]
- local fullname=joinfile(path,filename)
- if is_readable(fullname) then
- usedreadables[i]=true
- return fullname,path
- end
- end
- return fullname,path
-end
-caches.getreadablepaths=getreadablepaths
-caches.getwritablepath=getwritablepath
-caches.setfirstwritablefile=setfirstwritablefile
-caches.getfirstreadablefile=getfirstreadablefile
-caches.setluanames=setluanames
-local checkmemory=utilities and utilities.lua and utilities.lua.checkmemory
-local threshold=100
-function caches.loaddata(readables,name,writable)
- local used=checkmemory and checkmemory()
- if type(readables)=="string" then
- readables={ readables }
- end
- for i=1,#readables do
- local path=readables[i]
- local loader=false
- local state=false
- local tmaname,tmcname=setluanames(path,name)
- if isfile(tmcname) then
- state,loader=pcall(loadfile,tmcname)
- end
- if not loader and isfile(tmaname) then
- local tmacrap,tmcname=setluanames(writable,name)
- if isfile(tmcname) then
- state,loader=pcall(loadfile,tmcname)
- end
- compilelua(tmaname,tmcname)
- if isfile(tmcname) then
- state,loader=pcall(loadfile,tmcname)
- end
- if not loader then
- state,loader=pcall(loadfile,tmaname)
- end
- end
- if loader then
- loader=loader()
- if checkmemory then
- checkmemory(used,threshold)
- else
- collectgarbage("step")
- end
- return loader
- end
- end
- return false
-end
-function caches.is_writable(filepath,filename)
- local tmaname,tmcname=setluanames(filepath,filename)
- return is_writable(tmaname)
-end
-local saveoptions={ compact=true,accurate=not JITSUPPORTED }
-function caches.savedata(filepath,filename,data,fast)
- local tmaname,tmcname=setluanames(filepath,filename)
- data.cache_uuid=osuuid()
- if fast or fast_cache then
- savedata(tmaname,fastserialize(data,true))
- elseif direct_cache then
- savedata(tmaname,serialize(data,true,saveoptions))
- else
- serializetofile(tmaname,data,true,saveoptions)
- end
- compilelua(tmaname,tmcname)
-end
-local content_state={}
-function caches.contentstate()
- return content_state or {}
-end
-function caches.loadcontent(cachename,dataname,filename)
- if not filename then
- local name=hashed(cachename)
- local full,path=getfirstreadablefile(addsuffix(name,luasuffixes.lua),"trees")
- filename=joinfile(path,name)
- end
- local state,blob=pcall(loadfile,addsuffix(filename,luasuffixes.luc))
- if not blob then
- state,blob=pcall(loadfile,addsuffix(filename,luasuffixes.lua))
- end
- if blob then
- local data=blob()
- if data and data.content then
- if data.type==dataname then
- if data.version==resolvers.cacheversion then
- content_state[#content_state+1]=data.uuid
- if trace_locating then
- report_resolvers("loading %a for %a from %a",dataname,cachename,filename)
- end
- return data.content
- else
- report_resolvers("skipping %a for %a from %a (version mismatch)",dataname,cachename,filename)
- end
- else
- report_resolvers("skipping %a for %a from %a (datatype mismatch)",dataname,cachename,filename)
- end
- elseif trace_locating then
- report_resolvers("skipping %a for %a from %a (no content)",dataname,cachename,filename)
- end
- elseif trace_locating then
- report_resolvers("skipping %a for %a from %a (invalid file)",dataname,cachename,filename)
- end
-end
-function caches.collapsecontent(content)
- for k,v in next,content do
- if type(v)=="table" and #v==1 then
- content[k]=v[1]
- end
- end
-end
-function caches.savecontent(cachename,dataname,content,filename)
- if not filename then
- local name=hashed(cachename)
- local full,path=setfirstwritablefile(addsuffix(name,luasuffixes.lua),"trees")
- filename=joinfile(path,name)
- end
- local luaname=addsuffix(filename,luasuffixes.lua)
- local lucname=addsuffix(filename,luasuffixes.luc)
- if trace_locating then
- report_resolvers("preparing %a for %a",dataname,cachename)
- end
- local data={
- type=dataname,
- root=cachename,
- version=resolvers.cacheversion,
- date=osdate("%Y-%m-%d"),
- time=osdate("%H:%M:%S"),
- content=content,
- uuid=osuuid(),
- }
- local ok=savedata(luaname,serialize(data,true))
- if ok then
- if trace_locating then
- report_resolvers("category %a, cachename %a saved in %a",dataname,cachename,luaname)
- end
- if compilelua(luaname,lucname) then
- if trace_locating then
- report_resolvers("%a compiled to %a",dataname,lucname)
- end
- return true
- else
- if trace_locating then
- report_resolvers("compiling failed for %a, deleting file %a",dataname,lucname)
- end
- removefile(lucname)
- end
- elseif trace_locating then
- report_resolvers("unable to save %a in %a (access error)",dataname,luaname)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-met"] = package.loaded["data-met"] or true
-
--- original size: 5518, stripped down to: 3854
-
-if not modules then modules={} end modules ['data-met']={
- version=1.100,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type=type
-local find=string.find
-local addurlscheme,urlhashed=url.addscheme,url.hashed
-local collapsepath,joinfile=file.collapsepath,file.join
-local report_methods=logs.reporter("resolvers","methods")
-local trace_locating=false
-local trace_methods=false
-trackers.register("resolvers.locating",function(v) trace_methods=v end)
-trackers.register("resolvers.methods",function(v) trace_methods=v end)
-local allocate=utilities.storage.allocate
-local resolvers=resolvers
-local registered={}
-local function splitmethod(filename)
- if not filename then
- return {
- scheme="unknown",
- original=filename,
- }
- end
- if type(filename)=="table" then
- return filename
- end
- filename=collapsepath(filename,".")
- if not find(filename,"://",1,true) then
- return {
- scheme="file",
- path=filename,
- original=filename,
- filename=filename,
- }
- end
- local specification=urlhashed(filename)
- if not specification.scheme or specification.scheme=="" then
- return {
- scheme="file",
- path=filename,
- original=filename,
- filename=filename,
- }
- else
- return specification
- end
-end
-resolvers.splitmethod=splitmethod
-local function methodhandler(what,first,...)
- local method=registered[what]
- if method then
- local how=method.how
- local namespace=method.namespace
- if how=="uri" or how=="url" then
- local specification=splitmethod(first)
- local scheme=specification.scheme
- local resolver=namespace and namespace[scheme]
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, handler %a, argument %a",what,how,scheme,first)
- end
- return resolver(specification,...)
- else
- resolver=namespace.default or namespace.file
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, handler %a, argument %a",what,how,"default",first)
- end
- return resolver(specification,...)
- elseif trace_methods then
- report_methods("resolving, method %a, how %a, handler %a, argument %a",what,how,"unset")
- end
- end
- elseif how=="tag" then
- local resolver=namespace and namespace[first]
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, tag %a",what,how,first)
- end
- return resolver(...)
- else
- resolver=namespace.default or namespace.file
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, tag %a",what,how,"default")
- end
- return resolver(...)
- elseif trace_methods then
- report_methods("resolving, method %a, how %a, tag %a",what,how,"unset")
- end
- end
- end
- else
- report_methods("resolving, invalid method %a")
- end
-end
-resolvers.methodhandler=methodhandler
-function resolvers.registermethod(name,namespace,how)
- registered[name]={
- how=how or "tag",
- namespace=namespace
- }
- namespace["byscheme"]=function(scheme,filename,...)
- if scheme=="file" then
- return methodhandler(name,filename,...)
- else
- return methodhandler(name,addurlscheme(filename,scheme),...)
- end
- end
-end
-local concatinators=allocate { notfound=joinfile }
-local locators=allocate { notfound=function() end }
-local hashers=allocate { notfound=function() end }
-local generators=allocate { notfound=function() end }
-resolvers.concatinators=concatinators
-resolvers.locators=locators
-resolvers.hashers=hashers
-resolvers.generators=generators
-local registermethod=resolvers.registermethod
-registermethod("concatinators",concatinators,"tag")
-registermethod("locators",locators,"uri")
-registermethod("hashers",hashers,"uri")
-registermethod("generators",generators,"uri")
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-res"] = package.loaded["data-res"] or true
-
--- original size: 69576, stripped down to: 44470
-
-if not modules then modules={} end modules ['data-res']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local gsub,find,lower,upper,match,gmatch=string.gsub,string.find,string.lower,string.upper,string.match,string.gmatch
-local concat,insert,remove=table.concat,table.insert,table.remove
-local next,type,rawget,loadfile=next,type,rawget,loadfile
-local mergedtable=table.merged
-local os=os
-local P,S,R,C,Cc,Cs,Ct,Carg=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.Cc,lpeg.Cs,lpeg.Ct,lpeg.Carg
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local formatters=string.formatters
-local filedirname=file.dirname
-local filebasename=file.basename
-local suffixonly=file.suffixonly
-local addsuffix=file.addsuffix
-local removesuffix=file.removesuffix
-local filejoin=file.join
-local collapsepath=file.collapsepath
-local joinpath=file.joinpath
-local is_qualified_path=file.is_qualified_path
-local allocate=utilities.storage.allocate
-local settings_to_array=utilities.parsers.settings_to_array
-local urlhasscheme=url.hasscheme
-local getcurrentdir=lfs.currentdir
-local isfile=lfs.isfile
-local isdir=lfs.isdir
-local setmetatableindex=table.setmetatableindex
-local luasuffixes=utilities.lua.suffixes
-local trace_locating=false trackers .register("resolvers.locating",function(v) trace_locating=v end)
-local trace_details=false trackers .register("resolvers.details",function(v) trace_details=v end)
-local trace_expansions=false trackers .register("resolvers.expansions",function(v) trace_expansions=v end)
-local trace_paths=false trackers .register("resolvers.paths",function(v) trace_paths=v end)
-local resolve_otherwise=true directives.register("resolvers.otherwise",function(v) resolve_otherwise=v end)
-local report_resolving=logs.reporter("resolvers","resolving")
-local resolvers=resolvers
-local expandedpathfromlist=resolvers.expandedpathfromlist
-local checkedvariable=resolvers.checkedvariable
-local splitconfigurationpath=resolvers.splitconfigurationpath
-local methodhandler=resolvers.methodhandler
-local filtered=resolvers.filtered_from_content
-local lookup=resolvers.get_from_content
-local cleanpath=resolvers.cleanpath
-local resolveprefix=resolvers.resolve
-local initializesetter=utilities.setters.initialize
-local ostype,osname,osenv,ossetenv,osgetenv=os.type,os.name,os.env,os.setenv,os.getenv
-resolvers.cacheversion="1.100"
-resolvers.configbanner=""
-resolvers.homedir=environment.homedir
-resolvers.luacnfname="texmfcnf.lua"
-resolvers.luacnffallback="contextcnf.lua"
-resolvers.luacnfstate="unknown"
-local criticalvars={
- "SELFAUTOLOC",
- "SELFAUTODIR",
- "SELFAUTOPARENT",
- "TEXMFCNF",
- "TEXMF",
- "TEXOS",
-}
-if environment.default_texmfcnf then
- resolvers.luacnfspec="home:texmf/web2c;"..environment.default_texmfcnf
-else
- resolvers.luacnfspec=concat ({
- "home:texmf/web2c",
- "selfautoparent:/texmf-local/web2c",
- "selfautoparent:/texmf-context/web2c",
- "selfautoparent:/texmf-dist/web2c",
- "selfautoparent:/texmf/web2c",
- },";")
-end
-local unset_variable="unset"
-local formats=resolvers.formats
-local suffixes=resolvers.suffixes
-local usertypes=resolvers.usertypes
-local dangerous=resolvers.dangerous
-local suffixmap=resolvers.suffixmap
-resolvers.defaultsuffixes={ "tex" }
-local instance=nil
-local variable
-local expansion
-local setenv
-local getenv
-local formatofsuffix=resolvers.formatofsuffix
-local splitpath=resolvers.splitpath
-local splitmethod=resolvers.splitmethod
-setenv=function(key,value,raw)
- if instance then
- instance.environment[key]=value
- ossetenv(key,raw and value or resolveprefix(value))
- end
-end
-getenv=function(key)
- local value=rawget(instance.environment,key)
- if value and value~="" then
- return value
- else
- local e=osgetenv(key)
- return e~=nil and e~="" and checkedvariable(e) or ""
- end
-end
-resolvers.getenv=getenv
-resolvers.setenv=setenv
-local dollarstripper=lpeg.stripper("$")
-local inhibitstripper=P("!")^0*Cs(P(1)^0)
-local expandedvariable,resolvedvariable do
- local function resolveinstancevariable(k)
- return instance.expansions[k]
- end
- local p_variable=P("$")/""
- local p_key=C(R("az","AZ","09","__","--")^1)
- local p_whatever=P(";")*((1-S("!{}/\\"))^1*P(";")/"")+P(";")*(P(";")/"")+P(1)
- local variableexpander=Cs((p_variable*(p_key/resolveinstancevariable)+p_whatever)^1 )
- local p_cleaner=P("\\")/"/"+P(";")*S("!{}/\\")^0*P(";")^1/";"
- local variablecleaner=Cs((p_cleaner+P(1))^0)
- local p_variable=R("az","AZ","09","__","--")^1/resolveinstancevariable
- local p_variable=(P("$")/"")*(p_variable+(P("{")/"")*p_variable*(P("}")/""))
- local variableresolver=Cs((p_variable+P(1))^0)
- expandedvariable=function(var)
- return lpegmatch(variableexpander,var) or var
- end
- function resolvers.reset()
- if trace_locating then
- report_resolving("creating instance")
- end
- local environment={}
- local variables={}
- local expansions={}
- local order={}
- instance={
- environment=environment,
- variables=variables,
- expansions=expansions,
- order=order,
- files={},
- setups={},
- found={},
- foundintrees={},
- hashes={},
- hashed={},
- pathlists=false,
- specification={},
- lists={},
- data={},
- fakepaths={},
- remember=true,
- diskcache=true,
- renewcache=false,
- renewtree=false,
- loaderror=false,
- savelists=true,
- pattern=nil,
- force_suffixes=true,
- pathstack={},
- }
- setmetatableindex(variables,function(t,k)
- local v
- for i=1,#order do
- v=order[i][k]
- if v~=nil then
- t[k]=v
- return v
- end
- end
- if v==nil then
- v=""
- end
- t[k]=v
- return v
- end)
- local repath=resolvers.repath
- setmetatableindex(environment,function(t,k)
- local v=osgetenv(k)
- if v==nil then
- v=variables[k]
- end
- if v~=nil then
- v=checkedvariable(v) or ""
- end
- v=repath(v)
- t[k]=v
- return v
- end)
- setmetatableindex(expansions,function(t,k)
- local v=environment[k]
- if type(v)=="string" then
- v=lpegmatch(variableresolver,v)
- v=lpegmatch(variablecleaner,v)
- end
- t[k]=v
- return v
- end)
- end
-end
-function resolvers.initialized()
- return instance~=nil
-end
-local function reset_hashes()
- instance.lists={}
- instance.pathlists=false
- instance.found={}
-end
-local function reset_caches()
- instance.lists={}
- instance.pathlists=false
-end
-local makepathexpression do
- local slash=P("/")
- local pathexpressionpattern=Cs (
- Cc("^")*(
- Cc("%")*S(".-")+slash^2*P(-1)/"/.*"
-+slash^2/"/"+(1-slash)*P(-1)*Cc("/")+P(1)
- )^1*Cc("$")
- )
- local cache={}
- makepathexpression=function(str)
- if str=="." then
- return "^%./$"
- else
- local c=cache[str]
- if not c then
- c=lpegmatch(pathexpressionpattern,str)
- cache[str]=c
- end
- return c
- end
- end
-end
-local function reportcriticalvariables(cnfspec)
- if trace_locating then
- for i=1,#criticalvars do
- local k=criticalvars[i]
- local v=getenv(k) or "unknown"
- report_resolving("variable %a set to %a",k,v)
- end
- report_resolving()
- if cnfspec then
- report_resolving("using configuration specification %a",type(cnfspec)=="table" and concat(cnfspec,",") or cnfspec)
- end
- report_resolving()
- end
- reportcriticalvariables=function() end
-end
-local function identify_configuration_files()
- local specification=instance.specification
- if #specification==0 then
- local cnfspec=getenv("TEXMFCNF")
- if cnfspec=="" then
- cnfspec=resolvers.luacnfspec
- resolvers.luacnfstate="default"
- else
- resolvers.luacnfstate="environment"
- end
- reportcriticalvariables(cnfspec)
- local cnfpaths=expandedpathfromlist(splitpath(cnfspec))
- local function locatecnf(luacnfname,kind)
- for i=1,#cnfpaths do
- local filepath=cnfpaths[i]
- local filename=collapsepath(filejoin(filepath,luacnfname))
- local realname=resolveprefix(filename)
- if trace_locating then
- local fullpath=gsub(resolveprefix(collapsepath(filepath)),"//","/")
- local weirdpath=find(fullpath,"/texmf.+/texmf") or not find(fullpath,"/web2c",1,true)
- report_resolving("looking for %s %a on %s path %a from specification %a",
- kind,luacnfname,weirdpath and "weird" or "given",fullpath,filepath)
- end
- if isfile(realname) then
- specification[#specification+1]=filename
- if trace_locating then
- report_resolving("found %s configuration file %a",kind,realname)
- end
- end
- end
- end
- locatecnf(resolvers.luacnfname,"regular")
- if #specification==0 then
- locatecnf(resolvers.luacnffallback,"fallback")
- end
- if trace_locating then
- report_resolving()
- end
- elseif trace_locating then
- report_resolving("configuration files already identified")
- end
-end
-local function load_configuration_files()
- local specification=instance.specification
- local setups=instance.setups
- local order=instance.order
- if #specification>0 then
- local luacnfname=resolvers.luacnfname
- for i=1,#specification do
- local filename=specification[i]
- local pathname=filedirname(filename)
- local filename=filejoin(pathname,luacnfname)
- local realname=resolveprefix(filename)
- local blob=loadfile(realname)
- if blob then
- local data=blob()
- local parent=data and data.parent
- if parent then
- local filename=filejoin(pathname,parent)
- local realname=resolveprefix(filename)
- local blob=loadfile(realname)
- if blob then
- local parentdata=blob()
- if parentdata then
- report_resolving("loading configuration file %a",filename)
- data=mergedtable(parentdata,data)
- end
- end
- end
- data=data and data.content
- if data then
- if trace_locating then
- report_resolving("loading configuration file %a",filename)
- report_resolving()
- end
- local variables=data.variables or {}
- local warning=false
- for k,v in next,data do
- local variant=type(v)
- if variant=="table" then
- initializesetter(filename,k,v)
- elseif variables[k]==nil then
- if trace_locating and not warning then
- report_resolving("variables like %a in configuration file %a should move to the 'variables' subtable",
- k,resolveprefix(filename))
- warning=true
- end
- variables[k]=v
- end
- end
- setups[pathname]=variables
- if resolvers.luacnfstate=="default" then
- local cnfspec=variables["TEXMFCNF"]
- if cnfspec then
- if trace_locating then
- report_resolving("reloading configuration due to TEXMF redefinition")
- end
- setenv("TEXMFCNF",cnfspec)
- instance.specification={}
- identify_configuration_files()
- load_configuration_files()
- resolvers.luacnfstate="configuration"
- break
- end
- end
- else
- if trace_locating then
- report_resolving("skipping configuration file %a (no content)",filename)
- end
- setups[pathname]={}
- instance.loaderror=true
- end
- elseif trace_locating then
- report_resolving("skipping configuration file %a (no valid format)",filename)
- end
- order[#order+1]=setups[pathname]
- if instance.loaderror then
- break
- end
- end
- elseif trace_locating then
- report_resolving("warning: no lua configuration files found")
- end
-end
-local expandedpathlist
-local unexpandedpathlist
-function resolvers.configurationfiles()
- return instance.specification or {}
-end
-local function load_file_databases()
- instance.loaderror=false
- instance.files={}
- if not instance.renewcache then
- local hashes=instance.hashes
- for k=1,#hashes do
- local hash=hashes[k]
- resolvers.hashers.byscheme(hash.type,hash.name)
- if instance.loaderror then break end
- end
- end
-end
-local function locate_file_databases()
- local texmfpaths=expandedpathlist("TEXMF")
- if #texmfpaths>0 then
- for i=1,#texmfpaths do
- local path=collapsepath(texmfpaths[i])
- path=gsub(path,"/+$","")
- local stripped=lpegmatch(inhibitstripper,path)
- if stripped~="" then
- local runtime=stripped==path
- path=cleanpath(path)
- local spec=splitmethod(stripped)
- if runtime and (spec.noscheme or spec.scheme=="file") then
- stripped="tree:///"..stripped
- elseif spec.scheme=="cache" or spec.scheme=="file" then
- stripped=spec.path
- end
- if trace_locating then
- if runtime then
- report_resolving("locating list of %a (runtime) (%s)",path,stripped)
- else
- report_resolving("locating list of %a (cached)",path)
- end
- end
- methodhandler('locators',stripped)
- end
- end
- if trace_locating then
- report_resolving()
- end
- elseif trace_locating then
- report_resolving("no texmf paths are defined (using TEXMF)")
- end
-end
-local function generate_file_databases()
- local hashes=instance.hashes
- for k=1,#hashes do
- local hash=hashes[k]
- methodhandler('generators',hash.name)
- end
- if trace_locating then
- report_resolving()
- end
-end
-local function save_file_databases()
- local hashes=instance.hashes
- local files=instance.files
- for i=1,#hashes do
- local hash=hashes[i]
- local cachename=hash.name
- if hash.cache then
- local content=files[cachename]
- caches.collapsecontent(content)
- if trace_locating then
- report_resolving("saving tree %a",cachename)
- end
- caches.savecontent(cachename,"files",content)
- elseif trace_locating then
- report_resolving("not saving runtime tree %a",cachename)
- end
- end
-end
-function resolvers.renew(hashname)
- local files=instance.files
- if hashname and hashname~="" then
- local expanded=expansion(hashname) or ""
- if expanded~="" then
- if trace_locating then
- report_resolving("identifying tree %a from %a",expanded,hashname)
- end
- hashname=expanded
- else
- if trace_locating then
- report_resolving("identifying tree %a",hashname)
- end
- end
- local realpath=resolveprefix(hashname)
- if isdir(realpath) then
- if trace_locating then
- report_resolving("using path %a",realpath)
- end
- methodhandler('generators',hashname)
- local content=files[hashname]
- caches.collapsecontent(content)
- if trace_locating then
- report_resolving("saving tree %a",hashname)
- end
- caches.savecontent(hashname,"files",content)
- else
- report_resolving("invalid path %a",realpath)
- end
- end
-end
-local function load_databases()
- locate_file_databases()
- if instance.diskcache and not instance.renewcache then
- load_file_databases()
- if instance.loaderror then
- generate_file_databases()
- save_file_databases()
- end
- else
- generate_file_databases()
- if instance.renewcache then
- save_file_databases()
- end
- end
-end
-function resolvers.appendhash(type,name,cache)
- local hashed=instance.hashed
- local hashes=instance.hashes
- if hashed[name] then
- else
- if trace_locating then
- report_resolving("hash %a appended",name)
- end
- insert(hashes,{ type=type,name=name,cache=cache } )
- hashed[name]=cache
- end
-end
-function resolvers.prependhash(type,name,cache)
- local hashed=instance.hashed
- local hashes=instance.hashes
- if hashed[name] then
- else
- if trace_locating then
- report_resolving("hash %a prepended",name)
- end
- insert(hashes,1,{ type=type,name=name,cache=cache } )
- hashed[name]=cache
- end
-end
-function resolvers.extendtexmfvariable(specification)
- local environment=instance.environment
- local variables=instance.variables
- local texmftrees=splitpath(getenv("TEXMF"))
- insert(texmftrees,1,specification)
- texmftrees=concat(texmftrees,",")
- if environment["TEXMF"] then
- environment["TEXMF"]=texmftrees
- elseif variables["TEXMF"] then
- variables["TEXMF"]=texmftrees
- else
- end
- reset_hashes()
-end
-function resolvers.splitexpansions()
- local expansions=instance.expansions
- for k,v in next,expansions do
- local t,tn,h,p={},0,{},splitconfigurationpath(v)
- for kk=1,#p do
- local vv=p[kk]
- if vv~="" and not h[vv] then
- tn=tn+1
- t[tn]=vv
- h[vv]=true
- end
- end
- if tn>1 then
- expansions[k]=t
- else
- expansions[k]=t[1]
- end
- end
-end
-function resolvers.datastate()
- return caches.contentstate()
-end
-variable=function(name)
- local variables=instance.variables
- local name=name and lpegmatch(dollarstripper,name)
- local result=name and variables[name]
- return result~=nil and result or ""
-end
-expansion=function(name)
- local expansions=instance.expansions
- local name=name and lpegmatch(dollarstripper,name)
- local result=name and expansions[name]
- return result~=nil and result or ""
-end
-resolvers.variable=variable
-resolvers.expansion=expansion
-unexpandedpathlist=function(str)
- local pth=variable(str)
- local lst=splitpath(pth)
- return expandedpathfromlist(lst)
-end
-function resolvers.unexpandedpath(str)
- return joinpath(unexpandedpathlist(str))
-end
-function resolvers.pushpath(name)
- local pathstack=instance.pathstack
- local lastpath=pathstack[#pathstack]
- local pluspath=filedirname(name)
- if lastpath then
- lastpath=collapsepath(filejoin(lastpath,pluspath))
- else
- lastpath=collapsepath(pluspath)
- end
- insert(pathstack,lastpath)
- if trace_paths then
- report_resolving("pushing path %a",lastpath)
- end
-end
-function resolvers.poppath()
- local pathstack=instance.pathstack
- if trace_paths and #pathstack>0 then
- report_resolving("popping path %a",pathstack[#pathstack])
- end
- remove(pathstack)
-end
-function resolvers.stackpath()
- local pathstack=instance.pathstack
- local currentpath=pathstack[#pathstack]
- return currentpath~="" and currentpath or nil
-end
-local done={}
-function resolvers.resetextrapaths()
- local extra_paths=instance.extra_paths
- if not extra_paths then
- done={}
- instance.extra_paths={}
- elseif #ep>0 then
- done={}
- reset_caches()
- end
-end
-function resolvers.getextrapaths()
- return instance.extra_paths or {}
-end
-function resolvers.registerextrapath(paths,subpaths)
- if not subpaths or subpaths=="" then
- if not paths or path=="" then
- return
- elseif done[paths] then
- return
- end
- end
- local paths=settings_to_array(paths)
- local subpaths=settings_to_array(subpaths)
- local extra_paths=instance.extra_paths or {}
- local oldn=#extra_paths
- local newn=oldn
- local nofpaths=#paths
- local nofsubpaths=#subpaths
- if nofpaths>0 then
- if nofsubpaths>0 then
- for i=1,nofpaths do
- local p=paths[i]
- for j=1,nofsubpaths do
- local s=subpaths[j]
- local ps=p.."/"..s
- if not done[ps] then
- newn=newn+1
- extra_paths[newn]=cleanpath(ps)
- done[ps]=true
- end
- end
- end
- else
- for i=1,nofpaths do
- local p=paths[i]
- if not done[p] then
- newn=newn+1
- extra_paths[newn]=cleanpath(p)
- done[p]=true
- end
- end
- end
- elseif nofsubpaths>0 then
- for i=1,oldn do
- for j=1,nofsubpaths do
- local s=subpaths[j]
- local ps=extra_paths[i].."/"..s
- if not done[ps] then
- newn=newn+1
- extra_paths[newn]=cleanpath(ps)
- done[ps]=true
- end
- end
- end
- end
- if newn>0 then
- instance.extra_paths=extra_paths
- end
- if newn~=oldn then
- reset_caches()
- end
-end
-function resolvers.pushextrapath(path)
- local paths=settings_to_array(path)
- local extra_stack=instance.extra_stack
- if extra_stack then
- insert(extra_stack,1,paths)
- else
- instance.extra_stack={ paths }
- end
- reset_caches()
-end
-function resolvers.popextrapath()
- local extra_stack=instance.extra_stack
- if extra_stack then
- reset_caches()
- return remove(extra_stack,1)
- end
-end
-local function made_list(instance,list,extra_too)
- local done={}
- local new={}
- local newn=0
- local function add(p)
- for k=1,#p do
- local v=p[k]
- if not done[v] then
- done[v]=true
- newn=newn+1
- new[newn]=v
- end
- end
- end
- for k=1,#list do
- local v=list[k]
- if done[v] then
- elseif find(v,"^[%.%/]$") then
- done[v]=true
- newn=newn+1
- new[newn]=v
- else
- break
- end
- end
- if extra_too then
- local extra_stack=instance.extra_stack
- local extra_paths=instance.extra_paths
- if extra_stack and #extra_stack>0 then
- for k=1,#extra_stack do
- add(extra_stack[k])
- end
- end
- if extra_paths and #extra_paths>0 then
- add(extra_paths)
- end
- end
- add(list)
- return new
-end
-expandedpathlist=function(str,extra_too)
- if not str then
- return {}
- elseif instance.savelists then
- str=lpegmatch(dollarstripper,str)
- local lists=instance.lists
- local lst=lists[str]
- if not lst then
- local l=made_list(instance,splitpath(expansion(str)),extra_too)
- lst=expandedpathfromlist(l)
- lists[str]=lst
- end
- return lst
- else
- local lst=splitpath(expansion(str))
- return made_list(instance,expandedpathfromlist(lst),extra_too)
- end
-end
-resolvers.expandedpathlist=expandedpathlist
-resolvers.unexpandedpathlist=unexpandedpathlist
-function resolvers.cleanpathlist(str)
- local t=expandedpathlist(str)
- if t then
- for i=1,#t do
- t[i]=collapsepath(cleanpath(t[i]))
- end
- end
- return t
-end
-function resolvers.expandpath(str)
- return joinpath(expandedpathlist(str))
-end
-local function expandedpathlistfromvariable(str)
- str=lpegmatch(dollarstripper,str)
- local tmp=resolvers.variableofformatorsuffix(str)
- return expandedpathlist(tmp~="" and tmp or str)
-end
-function resolvers.expandpathfromvariable(str)
- return joinpath(expandedpathlistfromvariable(str))
-end
-resolvers.expandedpathlistfromvariable=expandedpathlistfromvariable
-function resolvers.cleanedpathlist(v)
- local t=expandedpathlist(v)
- for i=1,#t do
- t[i]=resolveprefix(cleanpath(t[i]))
- end
- return t
-end
-function resolvers.expandbraces(str)
- local pth=expandedpathfromlist(splitpath(str))
- return joinpath(pth)
-end
-function resolvers.registerfilehash(name,content,someerror)
- local files=instance.files
- if content then
- files[name]=content
- else
- files[name]={}
- if somerror==true then
- instance.loaderror=someerror
- end
- end
-end
-function resolvers.getfilehashes()
- return instance and instance.files or {}
-end
-function resolvers.gethashes()
- return instance and instance.hashes or {}
-end
-function resolvers.renewcache()
- if instance then
- instance.renewcache=true
- end
-end
-local function isreadable(name)
- local readable=isfile(name)
- if trace_details then
- if readable then
- report_resolving("file %a is readable",name)
- else
- report_resolving("file %a is not readable",name)
- end
- end
- return readable
-end
-local function collect_files(names)
- local filelist={}
- local noffiles=0
- local function check(hash,root,pathname,path,basename,name)
- if not pathname or find(path,pathname) then
- local variant=hash.type
- local search=filejoin(root,path,name)
- local result=methodhandler('concatinators',variant,root,path,name)
- if trace_details then
- report_resolving("match: variant %a, search %a, result %a",variant,search,result)
- end
- noffiles=noffiles+1
- filelist[noffiles]={ variant,search,result }
- end
- end
- for k=1,#names do
- local filename=names[k]
- if trace_details then
- report_resolving("checking name %a",filename)
- end
- local basename=filebasename(filename)
- local pathname=filedirname(filename)
- if pathname=="" or find(pathname,"^%.") then
- pathname=false
- else
- pathname=gsub(pathname,"%*",".*")
- pathname="/"..pathname.."$"
- end
- local hashes=instance.hashes
- local files=instance.files
- for h=1,#hashes do
- local hash=hashes[h]
- local hashname=hash.name
- local content=hashname and files[hashname]
- if content then
- if trace_details then
- report_resolving("deep checking %a, base %a, pattern %a",hashname,basename,pathname)
- end
- local path,name=lookup(content,basename)
- if path then
- local metadata=content.metadata
- local realroot=metadata and metadata.path or hashname
- if type(path)=="string" then
- check(hash,realroot,pathname,path,basename,name)
- else
- for i=1,#path do
- check(hash,realroot,pathname,path[i],basename,name)
- end
- end
- end
- elseif trace_locating then
- report_resolving("no match in %a (%s)",hashname,basename)
- end
- end
- end
- return noffiles>0 and filelist or nil
-end
-local fit={}
-function resolvers.registerintrees(filename,format,filetype,usedmethod,foundname)
- local foundintrees=instance.foundintrees
- if usedmethod=="direct" and filename==foundname and fit[foundname] then
- else
- local collapsed=collapsepath(foundname,true)
- local t={
- filename=filename,
- format=format~="" and format or nil,
- filetype=filetype~="" and filetype or nil,
- usedmethod=usedmethod,
- foundname=foundname,
- fullname=collapsed,
- }
- fit[foundname]=t
- foundintrees[#foundintrees+1]=t
- end
-end
-function resolvers.foundintrees()
- return instance.foundintrees or {}
-end
-function resolvers.foundintree(fullname)
- local f=fit[fullname]
- return f and f.usedmethod=="database"
-end
-local function can_be_dir(name)
- local fakepaths=instance.fakepaths
- if not fakepaths[name] then
- if isdir(name) then
- fakepaths[name]=1
- else
- fakepaths[name]=2
- end
- end
- return fakepaths[name]==1
-end
-local preparetreepattern=Cs((P(".")/"%%."+P("-")/"%%-"+P(1))^0*Cc("$"))
-local collect_instance_files
-local function find_analyze(filename,askedformat,allresults)
- local filetype=''
- local filesuffix=suffixonly(filename)
- local wantedfiles={}
- wantedfiles[#wantedfiles+1]=filename
- if askedformat=="" then
- if filesuffix=="" or not suffixmap[filesuffix] then
- local defaultsuffixes=resolvers.defaultsuffixes
- for i=1,#defaultsuffixes do
- local forcedname=filename..'.'..defaultsuffixes[i]
- wantedfiles[#wantedfiles+1]=forcedname
- filetype=formatofsuffix(forcedname)
- if trace_locating then
- report_resolving("forcing filetype %a",filetype)
- end
- end
- else
- filetype=formatofsuffix(filename)
- if trace_locating then
- report_resolving("using suffix based filetype %a",filetype)
- end
- end
- else
- if filesuffix=="" or not suffixmap[filesuffix] then
- local format_suffixes=suffixes[askedformat]
- if format_suffixes then
- for i=1,#format_suffixes do
- wantedfiles[#wantedfiles+1]=filename.."."..format_suffixes[i]
- end
- end
- end
- filetype=askedformat
- if trace_locating then
- report_resolving("using given filetype %a",filetype)
- end
- end
- return filetype,wantedfiles
-end
-local function find_direct(filename,allresults)
- if not dangerous[askedformat] and isreadable(filename) then
- if trace_details then
- report_resolving("file %a found directly",filename)
- end
- return "direct",{ filename }
- end
-end
-local function find_wildcard(filename,allresults)
- if find(filename,'*',1,true) then
- if trace_locating then
- report_resolving("checking wildcard %a",filename)
- end
- local result=resolvers.findwildcardfiles(filename)
- if result then
- return "wildcard",result
- end
- end
-end
-local function find_qualified(filename,allresults,askedformat,alsostripped)
- if not is_qualified_path(filename) then
- return
- end
- if trace_locating then
- report_resolving("checking qualified name %a",filename)
- end
- if isreadable(filename) then
- if trace_details then
- report_resolving("qualified file %a found",filename)
- end
- return "qualified",{ filename }
- end
- if trace_details then
- report_resolving("locating qualified file %a",filename)
- end
- local forcedname,suffix="",suffixonly(filename)
- if suffix=="" then
- local format_suffixes=askedformat=="" and resolvers.defaultsuffixes or suffixes[askedformat]
- if format_suffixes then
- for i=1,#format_suffixes do
- local suffix=format_suffixes[i]
- forcedname=filename.."."..suffix
- if isreadable(forcedname) then
- if trace_locating then
- report_resolving("no suffix, forcing format filetype %a",suffix)
- end
- return "qualified",{ forcedname }
- end
- end
- end
- end
- if alsostripped and suffix and suffix~="" then
- local basename=filebasename(filename)
- local pattern=lpegmatch(preparetreepattern,filename)
- local savedformat=askedformat
- local format=savedformat or ""
- if format=="" then
- askedformat=formatofsuffix(suffix)
- end
- if not format then
- askedformat="othertextfiles"
- end
- if basename~=filename then
- local resolved=collect_instance_files(basename,askedformat,allresults)
- if #resolved==0 then
- local lowered=lower(basename)
- if filename~=lowered then
- resolved=collect_instance_files(lowered,askedformat,allresults)
- end
- end
- resolvers.format=savedformat
- if #resolved>0 then
- local result={}
- for r=1,#resolved do
- local rr=resolved[r]
- if find(rr,pattern) then
- result[#result+1]=rr
- end
- end
- if #result>0 then
- return "qualified",result
- end
- end
- end
- end
-end
-local function check_subpath(fname)
- if isreadable(fname) then
- if trace_details then
- report_resolving("found %a by deep scanning",fname)
- end
- return fname
- end
-end
-local function makepathlist(list,filetype)
- local typespec=resolvers.variableofformat(filetype)
- local pathlist=expandedpathlist(typespec,filetype and usertypes[filetype])
- local entry={}
- if pathlist and #pathlist>0 then
- for k=1,#pathlist do
- local path=pathlist[k]
- local prescanned=find(path,'^!!')
- local resursive=find(path,'//$')
- local pathname=lpegmatch(inhibitstripper,path)
- local expression=makepathexpression(pathname)
- local barename=gsub(pathname,"/+$","")
- barename=resolveprefix(barename)
- local scheme=urlhasscheme(barename)
- local schemename=gsub(barename,"%.%*$",'')
- entry[k]={
- path=path,
- pathname=pathname,
- prescanned=prescanned,
- recursive=recursive,
- expression=expression,
- barename=barename,
- scheme=scheme,
- schemename=schemename,
- }
- end
- entry.typespec=typespec
- list[filetype]=entry
- else
- list[filetype]=false
- end
- return entry
-end
-local function find_intree(filename,filetype,wantedfiles,allresults)
- local pathlists=instance.pathlists
- if not pathlists then
- pathlists=setmetatableindex({},makepathlist)
- instance.pathlists=pathlists
- end
- local pathlist=pathlists[filetype]
- if pathlist then
- local method="intree"
- local filelist=collect_files(wantedfiles)
- local dirlist={}
- local result={}
- if filelist then
- for i=1,#filelist do
- dirlist[i]=filedirname(filelist[i][3]).."/"
- end
- end
- if trace_details then
- report_resolving("checking filename %a in tree",filename)
- end
- for k=1,#pathlist do
- local entry=pathlist[k]
- local path=entry.path
- local pathname=entry.pathname
- local done=false
- if filelist then
- local expression=entry.expression
- if trace_details then
- report_resolving("using pattern %a for path %a",expression,pathname)
- end
- for k=1,#filelist do
- local fl=filelist[k]
- local f=fl[2]
- local d=dirlist[k]
- if find(d,expression) or find(resolveprefix(d),expression) then
- result[#result+1]=resolveprefix(fl[3])
- done=true
- if allresults then
- if trace_details then
- report_resolving("match to %a in hash for file %a and path %a, continue scanning",expression,f,d)
- end
- else
- if trace_details then
- report_resolving("match to %a in hash for file %a and path %a, quit scanning",expression,f,d)
- end
- break
- end
- elseif trace_details then
- report_resolving("no match to %a in hash for file %a and path %a",expression,f,d)
- end
- end
- end
- if done then
- method="database"
- else
- method="filesystem"
- local scheme=entry.scheme
- if not scheme or scheme=="file" then
- local pname=entry.schemename
- if not find(pname,"*",1,true) then
- if can_be_dir(pname) then
- if not done and not entry.prescanned then
- if trace_details then
- report_resolving("quick root scan for %a",pname)
- end
- for k=1,#wantedfiles do
- local w=wantedfiles[k]
- local fname=check_subpath(filejoin(pname,w))
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- end
- if not done and entry.recursive then
- if trace_details then
- report_resolving("scanning filesystem for %a",pname)
- end
- local files=resolvers.simplescanfiles(pname,false,true)
- for k=1,#wantedfiles do
- local w=wantedfiles[k]
- local subpath=files[w]
- if not subpath or subpath=="" then
- elseif type(subpath)=="string" then
- local fname=check_subpath(filejoin(pname,subpath,w))
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- else
- for i=1,#subpath do
- local sp=subpath[i]
- if sp=="" then
- else
- local fname=check_subpath(filejoin(pname,sp,w))
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- end
- end
- if done and not allresults then
- break
- end
- end
- end
- end
- end
- end
- else
- end
- else
- for k=1,#wantedfiles do
- local pname=entry.barename
- local fname=methodhandler('finders',pname.."/"..wantedfiles[k])
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- end
- end
- end
- if done and not allresults then
- break
- end
- end
- if #result>0 then
- return method,result
- end
- end
-end
-local function find_onpath(filename,filetype,wantedfiles,allresults)
- if trace_details then
- report_resolving("checking filename %a, filetype %a, wanted files %a",filename,filetype,concat(wantedfiles," | "))
- end
- local result={}
- for k=1,#wantedfiles do
- local fname=wantedfiles[k]
- if fname and isreadable(fname) then
- filename=fname
- result[#result+1]=filejoin('.',fname)
- if not allresults then
- break
- end
- end
- end
- if #result>0 then
- return "onpath",result
- end
-end
-local function find_otherwise(filename,filetype,wantedfiles,allresults)
- local filelist=collect_files(wantedfiles)
- local fl=filelist and filelist[1]
- if fl then
- return "otherwise",{ resolveprefix(fl[3]) }
- end
-end
-collect_instance_files=function(filename,askedformat,allresults)
- if not filename or filename=="" then
- return {}
- end
- askedformat=askedformat or ""
- filename=collapsepath(filename,".")
- filename=gsub(filename,"^%./",getcurrentdir().."/")
- if allresults then
- local filetype,wantedfiles=find_analyze(filename,askedformat)
- local results={
- { find_direct (filename,true) },
- { find_wildcard (filename,true) },
- { find_qualified(filename,true,askedformat) },
- { find_intree (filename,filetype,wantedfiles,true) },
- { find_onpath (filename,filetype,wantedfiles,true) },
- { find_otherwise(filename,filetype,wantedfiles,true) },
- }
- local result={}
- local status={}
- local done={}
- for k,r in next,results do
- local method,list=r[1],r[2]
- if method and list then
- for i=1,#list do
- local c=collapsepath(list[i])
- if not done[c] then
- result[#result+1]=c
- done[c]=true
- end
- status[#status+1]=formatters["%-10s: %s"](method,c)
- end
- end
- end
- if trace_details then
- report_resolving("lookup status: %s",table.serialize(status,filename))
- end
- return result,status
- else
- local method,result,stamp,filetype,wantedfiles
- if instance.remember then
- if askedformat=="" then
- stamp=formatters["%s::%s"](suffixonly(filename),filename)
- else
- stamp=formatters["%s::%s"](askedformat,filename)
- end
- result=stamp and instance.found[stamp]
- if result then
- if trace_locating then
- report_resolving("remembered file %a",filename)
- end
- return result
- end
- end
- method,result=find_direct(filename)
- if not result then
- method,result=find_wildcard(filename)
- if not result then
- method,result=find_qualified(filename,false,askedformat)
- if not result then
- filetype,wantedfiles=find_analyze(filename,askedformat)
- method,result=find_intree(filename,filetype,wantedfiles)
- if not result then
- method,result=find_onpath(filename,filetype,wantedfiles)
- if resolve_otherwise and not result then
- method,result=find_otherwise(filename,filetype,wantedfiles)
- end
- end
- end
- end
- end
- if result and #result>0 then
- local foundname=collapsepath(result[1])
- resolvers.registerintrees(filename,askedformat,filetype,method,foundname)
- result={ foundname }
- else
- result={}
- end
- if stamp then
- if trace_locating then
- report_resolving("remembering file %a using hash %a",filename,stamp)
- end
- instance.found[stamp]=result
- end
- return result
- end
-end
-local function findfiles(filename,filetype,allresults)
- if not filename or filename=="" then
- return {}
- end
- if allresults==nil then
- allresults=true
- end
- local result,status=collect_instance_files(filename,filetype or "",allresults)
- if not result or #result==0 then
- local lowered=lower(filename)
- if filename~=lowered then
- result,status=collect_instance_files(lowered,filetype or "",allresults)
- end
- end
- return result or {},status
-end
-local function findfile(filename,filetype)
- if not filename or filename=="" then
- return ""
- else
- return findfiles(filename,filetype,false)[1] or ""
- end
-end
-resolvers.findfiles=findfiles
-resolvers.findfile=findfile
-resolvers.find_file=findfile
-resolvers.find_files=findfiles
-function resolvers.findpath(filename,filetype)
- return filedirname(findfiles(filename,filetype,false)[1] or "")
-end
-local function findgivenfiles(filename,allresults)
- local hashes=instance.hashes
- local files=instance.files
- local base=filebasename(filename)
- local result={}
- local function okay(hash,path,name)
- local found=methodhandler('concatinators',hash.type,hash.name,path,name)
- if found and found~="" then
- result[#result+1]=resolveprefix(found)
- return not allresults
- end
- end
- for k=1,#hashes do
- local hash=hashes[k]
- local content=files[hash.name]
- if content then
- local path,name=lookup(content,base)
- if not path then
- elseif type(path)=="string" then
- if okay(hash,path,name) then
- return result
- end
- else
- for i=1,#path do
- if okay(hash,path[i],name) then
- return result
- end
- end
- end
- end
- end
- return result
-end
-function resolvers.findgivenfiles(filename)
- return findgivenfiles(filename,true)
-end
-function resolvers.findgivenfile(filename)
- return findgivenfiles(filename,false)[1] or ""
-end
-local makewildcard=Cs(
- (P("^")^0*P("/")*P(-1)+P(-1))/".*"+(P("^")^0*P("/")/"")^0*(P("*")/".*"+P("-")/"%%-"+P(".")/"%%."+P("?")/"."+P("\\")/"/"+P(1))^0
-)
-function resolvers.wildcardpattern(pattern)
- return lpegmatch(makewildcard,pattern) or pattern
-end
-local function findwildcardfiles(filename,allresults,result)
- local files=instance.files
- local hashes=instance.hashes
- local result=result or {}
- local base=filebasename(filename)
- local dirn=filedirname(filename)
- local path=lower(lpegmatch(makewildcard,dirn) or dirn)
- local name=lower(lpegmatch(makewildcard,base) or base)
- if find(name,"*",1,true) then
- local function okay(found,path,base,hashname,hashtype)
- if find(found,path) then
- local full=methodhandler('concatinators',hashtype,hashname,found,base)
- if full and full~="" then
- result[#result+1]=resolveprefix(full)
- return not allresults
- end
- end
- end
- for k=1,#hashes do
- local hash=hashes[k]
- local hashname=hash.name
- local hashtype=hash.type
- if hashname and hashtype then
- for found,base in filtered(files[hashname],name) do
- if type(found)=='string' then
- if okay(found,path,base,hashname,hashtype) then
- break
- end
- else
- for i=1,#found do
- if okay(found[i],path,base,hashname,hashtype) then
- break
- end
- end
- end
- end
- end
- end
- else
- local function okayokay(found,path,base,hashname,hashtype)
- if find(found,path) then
- local full=methodhandler('concatinators',hashtype,hashname,found,base)
- if full and full~="" then
- result[#result+1]=resolveprefix(full)
- return not allresults
- end
- end
- end
- for k=1,#hashes do
- local hash=hashes[k]
- local hashname=hash.name
- local hashtype=hash.type
- if hashname and hashtype then
- local found,base=lookup(content,base)
- if not found then
- elseif type(found)=='string' then
- if okay(found,path,base,hashname,hashtype) then
- break
- end
- else
- for i=1,#found do
- if okay(found[i],path,base,hashname,hashtype) then
- break
- end
- end
- end
- end
- end
- end
- return result
-end
-function resolvers.findwildcardfiles(filename,result)
- return findwildcardfiles(filename,true,result)
-end
-function resolvers.findwildcardfile(filename)
- return findwildcardfiles(filename,false)[1] or ""
-end
-do
- local starttiming=statistics.starttiming
- local stoptiming=statistics.stoptiming
- local elapsedtime=statistics.elapsedtime
- function resolvers.starttiming()
- starttiming(instance)
- end
- function resolvers.stoptiming()
- stoptiming(instance)
- end
- function resolvers.loadtime()
- return elapsedtime(instance)
- end
-end
-function resolvers.automount()
-end
-function resolvers.load(option)
- resolvers.starttiming()
- identify_configuration_files()
- load_configuration_files()
- if option~="nofiles" then
- load_databases()
- resolvers.automount()
- end
- resolvers.stoptiming()
- local files=instance.files
- return files and next(files) and true
-end
-local function report(str)
- if trace_locating then
- report_resolving(str)
- else
- print(str)
- end
-end
-function resolvers.dowithfilesandreport(command,files,...)
- if files and #files>0 then
- if trace_locating then
- report('')
- end
- if type(files)=="string" then
- files={ files }
- end
- for f=1,#files do
- local file=files[f]
- local result=command(file,...)
- if type(result)=='string' then
- report(result)
- else
- for i=1,#result do
- report(result[i])
- end
- end
- end
- end
-end
-function resolvers.showpath(str)
- return joinpath(expandedpathlist(resolvers.formatofvariable(str)))
-end
-function resolvers.registerfile(files,name,path)
- if files[name] then
- if type(files[name])=='string' then
- files[name]={ files[name],path }
- else
- files[name]=path
- end
- else
- files[name]=path
- end
-end
-function resolvers.dowithpath(name,func)
- local pathlist=expandedpathlist(name)
- for i=1,#pathlist do
- func("^"..cleanpath(pathlist[i]))
- end
-end
-function resolvers.dowithvariable(name,func)
- func(expandedvariable(name))
-end
-function resolvers.locateformat(name)
- local engine=environment.ownmain or "luatex"
- local barename=removesuffix(file.basename(name))
- local fullname=addsuffix(barename,"fmt")
- local fmtname=caches.getfirstreadablefile(fullname,"formats",engine) or ""
- if fmtname=="" then
- fmtname=findfile(fullname)
- fmtname=cleanpath(fmtname)
- end
- if fmtname~="" then
- local barename=removesuffix(fmtname)
- local luaname=addsuffix(barename,luasuffixes.lua)
- local lucname=addsuffix(barename,luasuffixes.luc)
- local luiname=addsuffix(barename,luasuffixes.lui)
- if isfile(luiname) then
- return fmtname,luiname
- elseif isfile(lucname) then
- return fmtname,lucname
- elseif isfile(luaname) then
- return fmtname,luaname
- end
- end
- return nil,nil
-end
-function resolvers.booleanvariable(str,default)
- local b=expansion(str)
- if b=="" then
- return default
- else
- b=toboolean(b)
- return (b==nil and default) or b
- end
-end
-function resolvers.dowithfilesintree(pattern,handle,before,after)
- local hashes=instance.hashes
- local files=instance.files
- for i=1,#hashes do
- local hash=hashes[i]
- local blobtype=hash.type
- local blobpath=hash.name
- if blobtype and blobpath then
- local total=0
- local checked=0
- local done=0
- if before then
- before(blobtype,blobpath,pattern)
- end
- for path,name in filtered(files[blobpath],pattern) do
- if type(path)=="string" then
- checked=checked+1
- if handle(blobtype,blobpath,path,name) then
- done=done+1
- end
- else
- checked=checked+#path
- for i=1,#path do
- if handle(blobtype,blobpath,path[i],name) then
- done=done+1
- end
- end
- end
- end
- if after then
- after(blobtype,blobpath,pattern,checked,done)
- end
- end
- end
-end
-function resolvers.knownvariables(pattern)
- if instance then
- local environment=instance.environment
- local variables=instance.variables
- local expansions=instance.expansions
- local order=instance.order
- local pattern=upper(pattern or "")
- local result={}
- for i=1,#order do
- for key in next,order[i] do
- if result[key]==nil and key~="" and (pattern=="" or find(upper(key),pattern)) then
- result[key]={
- environment=rawget(environment,key),
- variable=key,
- expansion=expansions[key],
- resolved=resolveprefix(expansions[key]),
- }
- end
- end
- end
- return result
- else
- return {}
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-pre"] = package.loaded["data-pre"] or true
-
--- original size: 5088, stripped down to: 3144
-
-if not modules then modules={} end modules ['data-pre']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local insert,remove=table.insert,table.remove
-local resolvers=resolvers
-local prefixes=resolvers.prefixes
-local cleanpath=resolvers.cleanpath
-local findgivenfile=resolvers.findgivenfile
-local expansion=resolvers.expansion
-local getenv=resolvers.getenv
-local basename=file.basename
-local dirname=file.dirname
-local joinpath=file.join
-local isfile=lfs.isfile
-prefixes.environment=function(str)
- return cleanpath(expansion(str))
-end
-local function relative(str,n)
- if not isfile(str) then
- local pstr="./"..str
- if isfile(pstr) then
- str=pstr
- else
- local p="../"
- for i=1,n or 2 do
- local pstr=p..str
- if isfile(pstr) then
- str=pstr
- break
- else
- p=p.."../"
- end
- end
- end
- end
- return cleanpath(str)
-end
-local function locate(str)
- local fullname=findgivenfile(str) or ""
- return cleanpath(fullname~="" and fullname or str)
-end
-prefixes.relative=relative
-prefixes.locate=locate
-prefixes.auto=function(str)
- local fullname=relative(str)
- if not isfile(fullname) then
- fullname=locate(str)
- end
- return fullname
-end
-prefixes.filename=function(str)
- local fullname=findgivenfile(str) or ""
- return cleanpath(basename((fullname~="" and fullname) or str))
-end
-prefixes.pathname=function(str)
- local fullname=findgivenfile(str) or ""
- return cleanpath(dirname((fullname~="" and fullname) or str))
-end
-prefixes.selfautoloc=function(str)
- local pth=getenv('SELFAUTOLOC')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.selfautoparent=function(str)
- local pth=getenv('SELFAUTOPARENT')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.selfautodir=function(str)
- local pth=getenv('SELFAUTODIR')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.home=function(str)
- local pth=getenv('HOME')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.env=prefixes.environment
-prefixes.rel=prefixes.relative
-prefixes.loc=prefixes.locate
-prefixes.kpse=prefixes.locate
-prefixes.full=prefixes.locate
-prefixes.file=prefixes.filename
-prefixes.path=prefixes.pathname
-local inputstack={}
-local stackpath=resolvers.stackpath
-local function toppath()
- if not inputstack then
- return "."
- end
- local pathname=dirname(inputstack[#inputstack] or "")
- if pathname=="" then
- return "."
- else
- return pathname
- end
-end
-local function jobpath()
- local path=stackpath()
- if not path or path=="" then
- return "."
- else
- return path
- end
-end
-local function pushinputname(name)
- insert(inputstack,name)
-end
-local function popinputname(name)
- return remove(inputstack)
-end
-resolvers.toppath=toppath
-resolvers.jobpath=jobpath
-resolvers.pushinputname=pushinputname
-resolvers.popinputname=popinputname
-prefixes.toppath=function(str) return cleanpath(joinpath(toppath(),str)) end
-prefixes.jobpath=function(str) return cleanpath(joinpath(jobpath(),str)) end
-resolvers.setdynamic("toppath")
-resolvers.setdynamic("jobpath")
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-inp"] = package.loaded["data-inp"] or true
-
--- original size: 910, stripped down to: 818
-
-if not modules then modules={} end modules ['data-inp']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local allocate=utilities.storage.allocate
-local resolvers=resolvers
-local methodhandler=resolvers.methodhandler
-local registermethod=resolvers.registermethod
-local finders=allocate { helpers={},notfound=function() end }
-local openers=allocate { helpers={},notfound=function() end }
-local loaders=allocate { helpers={},notfound=function() return false,nil,0 end }
-registermethod("finders",finders,"uri")
-registermethod("openers",openers,"uri")
-registermethod("loaders",loaders,"uri")
-resolvers.finders=finders
-resolvers.openers=openers
-resolvers.loaders=loaders
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-out"] = package.loaded["data-out"] or true
-
--- original size: 551, stripped down to: 470
-
-if not modules then modules={} end modules ['data-out']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local allocate=utilities.storage.allocate
-local resolvers=resolvers
-local registermethod=resolvers.registermethod
-local savers=allocate { helpers={} }
-resolvers.savers=savers
-registermethod("savers",savers,"uri")
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-fil"] = package.loaded["data-fil"] or true
-
--- original size: 4365, stripped down to: 3452
-
-if not modules then modules={} end modules ['data-fil']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local ioopen=io.open
-local isdir=lfs.isdir
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_files=logs.reporter("resolvers","files")
-local resolvers=resolvers
-local resolveprefix=resolvers.resolve
-local findfile=resolvers.findfile
-local scanfiles=resolvers.scanfiles
-local registerfilehash=resolvers.registerfilehash
-local appendhash=resolvers.appendhash
-local loadcachecontent=caches.loadcontent
-function resolvers.locators.file(specification)
- local filename=specification.filename
- local realname=resolveprefix(filename)
- if realname and realname~='' and isdir(realname) then
- if trace_locating then
- report_files("file locator %a found as %a",filename,realname)
- end
- appendhash('file',filename,true)
- elseif trace_locating then
- report_files("file locator %a not found",filename)
- end
-end
-function resolvers.hashers.file(specification)
- local pathname=specification.filename
- local content=loadcachecontent(pathname,'files')
- registerfilehash(pathname,content,content==nil)
-end
-function resolvers.generators.file(specification)
- local pathname=specification.filename
- local content=scanfiles(pathname,false,true)
- registerfilehash(pathname,content,true)
-end
-resolvers.concatinators.file=file.join
-local finders=resolvers.finders
-local notfound=finders.notfound
-function finders.file(specification,filetype)
- local filename=specification.filename
- local foundname=findfile(filename,filetype)
- if foundname and foundname~="" then
- if trace_locating then
- report_files("file finder: %a found",filename)
- end
- return foundname
- else
- if trace_locating then
- report_files("file finder: %a not found",filename)
- end
- return notfound()
- end
-end
-local openers=resolvers.openers
-local notfound=openers.notfound
-local overloaded=false
-local function textopener(tag,filename,f)
- return {
- reader=function() return f:read () end,
- close=function() return f:close() end,
- }
-end
-function openers.helpers.textopener(...)
- return textopener(...)
-end
-function openers.helpers.settextopener(opener)
- if overloaded then
- report_files("file opener: %s overloaded","already")
- else
- if trace_locating then
- report_files("file opener: %s overloaded","once")
- end
- overloaded=true
- textopener=opener
- end
-end
-function openers.file(specification,filetype)
- local filename=specification.filename
- if filename and filename~="" then
- local f=ioopen(filename,"r")
- if f then
- if trace_locating then
- report_files("file opener: %a opened",filename)
- end
- return textopener("file",filename,f)
- end
- end
- if trace_locating then
- report_files("file opener: %a not found",filename)
- end
- return notfound()
-end
-local loaders=resolvers.loaders
-local notfound=loaders.notfound
-function loaders.file(specification,filetype)
- local filename=specification.filename
- if filename and filename~="" then
- local f=ioopen(filename,"rb")
- if f then
- if trace_locating then
- report_files("file loader: %a loaded",filename)
- end
- local s=f:read("*a")
- f:close()
- if s then
- return true,s,#s
- end
- end
- end
- if trace_locating then
- report_files("file loader: %a not found",filename)
- end
- return notfound()
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-con"] = package.loaded["data-con"] or true
-
--- original size: 5388, stripped down to: 3685
-
-if not modules then modules={} end modules ['data-con']={
- version=1.100,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local setmetatable=setmetatable
-local format,lower,gsub=string.format,string.lower,string.gsub
-local trace_cache=false trackers.register("resolvers.cache",function(v) trace_cache=v end)
-local trace_containers=false trackers.register("resolvers.containers",function(v) trace_containers=v end)
-local trace_storage=false trackers.register("resolvers.storage",function(v) trace_storage=v end)
-containers=containers or {}
-local containers=containers
-containers.usecache=true
-local getwritablepath=caches.getwritablepath
-local getreadablepaths=caches.getreadablepaths
-local cacheiswritable=caches.is_writable
-local loaddatafromcache=caches.loaddata
-local savedataincache=caches.savedata
-local report_containers=logs.reporter("resolvers","containers")
-local allocated={}
-local mt={
- __index=function(t,k)
- if k=="writable" then
- local writable=getwritablepath(t.category,t.subcategory) or { "." }
- t.writable=writable
- return writable
- elseif k=="readables" then
- local readables=getreadablepaths(t.category,t.subcategory) or { "." }
- t.readables=readables
- return readables
- end
- end,
- __storage__=true
-}
-function containers.define(category,subcategory,version,enabled)
- if category and subcategory then
- local c=allocated[category]
- if not c then
- c={}
- allocated[category]=c
- end
- local s=c[subcategory]
- if not s then
- s={
- category=category,
- subcategory=subcategory,
- storage={},
- enabled=enabled,
- version=version or math.pi,
- trace=false,
- }
- setmetatable(s,mt)
- c[subcategory]=s
- end
- return s
- end
-end
-function containers.is_usable(container,name)
- return container.enabled and caches and cacheiswritable(container.writable,name)
-end
-function containers.is_valid(container,name)
- if name and name~="" then
- local storage=container.storage[name]
- return storage and storage.cache_version==container.version
- else
- return false
- end
-end
-function containers.read(container,name)
- local storage=container.storage
- local stored=storage[name]
- if not stored and container.enabled and caches and containers.usecache then
- stored=loaddatafromcache(container.readables,name,container.writable)
- if stored and stored.cache_version==container.version then
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","load",container.subcategory,name)
- end
- else
- stored=nil
- end
- storage[name]=stored
- elseif stored then
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","reuse",container.subcategory,name)
- end
- end
- return stored
-end
-function containers.write(container,name,data,fast)
- if data then
- data.cache_version=container.version
- if container.enabled and caches then
- local unique=data.unique
- local shared=data.shared
- data.unique=nil
- data.shared=nil
- savedataincache(container.writable,name,data,fast)
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","save",container.subcategory,name)
- end
- data.unique=unique
- data.shared=shared
- end
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","store",container.subcategory,name)
- end
- container.storage[name]=data
- end
- return data
-end
-function containers.content(container,name)
- return container.storage[name]
-end
-function containers.cleanname(name)
- return (gsub(lower(name),"[^%w\128-\255]+","-"))
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-use"] = package.loaded["data-use"] or true
-
--- original size: 5785, stripped down to: 2905
-
-if not modules then modules={} end modules ['data-use']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local format=string.format
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_mounts=logs.reporter("resolvers","mounts")
-local resolvers=resolvers
-local findfile=resolvers.findfile
-statistics.register("used config file",function() return caches.configfiles() end)
-statistics.register("used cache path",function() return caches.usedpaths() end)
-function statistics.savefmtstatus(texname,formatbanner,sourcefile,banner)
- local enginebanner=status.banner
- if formatbanner and enginebanner and sourcefile then
- local luvname=file.replacesuffix(texname,"luv")
- local luvdata={
- enginebanner=enginebanner,
- formatbanner=formatbanner,
- sourcehash=md5.hex(io.loaddata(findfile(sourcefile)) or "unknown"),
- sourcefile=sourcefile,
- luaversion=LUAVERSION,
- formatid=LUATEXFORMATID,
- functionality=LUATEXFUNCTIONALITY,
- }
- io.savedata(luvname,table.serialize(luvdata,true))
- lua.registerfinalizer(function()
- if jit then
- logs.report("format banner","%s lua: %s jit",banner,LUAVERSION)
- else
- logs.report("format banner","%s lua: %s",banner,LUAVERSION)
- end
- logs.newline()
- end)
- end
-end
-function statistics.checkfmtstatus(texname)
- local enginebanner=status.banner
- if enginebanner and texname then
- local luvname=file.replacesuffix(texname,"luv")
- if lfs.isfile(luvname) then
- local luv=dofile(luvname)
- if luv and luv.sourcefile then
- local sourcehash=md5.hex(io.loaddata(findfile(luv.sourcefile)) or "unknown")
- local luvbanner=luv.enginebanner or "?"
- if luvbanner~=enginebanner then
- return format("engine mismatch (luv: %s <> bin: %s)",luvbanner,enginebanner)
- end
- local luvhash=luv.sourcehash or "?"
- if luvhash~=sourcehash then
- return format("source mismatch (luv: %s <> bin: %s)",luvhash,sourcehash)
- end
- local luvluaversion=luv.luaversion or 0
- local engluaversion=LUAVERSION or 0
- if luvluaversion~=engluaversion then
- return format("lua mismatch (luv: %s <> bin: %s)",luvluaversion,engluaversion)
- end
- local luvfunctionality=luv.functionality or 0
- local engfunctionality=status.development_id or 0
- if luvfunctionality~=engfunctionality then
- return format("functionality mismatch (luv: %s <> bin: %s)",luvfunctionality,engfunctionality)
- end
- local luvformatid=luv.formatid or 0
- local engformatid=status.format_id or 0
- if luvformatid~=engformatid then
- return format("formatid mismatch (luv: %s <> bin: %s)",luvformatid,engformatid)
- end
- else
- return "invalid status file"
- end
- else
- return "missing status file"
- end
- end
- return true
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-zip"] = package.loaded["data-zip"] or true
-
--- original size: 10725, stripped down to: 7949
-
-if not modules then modules={} end modules ['data-zip']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local format,find,match=string.format,string.find,string.match
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_zip=logs.reporter("resolvers","zip")
-local resolvers=resolvers
-local findfile=resolvers.findfile
-local registerfile=resolvers.registerfile
-local splitmethod=resolvers.splitmethod
-local prependhash=resolvers.prependhash
-local starttiming=resolvers.starttiming
-local extendtexmf=resolvers.extendtexmfvariable
-local stoptiming=resolvers.stoptiming
-local urlquery=url.query
-zip=zip or {}
-local zip=zip
-local archives=zip.archives or {}
-zip.archives=archives
-local registeredfiles=zip.registeredfiles or {}
-zip.registeredfiles=registeredfiles
-local zipfiles=utilities.zipfiles
-local openzip,closezip,validfile,wholefile,filehandle,traversezip
-if zipfiles then
- local ipairs=ipairs
- openzip=zipfiles.open
- closezip=zipfiles.close
- validfile=zipfiles.found
- wholefile=zipfiles.unzip
- local listzip=zipfiles.list
- traversezip=function(zfile)
- return ipairs(listzip(zfile))
- end
- local streams=utilities.streams
- local openstream=streams.open
- local readstring=streams.readstring
- local streamsize=streams.size
- local metatable={
- close=streams.close,
- read=function(stream,n)
- readstring(stream,n=="*a" and streamsize(stream) or n)
- end
- }
- filehandle=function(zfile,queryname)
- local data=wholefile(zfile,queryname)
- if data then
- local stream=openstream(data)
- if stream then
- return setmetatableindex(stream,metatable)
- end
- end
- end
-else
- openzip=zip.open
- closezip=zip.close
- validfile=function(zfile,queryname)
- local dfile=zfile:open(queryname)
- if dfile then
- dfile:close()
- return true
- end
- return false
- end
- traversezip=function(zfile)
- return z:files()
- end
- wholefile=function(zfile,queryname)
- local dfile=zfile:open(queryname)
- if dfile then
- local s=dfile:read("*all")
- dfile:close()
- return s
- end
- end
- filehandle=function(zfile,queryname)
- local dfile=zfile:open(queryname)
- if dfile then
- return dfile
- end
- end
-end
-local function validzip(str)
- if not find(str,"^zip://") then
- return "zip:///"..str
- else
- return str
- end
-end
-local function openarchive(name)
- if not name or name=="" then
- return nil
- else
- local arch=archives[name]
- if not arch then
- local full=findfile(name) or ""
- arch=full~="" and openzip(full) or false
- archives[name]=arch
- end
- return arch
- end
-end
-local function closearchive(name)
- if not name or (name=="" and archives[name]) then
- closezip(archives[name])
- archives[name]=nil
- end
-end
-zip.openarchive=openarchive
-zip.closearchive=closearchive
-function resolvers.locators.zip(specification)
- local archive=specification.filename
- local zipfile=archive and archive~="" and openarchive(archive)
- if trace_locating then
- if zipfile then
- report_zip("locator: archive %a found",archive)
- else
- report_zip("locator: archive %a not found",archive)
- end
- end
-end
-function resolvers.concatinators.zip(zipfile,path,name)
- if not path or path=="" then
- return format('%s?name=%s',zipfile,name)
- else
- return format('%s?name=%s/%s',zipfile,path,name)
- end
-end
-local finders=resolvers.finders
-local notfound=finders.notfound
-function finders.zip(specification)
- local original=specification.original
- local archive=specification.filename
- if archive then
- local query=urlquery(specification.query)
- local queryname=query.name
- if queryname then
- local zfile=openarchive(archive)
- if zfile then
- if trace_locating then
- report_zip("finder: archive %a found",archive)
- end
- if validfile(zfile,queryname) then
- if trace_locating then
- report_zip("finder: file %a found",queryname)
- end
- return specification.original
- elseif trace_locating then
- report_zip("finder: file %a not found",queryname)
- end
- elseif trace_locating then
- report_zip("finder: unknown archive %a",archive)
- end
- end
- end
- if trace_locating then
- report_zip("finder: %a not found",original)
- end
- return notfound()
-end
-local openers=resolvers.openers
-local notfound=openers.notfound
-local textopener=openers.helpers.textopener
-function openers.zip(specification)
- local original=specification.original
- local archive=specification.filename
- if archive then
- local query=urlquery(specification.query)
- local queryname=query.name
- if queryname then
- local zfile=openarchive(archive)
- if zfile then
- if trace_locating then
- report_zip("opener; archive %a opened",archive)
- end
- local handle=filehandle(zfile,queryname)
- if handle then
- if trace_locating then
- report_zip("opener: file %a found",queryname)
- end
- return textopener('zip',original,handle)
- elseif trace_locating then
- report_zip("opener: file %a not found",queryname)
- end
- elseif trace_locating then
- report_zip("opener: unknown archive %a",archive)
- end
- end
- end
- if trace_locating then
- report_zip("opener: %a not found",original)
- end
- return notfound()
-end
-local loaders=resolvers.loaders
-local notfound=loaders.notfound
-function loaders.zip(specification)
- local original=specification.original
- local archive=specification.filename
- if archive then
- local query=urlquery(specification.query)
- local queryname=query.name
- if queryname then
- local zfile=openarchive(archive)
- if zfile then
- if trace_locating then
- report_zip("loader: archive %a opened",archive)
- end
- local data=wholefile(zfile,queryname)
- if data then
- if trace_locating then
- report_zip("loader; file %a loaded",original)
- end
- return true,data,#data
- elseif trace_locating then
- report_zip("loader: file %a not found",queryname)
- end
- elseif trace_locating then
- report_zip("loader; unknown archive %a",archive)
- end
- end
- end
- if trace_locating then
- report_zip("loader: %a not found",original)
- end
- return notfound()
-end
-local function registerzipfile(z,tree)
- local names={}
- local files={}
- local remap={}
- local n=0
- local filter=tree=="" and "^(.+)/(.-)$" or format("^%s/(.+)/(.-)$",tree)
- if trace_locating then
- report_zip("registering: using filter %a",filter)
- end
- starttiming()
- for i in traversezip(z) do
- local filename=i.filename
- local path,name=match(filename,filter)
- if not path then
- n=n+1
- registerfile(names,filename,"")
- local usedname=lower(filename)
- files[usedname]=""
- if usedname~=filename then
- remap[usedname]=filename
- end
- elseif name and name~="" then
- n=n+1
- register(names,name,path)
- local usedname=lower(name)
- files[usedname]=path
- if usedname~=name then
- remap[usedname]=name
- end
- else
- end
- end
- stoptiming()
- report_zip("registering: %s files registered",n)
- return {
- files=files,
- remap=remap,
- }
-end
-local function usezipfile(archive)
- local specification=splitmethod(archive)
- local archive=specification.filename
- if archive and not registeredfiles[archive] then
- local z=openarchive(archive)
- if z then
- local tree=urlquery(specification.query).tree or ""
- if trace_locating then
- report_zip("registering: archive %a",archive)
- end
- prependhash('zip',archive)
- extendtexmf(archive)
- registeredfiles[archive]=z
- registerfilehash(archive,registerzipfile(z,tree))
- elseif trace_locating then
- report_zip("registering: unknown archive %a",archive)
- end
- elseif trace_locating then
- report_zip("registering: archive %a not found",archive)
- end
-end
-resolvers.usezipfile=usezipfile
-resolvers.registerzipfile=registerzipfile
-function resolvers.hashers.zip(specification)
- local archive=specification.filename
- if trace_locating then
- report_zip("loading file %a",archive)
- end
- usezipfile(specification.original)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-tre"] = package.loaded["data-tre"] or true
-
--- original size: 10802, stripped down to: 6619
-
-if not modules then modules={} end modules ['data-tre']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type=type
-local find,gsub,lower=string.find,string.gsub,string.lower
-local basename,dirname,joinname=file.basename,file.dirname,file.join
-local globdir,isdir,isfile=dir.glob,lfs.isdir,lfs.isfile
-local P,lpegmatch=lpeg.P,lpeg.match
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_trees=logs.reporter("resolvers","trees")
-local resolvers=resolvers
-local finders=resolvers.finders
-local openers=resolvers.openers
-local loaders=resolvers.loaders
-local locators=resolvers.locators
-local hashers=resolvers.hashers
-local generators=resolvers.generators
-do
- local collectors={}
- local found={}
- local notfound=finders.notfound
- function finders.tree(specification)
- local spec=specification.filename
- local okay=found[spec]
- if okay==nil then
- if spec~="" then
- local path=dirname(spec)
- local name=basename(spec)
- if path=="" then
- path="."
- end
- local names=collectors[path]
- if not names then
- local pattern=find(path,"/%*+$") and path or (path.."/*")
- names=globdir(pattern)
- collectors[path]=names
- end
- local pattern="/"..gsub(name,"([%.%-%+])","%%%1").."$"
- for i=1,#names do
- local fullname=names[i]
- if find(fullname,pattern) then
- found[spec]=fullname
- return fullname
- end
- end
- local pattern=lower(pattern)
- for i=1,#names do
- local fullname=lower(names[i])
- if find(fullname,pattern) then
- if isfile(fullname) then
- found[spec]=fullname
- return fullname
- else
- break
- end
- end
- end
- end
- okay=notfound()
- found[spec]=okay
- end
- return okay
- end
-end
-do
- local resolveprefix=resolvers.resolve
- local appendhash=resolvers.appendhash
- local function dolocate(specification)
- local name=specification.filename
- local realname=resolveprefix(name)
- if realname and realname~='' and isdir(realname) then
- if trace_locating then
- report_trees("locator %a found",realname)
- end
- appendhash('tree',name,false)
- elseif trace_locating then
- report_trees("locator %a not found",name)
- end
- end
- locators.tree=dolocate
- locators.dirlist=dolocate
- locators.dirfile=dolocate
-end
-do
- local filegenerator=generators.file
- generators.dirlist=filegenerator
- generators.dirfile=filegenerator
-end
-do
- local filegenerator=generators.file
- local methodhandler=resolvers.methodhandler
- local function dohash(specification)
- local name=specification.filename
- if trace_locating then
- report_trees("analyzing %a",name)
- end
- methodhandler("hashers",name)
- filegenerator(specification)
- end
- hashers.tree=dohash
- hashers.dirlist=dohash
- hashers.dirfile=dohash
-end
-local resolve do
- local collectors={}
- local splitter=lpeg.splitat("/**/")
- local stripper=lpeg.replacer { [P("/")*P("*")^1*P(-1)]="" }
- local loadcontent=caches.loadcontent
- local savecontent=caches.savecontent
- local notfound=finders.notfound
- local scanfiles=resolvers.scanfiles
- local lookup=resolvers.get_from_content
- table.setmetatableindex(collectors,function(t,k)
- local rootname=lpegmatch(stripper,k)
- local dataname=joinname(rootname,"dirlist")
- local content=loadcontent(dataname,"files",dataname)
- if not content then
- content=scanfiles(rootname,nil,nil,false,true)
- savecontent(dataname,"files",content,dataname)
- end
- t[k]=content
- return content
- end)
- local function checked(root,p,n)
- if p then
- if type(p)=="table" then
- for i=1,#p do
- local fullname=joinname(root,p[i],n)
- if isfile(fullname) then
- return fullname
- end
- end
- else
- local fullname=joinname(root,p,n)
- if isfile(fullname) then
- return fullname
- end
- end
- end
- return notfound()
- end
- resolve=function(specification)
- local filename=specification.filename
- if filename~="" then
- local root,rest=lpegmatch(splitter,filename)
- if root and rest then
- local path,name=dirname(rest),basename(rest)
- if name~=rest then
- local content=collectors[root]
- local p,n=lookup(content,name)
- if not p then
- return notfound()
- end
- local pattern=".*/"..path.."$"
- local istable=type(p)=="table"
- if istable then
- for i=1,#p do
- local pi=p[i]
- if pi==path or find(pi,pattern) then
- local fullname=joinname(root,pi,n)
- if isfile(fullname) then
- return fullname
- end
- end
- end
- elseif p==path or find(p,pattern) then
- local fullname=joinname(root,p,n)
- if isfile(fullname) then
- return fullname
- end
- end
- local queries=specification.queries
- if queries and queries.option=="fileonly" then
- return checked(root,p,n)
- else
- return notfound()
- end
- end
- end
- local path=dirname(filename)
- local name=basename(filename)
- local root=lpegmatch(stripper,path)
- local content=collectors[path]
- local p,n=lookup(content,name)
- if p then
- return checked(root,p,n)
- end
- end
- return notfound()
- end
- finders.dirlist=resolve
- function finders.dirfile(specification)
- local queries=specification.queries
- if queries then
- queries.option="fileonly"
- else
- specification.queries={ option="fileonly" }
- end
- return resolve(specification)
- end
-end
-do
- local fileopener=openers.file
- local fileloader=loaders.file
- openers.dirlist=fileopener
- loaders.dirlist=fileloader
- openers.dirfile=fileopener
- loaders.dirfile=fileloader
-end
-do
- local hashfile="dirhash.lua"
- local kind="HASH256"
- local version=1.0
- local loadtable=table.load
- local savetable=table.save
- local loaddata=io.loaddata
- function resolvers.dirstatus(patterns)
- local t=type(patterns)
- if t=="string" then
- patterns={ patterns }
- elseif t~="table" then
- return false
- end
- local status=loadtable(hashfile)
- if not status or status.version~=version or status.kind~=kind then
- status={
- version=1.0,
- kind=kind,
- hashes={},
- }
- end
- local hashes=status.hashes
- local changed={}
- local action=sha2[kind]
- local update={}
- for i=1,#patterns do
- local pattern=patterns[i]
- local files=globdir(pattern)
- for i=1,#files do
- local name=files[i]
- local hash=action(loaddata(name))
- if hashes[name]~=hash then
- changed[#changed+1]=name
- end
- update[name]=hash
- end
- end
- status.hashes=update
- savetable(hashfile,status)
- return #changed>0 and changed or false
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-sch"] = package.loaded["data-sch"] or true
-
--- original size: 6945, stripped down to: 5408
-
-if not modules then modules={} end modules ['data-sch']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local load,tonumber=load,tonumber
-local gsub,format=string.gsub,string.format
-local sortedhash,concat=table.sortedhash,table.concat
-local finders,openers,loaders=resolvers.finders,resolvers.openers,resolvers.loaders
-local addsuffix,suffix,splitbase=file.addsuffix,file.suffix,file.splitbase
-local md5hex=md5.hex
-local trace_schemes=false trackers.register("resolvers.schemes",function(v) trace_schemes=v end)
-local report_schemes=logs.reporter("resolvers","schemes")
-local http=require("socket.http")
-local ltn12=require("ltn12")
-if mbox then mbox=nil end
-local resolvers=resolvers
-local schemes=resolvers.schemes or {}
-resolvers.schemes=schemes
-local cleaners={}
-schemes.cleaners=cleaners
-local threshold=24*60*60
-directives.register("schemes.threshold",function(v) threshold=tonumber(v) or threshold end)
-function cleaners.none(specification)
- return specification.original
-end
-function cleaners.strip(specification)
- local path,name=splitbase(specification.original)
- if path=="" then
- return (gsub(name,"[^%a%d%.]+","-"))
- else
- return (gsub((gsub(path,"%.","-").."-"..name),"[^%a%d%.]+","-"))
- end
-end
-function cleaners.md5(specification)
- return addsuffix(md5hex(specification.original),suffix(specification.path))
-end
-local cleaner=cleaners.strip
-directives.register("schemes.cleanmethod",function(v) cleaner=cleaners[v] or cleaners.strip end)
-function resolvers.schemes.cleanname(specification)
- local hash=cleaner(specification)
- if trace_schemes then
- report_schemes("hashing %a to %a",specification.original,hash)
- end
- return hash
-end
-local cached={}
-local loaded={}
-local reused={}
-local thresholds={}
-local handlers={}
-local runner=sandbox.registerrunner {
- name="curl resolver",
- method="execute",
- program="curl",
- template='--silent --insecure --create-dirs --output "%cachename%" "%original%"',
- checkers={
- cachename="cache",
- original="url",
- }
-}
-local function fetch(specification)
- local original=specification.original
- local scheme=specification.scheme
- local cleanname=schemes.cleanname(specification)
- local cachename=caches.setfirstwritablefile(cleanname,"schemes")
- if not cached[original] then
- statistics.starttiming(schemes)
- if not io.exists(cachename) or (os.difftime(os.time(),lfs.attributes(cachename).modification)>(thresholds[protocol] or threshold)) then
- cached[original]=cachename
- local handler=handlers[scheme]
- if handler then
- if trace_schemes then
- report_schemes("fetching %a, protocol %a, method %a",original,scheme,"built-in")
- end
- logs.flush()
- handler(specification,cachename)
- else
- if trace_schemes then
- report_schemes("fetching %a, protocol %a, method %a",original,scheme,"curl")
- end
- logs.flush()
- runner {
- original=original,
- cachename=cachename,
- }
- end
- end
- if io.exists(cachename) then
- cached[original]=cachename
- if trace_schemes then
- report_schemes("using cached %a, protocol %a, cachename %a",original,scheme,cachename)
- end
- else
- cached[original]=""
- if trace_schemes then
- report_schemes("using missing %a, protocol %a",original,scheme)
- end
- end
- loaded[scheme]=loaded[scheme]+1
- statistics.stoptiming(schemes)
- else
- if trace_schemes then
- report_schemes("reusing %a, protocol %a",original,scheme)
- end
- reused[scheme]=reused[scheme]+1
- end
- return cached[original]
-end
-local function finder(specification,filetype)
- return resolvers.methodhandler("finders",fetch(specification),filetype)
-end
-local opener=openers.file
-local loader=loaders.file
-local function install(scheme,handler,newthreshold)
- handlers [scheme]=handler
- loaded [scheme]=0
- reused [scheme]=0
- finders [scheme]=finder
- openers [scheme]=opener
- loaders [scheme]=loader
- thresholds[scheme]=newthreshold or threshold
-end
-schemes.install=install
-local function http_handler(specification,cachename)
- local tempname=cachename..".tmp"
- local handle=io.open(tempname,"wb")
- local status,message=http.request {
- url=specification.original,
- sink=ltn12.sink.file(handle)
- }
- if not status then
- os.remove(tempname)
- else
- os.remove(cachename)
- os.rename(tempname,cachename)
- end
- return cachename
-end
-install('http',http_handler)
-install('https')
-install('ftp')
-statistics.register("scheme handling time",function()
- local l,r,nl,nr={},{},0,0
- for k,v in sortedhash(loaded) do
- if v>0 then
- nl=nl+1
- l[nl]=k..":"..v
- end
- end
- for k,v in sortedhash(reused) do
- if v>0 then
- nr=nr+1
- r[nr]=k..":"..v
- end
- end
- local n=nl+nr
- if n>0 then
- if nl==0 then l={ "none" } end
- if nr==0 then r={ "none" } end
- return format("%s seconds, %s processed, threshold %s seconds, loaded: %s, reused: %s",
- statistics.elapsedtime(schemes),n,threshold,concat(l," "),concat(l," "))
- else
- return nil
- end
-end)
-local httprequest=http.request
-local toquery=url.toquery
-local function fetchstring(url,data)
- local q=data and toquery(data)
- if q then
- url=url.."?"..q
- end
- local reply=httprequest(url)
- return reply
-end
-schemes.fetchstring=fetchstring
-function schemes.fetchtable(url,data)
- local reply=fetchstring(url,data)
- if reply then
- local s=load("return "..reply)
- if s then
- return s()
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-lua"] = package.loaded["data-lua"] or true
-
--- original size: 4227, stripped down to: 3049
-
-if not modules then modules={} end modules ['data-lua']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local package,lpeg=package,lpeg
-local loadfile=loadfile
-local addsuffix=file.addsuffix
-local P,S,Cs,lpegmatch=lpeg.P,lpeg.S,lpeg.Cs,lpeg.match
-local luasuffixes={ 'tex','lua' }
-local libsuffixes={ 'lib' }
-local luaformats={ 'TEXINPUTS','LUAINPUTS' }
-local libformats={ 'CLUAINPUTS' }
-local helpers=package.helpers or {}
-local methods=helpers.methods or {}
-local resolvers=resolvers
-local resolveprefix=resolvers.resolve
-local expandedpaths=resolvers.expandedpathlistfromvariable
-local findfile=resolvers.findfile
-helpers.report=logs.reporter("resolvers","libraries")
-trackers.register("resolvers.libraries",function(v) helpers.trace=v end)
-trackers.register("resolvers.locating",function(v) helpers.trace=v end)
-helpers.sequence={
- "already loaded",
- "preload table",
- "lua variable format",
- "lib variable format",
- "lua extra list",
- "lib extra list",
- "path specification",
- "cpath specification",
- "all in one fallback",
- "not loaded",
-}
-local pattern=Cs(P("!")^0/""*(P("/")*P(-1)/"/"+P("/")^1/"/"+1)^0)
-function helpers.cleanpath(path)
- return resolveprefix(lpegmatch(pattern,path))
-end
-local loadedaslib=helpers.loadedaslib
-local registerpath=helpers.registerpath
-local lualibfile=helpers.lualibfile
-local luaformatpaths
-local libformatpaths
-local function getluaformatpaths()
- if not luaformatpaths then
- luaformatpaths={}
- for i=1,#luaformats do
- registerpath("lua format","lua",luaformatpaths,expandedpaths(luaformats[i]))
- end
- end
- return luaformatpaths
-end
-local function getlibformatpaths()
- if not libformatpaths then
- libformatpaths={}
- for i=1,#libformats do
- registerpath("lib format","lib",libformatpaths,expandedpaths(libformats[i]))
- end
- end
- return libformatpaths
-end
-local function loadedbyformat(name,rawname,suffixes,islib,what)
- local trace=helpers.trace
- local report=helpers.report
- for i=1,#suffixes do
- local format=suffixes[i]
- local resolved=findfile(name,format) or ""
- if trace then
- report("%s format, identifying %a using format %a",what,name,format)
- end
- if resolved~="" then
- if trace then
- report("%s format, %a found on %a",what,name,resolved)
- end
- if islib then
- return loadedaslib(resolved,rawname)
- else
- return loadfile(resolved)
- end
- end
- end
-end
-helpers.loadedbyformat=loadedbyformat
-methods["lua variable format"]=function(name)
- if helpers.trace then
- helpers.report("%s format, checking %s paths","lua",#getluaformatpaths())
- end
- return loadedbyformat(addsuffix(lualibfile(name),"lua"),name,luasuffixes,false,"lua")
-end
-methods["lib variable format"]=function(name)
- if helpers.trace then
- helpers.report("%s format, checking %s paths","lib",#getlibformatpaths())
- end
- return loadedbyformat(addsuffix(lualibfile(name),os.libsuffix),name,libsuffixes,true,"lib")
-end
-resolvers.loadlualib=require
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-aux"] = package.loaded["data-aux"] or true
-
--- original size: 2610, stripped down to: 2019
-
-if not modules then modules={} end modules ['data-aux']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local find=string.find
-local type,next=type,next
-local addsuffix,removesuffix=file.addsuffix,file.removesuffix
-local loaddata,savedata=io.loaddata,io.savedata
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local resolvers=resolvers
-local cleanpath=resolvers.cleanpath
-local findfiles=resolvers.findfiles
-local report_scripts=logs.reporter("resolvers","scripts")
-function resolvers.updatescript(oldname,newname)
- local scriptpath="context/lua"
- local oldscript=cleanpath(oldname)
- local newname=addsuffix(newname,"lua")
- local newscripts=findfiles(newname) or {}
- if trace_locating then
- report_scripts("to be replaced old script %a",oldscript)
- end
- if #newscripts==0 then
- if trace_locating then
- report_scripts("unable to locate new script")
- end
- else
- for i=1,#newscripts do
- local newscript=cleanpath(newscripts[i])
- if trace_locating then
- report_scripts("checking new script %a",newscript)
- end
- if oldscript==newscript then
- if trace_locating then
- report_scripts("old and new script are the same")
- end
- elseif not find(newscript,scriptpath,1,true) then
- if trace_locating then
- report_scripts("new script should come from %a",scriptpath)
- end
- elseif not (find(oldscript,removesuffix(newname).."$") or find(oldscript,newname.."$")) then
- if trace_locating then
- report_scripts("invalid new script name")
- end
- else
- local newdata=loaddata(newscript)
- if newdata then
- if trace_locating then
- report_scripts("old script content replaced by new content: %s",oldscript)
- end
- savedata(oldscript,newdata)
- break
- elseif trace_locating then
- report_scripts("unable to load new script")
- end
- end
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-tmf"] = package.loaded["data-tmf"] or true
-
--- original size: 2601, stripped down to: 1549
-
-if not modules then modules={} end modules ['data-tmf']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local resolvers=resolvers
-local report_tds=logs.reporter("resolvers","tds")
-function resolvers.load_tree(tree,resolve)
- if type(tree)=="string" and tree~="" then
- local getenv,setenv=resolvers.getenv,resolvers.setenv
- local texos="texmf-"..os.platform
- local oldroot=environment.texroot
- local newroot=file.collapsepath(tree)
- local newtree=file.join(newroot,texos)
- local newpath=file.join(newtree,"bin")
- if not lfs.isdir(newtree) then
- report_tds("no %a under tree %a",texos,tree)
- os.exit()
- end
- if not lfs.isdir(newpath) then
- report_tds("no '%s/bin' under tree %a",texos,tree)
- os.exit()
- end
- local texmfos=newtree
- environment.texroot=newroot
- environment.texos=texos
- environment.texmfos=texmfos
- if resolve then
- resolvers.luacnfspec=resolvers.resolve(resolvers.luacnfspec)
- end
- setenv('SELFAUTOPARENT',newroot)
- setenv('SELFAUTODIR',newtree)
- setenv('SELFAUTOLOC',newpath)
- setenv('TEXROOT',newroot)
- setenv('TEXOS',texos)
- setenv('TEXMFOS',texmfos)
- setenv('TEXMFCNF',resolvers.luacnfspec,true)
- setenv('PATH',newpath..io.pathseparator..getenv('PATH'))
- report_tds("changing from root %a to %a",oldroot,newroot)
- report_tds("prepending %a to PATH",newpath)
- report_tds("setting TEXMFCNF to %a",resolvers.luacnfspec)
- report_tds()
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-lst"] = package.loaded["data-lst"] or true
-
--- original size: 2038, stripped down to: 1696
-
-if not modules then modules={} end modules ['data-lst']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type=type
-local sortedhash=table.sortedhash
-local isdir=lfs.isdir
-local resolvers=resolvers
-local listers=resolvers.listers or {}
-resolvers.listers=listers
-local resolveprefix=resolvers.resolve
-local configurationfiles=resolvers.configurationfiles
-local expandedpathfromlist=resolvers.expandedpathfromlist
-local splitpath=resolvers.splitpath
-local knownvariables=resolvers.knownvariables
-local report_lists=logs.reporter("resolvers","lists")
-local report_resolved=logs.reporter("system","resolved")
-local function tabstr(str)
- if not str then
- return "unset"
- elseif type(str)=='table' then
- return concat(str," | ")
- else
- return str
- end
-end
-function listers.variables(pattern)
- local result=resolvers.knownvariables(pattern)
- for key,value in sortedhash(result) do
- report_lists(key)
- report_lists(" env: %s",tabstr(value.environment))
- report_lists(" var: %s",tabstr(value.variable))
- report_lists(" exp: %s",tabstr(value.expansion))
- report_lists(" res: %s",tabstr(value.resolved))
- end
-end
-function listers.configurations()
- local configurations=configurationfiles()
- for i=1,#configurations do
- report_resolved("file : %s",resolveprefix(configurations[i]))
- end
- report_resolved("")
- local list=expandedpathfromlist(splitpath(resolvers.luacnfspec))
- for i=1,#list do
- local li=resolveprefix(list[i])
- if isdir(li) then
- report_resolved("path - %s",li)
- else
- report_resolved("path + %s",li)
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["libs-ini"] = package.loaded["libs-ini"] or true
-
--- original size: 6459, stripped down to: 4006
-
-if not modules then modules={} end modules ['libs-ini']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,unpack=type,unpack
-local find=string.find
-local nameonly=file.nameonly
-local joinfile=file.join
-local addsuffix=file.addsuffix
-local qualifiedpath=file.is_qualified_path
-local isfile=lfs.isfile
-local findfile=resolvers.findfile
-local expandpaths=resolvers.expandedpathlistfromvariable
-local report=logs.reporter("resolvers","libraries")
-local trace=false
-local silent=false
-trackers.register("resolvers.lib",function(v) trace=v end)
-trackers.register("resolvers.lib.silent",function(v) silent=v end)
-local function findlib(required)
- local suffix=os.libsuffix or "so"
- if not qualifiedpath(required) then
- local list=directives.value("system.librarynames" )
- local only=nameonly(required)
- if type(list)=="table" then
- list=list[only]
- if type(list)~="table" then
- list={ only }
- end
- else
- list={ only }
- end
- if trace then
- report("using lookup list for library %a: % | t",only,list)
- end
- for i=1,#list do
- local name=list[i]
- local found=findfile(name,"lib")
- if not found then
- found=findfile(addsuffix(name,suffix),"lib")
- end
- if found then
- if trace then
- report("library %a resolved via %a path to %a",name,"tds lib",found)
- end
- return found
- end
- end
- if expandpaths then
- local list=expandpaths("PATH")
- local base=addsuffix(only,suffix)
- for i=1,#list do
- local full=joinfile(list[i],base)
- local found=isfile(full) and full
- if found then
- if trace then
- report("library %a resolved via %a path to %a",name,"system",found)
- end
- return found
- end
- end
- end
- elseif isfile(addsuffix(required,suffix)) then
- if trace then
- report("library with qualified name %a %sfound",required,"")
- end
- return required
- else
- if trace then
- report("library with qualified name %a %sfound",required,"not ")
- end
- end
- return false
-end
-local foundlibraries=table.setmetatableindex(function(t,k)
- local v=findlib(k)
- t[k]=v
- return v
-end)
-function resolvers.findlib(required)
- return foundlibraries[required]
-end
-local libraries={}
-resolvers.libraries=libraries
-local report=logs.reporter("optional")
-if optional then optional.loaded={} end
-function libraries.validoptional(name)
- local thelib=optional and optional[name]
- if not thelib then
- elseif thelib.initialize then
- return thelib
- else
- report("invalid optional library %a",libname)
- end
-end
-function libraries.optionalloaded(name,libnames)
- local thelib=optional and optional[name]
- if not thelib then
- report("no optional %a library found",name)
- else
- local thelib_initialize=thelib.initialize
- if not thelib_initialize then
- report("invalid optional library %a",name)
- else
- if type(libnames)=="string" then
- libnames={ libnames }
- end
- if type(libnames)=="table" then
- for i=1,#libnames do
- local libname=libnames[i]
- local filename=foundlibraries[libname]
- if filename then
- libnames[i]=filename
- else
- report("unable to locate library %a",libname)
- return
- end
- end
- local initialized=thelib_initialize(unpack(libnames))
- if not initialized then
- report("unable to initialize library '% + t'",libnames)
- elseif not silent then
- report("using library '% + t'",libnames)
- end
- return initialized
- end
- end
- end
-end
-if FFISUPPORTED and ffi and ffi.load then
- local ffiload=ffi.load
- function ffi.load(name)
- local full=name and foundlibraries[name]
- if full then
- return ffiload(full)
- else
- return ffiload(name)
- end
- end
-end
-local dofile=dofile
-local savedrequire=require
-function require(name,version)
- if find(name,"%.lua$") or find(name,"%.lmt$") then
- local m=dofile(findfile(name))
- if m then
- package.loaded[name]=m
- return m
- end
- else
- return savedrequire(name)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["luat-sta"] = package.loaded["luat-sta"] or true
-
--- original size: 5703, stripped down to: 2321
-
-if not modules then modules={} end modules ['luat-sta']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local gmatch,match=string.gmatch,string.match
-local type=type
-states=states or {}
-local states=states
-states.data=states.data or {}
-local data=states.data
-states.hash=states.hash or {}
-local hash=states.hash
-states.tag=states.tag or ""
-states.filename=states.filename or ""
-function states.save(filename,tag)
- tag=tag or states.tag
- filename=file.addsuffix(filename or states.filename,'lus')
- io.savedata(filename,
- "-- generator : luat-sta.lua\n".."-- state tag : "..tag.."\n\n"..table.serialize(data[tag or states.tag] or {},true)
- )
-end
-function states.load(filename,tag)
- states.filename=filename
- states.tag=tag or "whatever"
- states.filename=file.addsuffix(states.filename,'lus')
- data[states.tag],hash[states.tag]=(io.exists(filename) and dofile(filename)) or {},{}
-end
-local function set_by_tag(tag,key,value,default,persistent)
- local d,h=data[tag],hash[tag]
- if d then
- if type(d)=="table" then
- local dkey,hkey=key,key
- local pre,post=match(key,"(.+)%.([^%.]+)$")
- if pre and post then
- for k in gmatch(pre,"[^%.]+") do
- local dk=d[k]
- if not dk then
- dk={}
- d[k]=dk
- elseif type(dk)=="string" then
- break
- end
- d=dk
- end
- dkey,hkey=post,key
- end
- if value==nil then
- value=default
- elseif value==false then
- elseif persistent then
- value=value or d[dkey] or default
- else
- value=value or default
- end
- d[dkey],h[hkey]=value,value
- elseif type(d)=="string" then
- data[tag],hash[tag]=value,value
- end
- end
-end
-local function get_by_tag(tag,key,default)
- local h=hash[tag]
- if h and h[key] then
- return h[key]
- else
- local d=data[tag]
- if d then
- for k in gmatch(key,"[^%.]+") do
- local dk=d[k]
- if dk~=nil then
- d=dk
- else
- return default
- end
- end
- if d==false then
- return false
- else
- return d or default
- end
- end
- end
-end
-states.set_by_tag=set_by_tag
-states.get_by_tag=get_by_tag
-function states.set(key,value,default,persistent)
- set_by_tag(states.tag,key,value,default,persistent)
-end
-function states.get(key,default)
- return get_by_tag(states.tag,key,default)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["luat-fmt"] = package.loaded["luat-fmt"] or true
-
--- original size: 11691, stripped down to: 8350
-
-if not modules then modules={} end modules ['luat-fmt']={
- version=1.001,
- comment="companion to mtxrun",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local format=string.format
-local concat=table.concat
-local quoted=string.quoted
-local luasuffixes=utilities.lua.suffixes
-local report_format=logs.reporter("resolvers","formats")
-local function primaryflags(arguments)
- local flags={}
- if arguments.silent then
- flags[#flags+1]="--interaction=batchmode"
- end
- return concat(flags," ")
-end
-local function secondaryflags(arguments)
- local trackers=arguments.trackers
- local directives=arguments.directives
- local flags={}
- if trackers and trackers~="" then
- flags[#flags+1]="--c:trackers="..quoted(trackers)
- end
- if directives and directives~="" then
- flags[#flags+1]="--c:directives="..quoted(directives)
- end
- if arguments.silent then
- flags[#flags+1]="--c:silent"
- end
- if arguments.errors then
- flags[#flags+1]="--c:errors"
- end
- if arguments.ansi then
- flags[#flags+1]="--c:ansi"
- end
- if arguments.ansilog then
- flags[#flags+1]="--c:ansilog"
- end
- if arguments.strip then
- flags[#flags+1]="--c:strip"
- end
- if arguments.lmtx then
- flags[#flags+1]="--c:lmtx"
- end
- return concat(flags," ")
-end
-local template=[[--ini %primaryflags% --lua=%luafile% %texfile% %secondaryflags% %redirect%]]
-local checkers={
- primaryflags="verbose",
- secondaryflags="verbose",
- luafile="readable",
- texfile="readable",
- redirect="string",
- binarypath="string",
-}
-local runners={
- luametatex=sandbox.registerrunner {
- name="make luametatex format",
- program="luametatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luatex=sandbox.registerrunner {
- name="make luatex format",
- program="luatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luajittex=sandbox.registerrunner {
- name="make luajittex format",
- program="luajittex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
-}
-local stubfiles={
- luametatex="luat-cod.lmt",
- luatex="luat-cod.lua",
- luajittex="luat-cod.lua",
-}
-local suffixes={
- luametatex="mkxl",
- luatex="mkiv",
- luajittex="mkiv",
-}
-local function validbinarypath()
- if not environment.arguments.nobinarypath then
- local path=environment.ownpath or file.dirname(environment.ownname)
- if path and path~="" then
- path=dir.expandname(path)
- if path~="" and lfs.isdir(path) then
- return path
- end
- end
- end
-end
-local function fatalerror(startupdir,...)
- report_format(...)
- lfs.chdir(startupdir)
-end
-function environment.make_format(formatname)
- local arguments=environment.arguments
- local engine=environment.ownmain or "luatex"
- local silent=arguments.silent
- local errors=arguments.errors
- local runner=runners[engine]
- local startupdir=dir.current()
- if not runner then
- return fatalerror(startupdir,"the format %a cannot be generated, no runner available for engine %a",name,engine)
- end
- local luasourcename=stubfiles[engine]
- if not luasourcename then
- return fatalerror(startupdir,"no lua stub file specified for %a",engine)
- end
- local texsourcename=file.addsuffix(formatname,suffixes[engine])
- local fulltexsourcename=resolvers.findfile(texsourcename,"tex") or ""
- if fulltexsourcename=="" then
- return fatalerror(startupdir,"no tex source file with name %a (mkiv or tex)",formatname)
- end
- local fulltexsourcename=dir.expandname(fulltexsourcename)
- local texsourcepath=file.dirname(fulltexsourcename)
- if lfs.isfile(fulltexsourcename) then
- report_format("using tex source file %a",fulltexsourcename)
- else
- return fatalerror(startupdir,"no accessible tex source file with name %a",fulltexsourcename)
- end
- local fullluasourcename=dir.expandname(file.join(texsourcepath,luasourcename) or "")
- if lfs.isfile(fullluasourcename) then
- report_format("using lua stub file %a",fullluasourcename)
- else
- return fatalerror(startupdir,"no accessible lua stub file with name %a",fulltexsourcename)
- end
- local validformatpath=caches.getwritablepath("formats",engine) or ""
- if validformatpath=="" then
- return fatalerror(startupdir,"invalid format path, insufficient write access")
- end
- local binarypath=validbinarypath()
- report_format("changing to format path %a",validformatpath)
- if not lfs.chdir(validformatpath) then
- return fatalerror(startupdir,"unable to change to format path %a",validformatpath)
- end
- local primaryflags=primaryflags(arguments)
- local secondaryflags=secondaryflags(arguments)
- local specification={
- binarypath=binarypath,
- primaryflags=primaryflags,
- secondaryflags=secondaryflags,
- luafile=quoted(fullluasourcename),
- texfile=quoted(fulltexsourcename),
- }
- if silent then
- specification.redirect="> temp.log"
- end
- statistics.starttiming("format")
- local result=runner(specification)
- statistics.stoptiming("format")
- if silent then
- os.remove("temp.log")
- end
- report_format()
- if binarypath and binarypath~="" then
- report_format("binary path : %s",binarypath or "?")
- end
- report_format("format path : %s",validformatpath)
- report_format("luatex engine : %s",engine)
- report_format("lua startup file : %s",fullluasourcename)
- if primaryflags~="" then
- report_format("primary flags : %s",primaryflags)
- end
- if secondaryflags~="" then
- report_format("secondary flags : %s",secondaryflags)
- end
- report_format("context file : %s",fulltexsourcename)
- report_format("run time : %.3f seconds",statistics.elapsed("format"))
- report_format("return value : %s",result==0 and "okay" or "error")
- report_format()
- lfs.chdir(startupdir)
-end
-local template=[[%primaryflags% --fmt=%fmtfile% --lua=%luafile% %texfile% %secondaryflags%]]
-local checkers={
- primaryflags="verbose",
- secondaryflags="verbose",
- fmtfile="readable",
- luafile="readable",
- texfile="readable",
-}
-local runners={
- luatex=sandbox.registerrunner {
- name="run luatex format",
- program="luatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luametatex=sandbox.registerrunner {
- name="run luametatex format",
- program="luametatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luajittex=sandbox.registerrunner {
- name="run luajittex format",
- program="luajittex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
-}
-function environment.run_format(formatname,scriptname,filename,primaryflags,secondaryflags,verbose)
- local engine=environment.ownmain or "luatex"
- if not formatname or formatname=="" then
- report_format("missing format name")
- return
- end
- if not scriptname or scriptname=="" then
- report_format("missing script name")
- return
- end
- if not lfs.isfile(formatname) or not lfs.isfile(scriptname) then
- formatname,scriptname=resolvers.locateformat(formatname)
- end
- if not formatname or formatname=="" then
- report_format("invalid format name")
- return
- end
- if not scriptname or scriptname=="" then
- report_format("invalid script name")
- return
- end
- local runner=runners[engine]
- if not runner then
- report_format("format %a cannot be run, no runner available for engine %a",file.nameonly(name),engine)
- return
- end
- if not filename then
- filename ""
- end
- local binarypath=validbinarypath()
- local specification={
- binarypath=binarypath,
- primaryflags=primaryflags or "",
- secondaryflags=secondaryflags or "",
- fmtfile=quoted(formatname),
- luafile=quoted(scriptname),
- texfile=filename~="" and quoted(filename) or "",
- }
- statistics.starttiming("make format")
- local result=runner(specification)
- statistics.stoptiming("make format")
- if verbose then
- report_format()
- if binarypath and binarypath~="" then
- report_format("binary path : %s",binarypath)
- end
- report_format("luatex engine : %s",engine)
- report_format("lua startup file : %s",scriptname)
- report_format("tex format file : %s",formatname)
- if filename~="" then
- report_format("tex input file : %s",filename)
- end
- if primaryflags~="" then
- report_format("primary flags : %s",primaryflags)
- end
- if secondaryflags~="" then
- report_format("secondary flags : %s",secondaryflags)
- end
- report_format("run time : %0.3f seconds",statistics.elapsed("make format"))
- report_format("return value : %s",result==0 and "okay" or "error")
- report_format()
- end
- return result
-end
-
-
-end -- of closure
-
--- used libraries : l-bit32.lua l-lua.lua l-macro.lua l-sandbox.lua l-package.lua l-lpeg.lua l-function.lua l-string.lua l-table.lua l-io.lua l-number.lua l-set.lua l-os.lua l-file.lua l-gzip.lua l-md5.lua l-sha.lua l-url.lua l-dir.lua l-boolean.lua l-unicode.lua l-math.lua util-str.lua util-tab.lua util-fil.lua util-sac.lua util-sto.lua util-prs.lua util-fmt.lua util-soc-imp-reset.lua util-soc-imp-socket.lua util-soc-imp-copas.lua util-soc-imp-ltn12.lua util-soc-imp-mime.lua util-soc-imp-url.lua util-soc-imp-headers.lua util-soc-imp-tp.lua util-soc-imp-http.lua util-soc-imp-ftp.lua util-soc-imp-smtp.lua trac-set.lua trac-log.lua trac-inf.lua trac-pro.lua util-lua.lua util-deb.lua util-tpl.lua util-sbx.lua util-mrg.lua util-env.lua luat-env.lua util-zip.lua lxml-tab.lua lxml-lpt.lua lxml-mis.lua lxml-aux.lua lxml-xml.lua trac-xml.lua data-ini.lua data-exp.lua data-env.lua data-tmp.lua data-met.lua data-res.lua data-pre.lua data-inp.lua data-out.lua data-fil.lua data-con.lua data-use.lua data-zip.lua data-tre.lua data-sch.lua data-lua.lua data-aux.lua data-tmf.lua data-lst.lua libs-ini.lua luat-sta.lua luat-fmt.lua
--- skipped libraries : -
--- original bytes : 1025947
--- stripped bytes : 405652
-
--- end library merge
-
--- We need this hack till luatex is fixed.
---
--- for k,v in pairs(arg) do print(k,v) end
-
-if arg and (arg[0] == 'luatex' or arg[0] == 'luatex.exe') and arg[1] == "--luaonly" then
- arg[-1]=arg[0] arg[0]=arg[2] for k=3,#arg do arg[k-2]=arg[k] end arg[#arg]=nil arg[#arg]=nil
-end
-
--- End of hack.
-
-local format, gsub, gmatch, match, find = string.format, string.gsub, string.gmatch, string.match, string.find
-local concat = table.concat
-
-local ownname = environment and environment.ownname or arg[0] or 'mtxrun.lua'
-local ownpath = gsub(match(ownname,"^(.+)[\\/].-$") or ".","\\","/")
-local owntree = environment and environment.ownpath or ownpath
-
-local ownlibs = { -- order can be made better
-
- 'l-bit32.lua',
- 'l-lua.lua',
- 'l-macro.lua',
- 'l-sandbox.lua',
- 'l-package.lua',
- 'l-lpeg.lua',
- 'l-function.lua',
- 'l-string.lua',
- 'l-table.lua',
- 'l-io.lua',
- 'l-number.lua',
- 'l-set.lua',
- 'l-os.lua',
- 'l-file.lua',
- 'l-gzip.lua',
- 'l-md5.lua',
- 'l-sha.lua',
- 'l-url.lua',
- 'l-dir.lua',
- 'l-boolean.lua',
- 'l-unicode.lua',
- 'l-math.lua',
-
- 'util-str.lua', -- code might move to l-string
- 'util-tab.lua',
- 'util-fil.lua',
- 'util-sac.lua',
- 'util-sto.lua',
- 'util-prs.lua',
- 'util-fmt.lua',
-
- 'util-soc-imp-reset.lua',
- 'util-soc-imp-socket.lua',
- 'util-soc-imp-copas.lua',
- 'util-soc-imp-ltn12.lua',
- -- 'util-soc-imp-mbox.lua',
- 'util-soc-imp-mime.lua',
- 'util-soc-imp-url.lua',
- 'util-soc-imp-headers.lua',
- 'util-soc-imp-tp.lua',
- 'util-soc-imp-http.lua',
- 'util-soc-imp-ftp.lua',
- 'util-soc-imp-smtp.lua',
-
- 'trac-set.lua',
- 'trac-log.lua',
- 'trac-inf.lua', -- was before trac-set
- 'trac-pro.lua', -- not really needed
- 'util-lua.lua', -- indeed here?
- 'util-deb.lua',
-
- 'util-tpl.lua',
- 'util-sbx.lua',
- 'util-mrg.lua',
-
- 'util-env.lua',
- 'luat-env.lua', -- can come before inf (as in mkiv)
-
- 'util-zip.lua',
-
- 'lxml-tab.lua',
- 'lxml-lpt.lua',
- -- 'lxml-ent.lua',
- 'lxml-mis.lua',
- 'lxml-aux.lua',
- 'lxml-xml.lua',
-
- 'trac-xml.lua',
-
- 'data-ini.lua',
- 'data-exp.lua',
- 'data-env.lua',
- 'data-tmp.lua',
- 'data-met.lua',
- 'data-res.lua',
- 'data-pre.lua',
- 'data-inp.lua',
- 'data-out.lua',
- 'data-fil.lua',
- 'data-con.lua',
- 'data-use.lua',
--- 'data-tex.lua',
--- 'data-bin.lua',
- 'data-zip.lua',
- 'data-tre.lua',
- 'data-sch.lua',
- 'data-lua.lua',
- 'data-aux.lua', -- updater
- 'data-tmf.lua',
- 'data-lst.lua',
-
- 'libs-ini.lua',
-
- 'luat-sta.lua',
- 'luat-fmt.lua',
-
-}
-
--- c:/data/develop/tex-context/tex/texmf-win64/bin/../../texmf-context/tex/context/base/mkiv/data-tmf.lua
--- c:/data/develop/context/sources/data-tmf.lua
-
-local ownlist = {
- -- '.',
- -- ownpath ,
- owntree .. "/../../../../context/sources", -- HH's development path
- --
- owntree .. "/../../texmf-local/tex/context/base/mkiv",
- owntree .. "/../../texmf-context/tex/context/base/mkiv",
- owntree .. "/../../texmf/tex/context/base/mkiv",
- owntree .. "/../../../texmf-local/tex/context/base/mkiv",
- owntree .. "/../../../texmf-context/tex/context/base/mkiv",
- owntree .. "/../../../texmf/tex/context/base/mkiv",
- --
- owntree .. "/../../texmf-local/tex/context/base",
- owntree .. "/../../texmf-context/tex/context/base",
- owntree .. "/../../texmf/tex/context/base",
- owntree .. "/../../../texmf-local/tex/context/base",
- owntree .. "/../../../texmf-context/tex/context/base",
- owntree .. "/../../../texmf/tex/context/base",
-}
-
-if ownpath == "." then table.remove(ownlist,1) end
-
-own = {
- name = ownname,
- path = ownpath,
- tree = owntree,
- list = ownlist,
- libs = ownlibs,
-}
-
-local function locate_libs()
- for l=1,#ownlibs do
- local lib = ownlibs[l]
- for p =1,#ownlist do
- local pth = ownlist[p]
- local filename = pth .. "/" .. lib
- local found = lfs.isfile(filename)
- if found then
- package.path = package.path .. ";" .. pth .. "/?.lua" -- in case l-* does a require
- return pth
- end
- end
- end
-end
-
-local function load_libs()
- local found = locate_libs()
- if found then
- for l=1,#ownlibs do
- local filename = found .. "/" .. ownlibs[l]
- local codeblob = loadfile(filename)
- if codeblob then
- codeblob()
- end
- end
- else
- resolvers = nil
- end
-end
-
-if not resolvers then
- load_libs()
-end
-
-if not resolvers then
- print("")
- print("Mtxrun is unable to start up due to lack of libraries. You may")
- print("try to run 'lua mtxrun.lua --selfmerge' in the path where this")
- print("script is located (normally under ..../scripts/context/lua) which")
- print("will make this script library independent.")
- os.exit()
-end
-
--- verbosity
-
------ e_verbose = environment.arguments["verbose"]
-
-local e_verbose = false
-
--- some common flags (also passed through environment)
-
-local e_silent = environment.argument("silent")
-local e_errors = environment.argument("errors")
-local e_noconsole = environment.argument("noconsole")
-
-local e_trackers = environment.argument("trackers")
-local e_directives = environment.argument("directives")
-local e_experiments = environment.argument("experiments")
-
-local t = { }
-
-if type(e_directives) == "string" then
- t[#t+1] = e_directives
-end
-
-if type(e_silent) == "string" then
- t[#t+1] = format("logs.blocked={%s}",e_silent)
-elseif e_silent == true then
- t[#t+1] = "logs.blocked"
-end
-
-if type(e_errors) == "string" then
- t[#t+1] = format("logs.errors={%s}",e_errors)
-elseif e_errors == true then
- t[#t+1] = "logs.errors"
-end
-
-if e_noconsole then
- t[#t+1] = format("logs.target=file")
-end
-
-if #t > 0 then
- e_directives = concat(t,",")
-end
-
-if e_trackers then trackers .enable(e_trackers) end
-if e_directives then directives .enable(e_directives) end
-if e_experiments then experiments.enable(e_experiments) end
-
-if not environment.trackers then environment.trackers = e_trackers end
-if not environment.directives then environment.directives = e_directives end
-if not environment.experiments then environment.experiments = e_experiments end
-
---
-
-resolvers.reset()
-
-local helpinfo = [[
-<?xml version="1.0" ?>
-<application>
- <metadata>
- <entry name="name">mtxrun</entry>
- <entry name="detail">ConTeXt TDS Runner Tool</entry>
- <entry name="version">1.33</entry>
- </metadata>
- <flags>
- <category name="basic">
- <subcategory>
- <flag name="script"><short>run an mtx script (lua prefered method) (<ref name="noquotes"/>), no script gives list</short></flag>
- <flag name="evaluate"><short>run code passed on the commandline (between quotes) (=loop) (exit|quit aborts)</short></flag>
- <flag name="execute"><short>run a script or program (texmfstart method) (<ref name="noquotes"/>)</short></flag>
- <flag name="resolve"><short>resolve prefixed arguments</short></flag>
- <flag name="ctxlua"><short>run internally (using preloaded libs)</short></flag>
- <flag name="internal"><short>run script using built in libraries (same as <ref name="ctxlua"/>)</short></flag>
- <flag name="locate"><short>locate given filename in database (default) or system (<ref name="first"/> <ref name="all"/> <ref name="detail"/>)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="tree" value="pathtotree"><short>use given texmf tree (default file: setuptex.tmf)</short></flag>
- <flag name="path" value="runpath"><short>go to given path before execution</short></flag>
- <flag name="ifchanged" value="filename"><short>only execute when given file has changed (md checksum)</short></flag>
- <flag name="iftouched" value="old,new"><short>only execute when given file has changed (time stamp)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="makestubs"><short>create stubs for (context related) scripts</short></flag>
- <flag name="removestubs"><short>remove stubs (context related) scripts</short></flag>
- <flag name="stubpath" value="binpath"><short>paths where stubs wil be written</short></flag>
- <flag name="windows"><short>create windows (mswin) stubs</short></flag>
- <flag name="unix"><short>create unix (linux) stubs</short></flag>
- <flag name="addbinarypath"><short>prepend the (found) binarypath to runners</short></flag>
- </subcategory>
- <subcategory>
- <flag name="verbose"><short>give a bit more info</short></flag>
- <flag name="trackers" value="list"><short>enable given trackers</short></flag>
- <flag name="progname" value="str"><short>format or backend</short></flag>
- <flag name="systeminfo" value="str"><short>show current operating system, processor, etc</short></flag>
- </subcategory>
- <subcategory>
- <flag name="edit"><short>launch editor with found file</short></flag>
- <flag name="launch"><short>launch files like manuals, assumes os support (<ref name="all"/>,<ref name="list"/>)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="timedrun"><short>run a script and time its run</short></flag>
- <flag name="autogenerate"><short>regenerate databases if needed (handy when used to run context in an editor)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="usekpse"><short>use kpse as fallback (when no mkiv and cache installed, often slower)</short></flag>
- <flag name="forcekpse"><short>force using kpse (handy when no mkiv and cache installed but less functionality)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="prefixes"><short>show supported prefixes</short></flag>
- </subcategory>
- <subcategory>
- <flag name="generate"><short>generate file database</short></flag>
- </subcategory>
- <subcategory>
- <flag name="variables"><short>show configuration variables</short></flag>
- <flag name="configurations"><short>show configuration order</short></flag>
- </subcategory>
- <subcategory>
- <flag name="directives"><short>show (known) directives</short></flag>
- <flag name="trackers"><short>show (known) trackers</short></flag>
- <flag name="experiments"><short>show (known) experiments</short></flag>
- </subcategory>
- <subcategory>
- <flag name="expand-braces"><short>expand complex variable</short></flag>
- <flag name="resolve-path"><short>expand variable (completely resolve paths)</short></flag>
- <flag name="expand-path"><short>expand variable (resolve paths)</short></flag>
- <flag name="expand-var"><short>expand variable (resolve references)</short></flag>
- <flag name="show-path"><short>show path expansion of ...</short></flag>
- <flag name="var-value"><short>report value of variable</short></flag>
- <flag name="find-file"><short>report file location</short></flag>
- <flag name="find-path"><short>report path of file</short></flag>
- </subcategory>
- <subcategory>
- <flag name="pattern" value="string"><short>filter variables</short></flag>
- </subcategory>
- </category>
- </flags>
-</application>
-]]
-
-local application = logs.application {
- name = "mtxrun",
- banner = "ConTeXt TDS Runner Tool 1.32",
- helpinfo = helpinfo,
-}
-
-local report = application.report
-
-messages = messages or { } -- for the moment
-
-runners = runners or { } -- global (might become local)
-
-runners.applications = {
- ["lua"] = "luatex --luaonly",
- ["luc"] = "luatex --luaonly",
- ["pl"] = "perl",
- ["py"] = "python",
- ["rb"] = "ruby",
-}
-
-runners.suffixes = {
- 'rb', 'lua', 'py', 'pl'
-}
-
-runners.registered = {
- texexec = { 'texexec.rb', false }, -- context mkii runner (only tool not to be luafied)
- texutil = { 'texutil.rb', true }, -- old perl based index sorter for mkii (old versions need it)
- texfont = { 'texfont.pl', true }, -- perl script that makes mkii font metric files
- texfind = { 'texfind.pl', false }, -- perltk based tex searching tool, mostly used at pragma
- texshow = { 'texshow.pl', false }, -- perltk based context help system, will be luafied
- -- texwork = { 'texwork.pl', false }, -- perltk based editing environment, only used at pragma
- makempy = { 'makempy.pl', true },
- mptopdf = { 'mptopdf.pl', true },
- pstopdf = { 'pstopdf.rb', true }, -- converts ps (and some more) images, does some cleaning (replaced)
- -- examplex = { 'examplex.rb', false },
- concheck = { 'concheck.rb', false },
- runtools = { 'runtools.rb', true },
- textools = { 'textools.rb', true },
- tmftools = { 'tmftools.rb', true },
- ctxtools = { 'ctxtools.rb', true },
- rlxtools = { 'rlxtools.rb', true },
- pdftools = { 'pdftools.rb', true },
- mpstools = { 'mpstools.rb', true },
- -- exatools = { 'exatools.rb', true },
- xmltools = { 'xmltools.rb', true },
- -- luatools = { 'luatools.lua', true },
- mtxtools = { 'mtxtools.rb', true },
- pdftrimwhite = { 'pdftrimwhite.pl', false },
-}
-
-runners.launchers = {
- windows = { },
- unix = { },
-}
-
--- like runners.libpath("framework"): looks on script's subpath
-
-function runners.libpath(...)
- package.prepend_libpath(file.dirname(environment.ownscript),...)
- package.prepend_libpath(file.dirname(environment.ownname) ,...)
-end
-
-function runners.prepare()
- local checkname = environment.argument("ifchanged")
- if type(checkname) == "string" and checkname ~= "" then
- local oldchecksum = file.loadchecksum(checkname)
- local newchecksum = file.checksum(checkname)
- if oldchecksum == newchecksum then
- if e_verbose then
- report("file '%s' is unchanged",checkname)
- end
- return "skip"
- elseif e_verbose then
- report("file '%s' is changed, processing started",checkname)
- end
- file.savechecksum(checkname)
- end
- local touchname = environment.argument("iftouched")
- if type(touchname) == "string" and touchname ~= "" then
- local oldname, newname = string.splitup(touchname, ",")
- if oldname and newname and oldname ~= "" and newname ~= "" then
- if not file.needs_updating(oldname,newname) then
- if e_verbose then
- report("file '%s' and '%s' have same age",oldname,newname)
- end
- return "skip"
- elseif e_verbose then
- report("file '%s' is older than '%s'",oldname,newname)
- end
- end
- end
- local runpath = environment.argument("path")
- if type(runpath) == "string" and not lfs.chdir(runpath) then
- report("unable to change to path '%s'",runpath)
- return "error"
- end
- runners.prepare = function() end
- return "run"
-end
-
-function runners.execute_script(fullname,internal,nosplit)
- local noquote = environment.argument("noquotes")
- if fullname and fullname ~= "" then
- local state = runners.prepare()
- if state == 'error' then
- return false
- elseif state == 'skip' then
- return true
- elseif state == "run" then
- local path, name, suffix = file.splitname(fullname)
- local result = ""
- if path ~= "" then
- result = fullname
- elseif name then
- name = gsub(name,"^int[%a]*:",function()
- internal = true
- return ""
- end )
- name = gsub(name,"^script:","")
- if suffix == "" and runners.registered[name] and runners.registered[name][1] then
- name = runners.registered[name][1]
- suffix = file.suffix(name)
- end
- if suffix == "" then
- -- loop over known suffixes
- for _,s in pairs(runners.suffixes) do
- result = resolvers.findfile(name .. "." .. s, 'texmfscripts')
- if result ~= "" then
- break
- end
- end
- elseif runners.applications[suffix] then
- result = resolvers.findfile(name, 'texmfscripts')
- else
- -- maybe look on path
- result = resolvers.findfile(name, 'other text files')
- end
- end
- if result and result ~= "" then
- if not no_split then
- local before, after = environment.splitarguments(fullname) -- already done
- environment.arguments_before, environment.arguments_after = before, after
- end
- if internal then
- arg = { } for _,v in pairs(environment.arguments_after) do arg[#arg+1] = v end
- environment.ownscript = result
- dofile(result)
- else
-local texmfcnf = resolvers.getenv("TEXMFCNF")
-if not texmfcnf or texmfcnf == "" then
- texmfcnf = resolvers.expandedpathfromlist(resolvers.splitpath(resolvers.resolve(resolvers.luacnfspec)))
- resolvers.setenv("TEXMFCNF",table.concat(texmfcnf,";")) -- for running texexec etc (after tl change to texmf-dist)
-end
- local binary = runners.applications[file.suffix(result)]
- result = string.quoted(string.unquoted(result))
- -- if string.match(result,' ') and not string.match(result,"^\".*\"$") then
- -- result = '"' .. result .. '"'
- -- end
- if binary and binary ~= "" then
- result = binary .. " " .. result
- end
- local command = result .. " " .. environment.reconstructcommandline(environment.arguments_after,noquote)
- if e_verbose then
- report()
- report("executing: %s",command)
- report()
- report()
- io.flush()
- end
- local code = os.execute(command)
- if code == 0 then
- return true
- else
- if binary then
- binary = file.addsuffix(binary,os.binsuffix)
- for p in gmatch(os.getenv("PATH"),"[^"..io.pathseparator.."]+") do
- if lfs.isfile(file.join(p,binary)) then
- return false
- end
- end
- report()
- report("This script needs '%s' which seems not to be installed.",binary)
- report()
- end
- return false
- end
- end
- end
- end
- end
- return false
-end
-
-function runners.execute_program(fullname)
- local noquote = environment.argument("noquotes")
- if fullname and fullname ~= "" then
- local state = runners.prepare()
- if state == 'error' then
- return false
- elseif state == 'skip' then
- return true
- elseif state == "run" then
- local before, after = environment.splitarguments(fullname)
- for k=1,#after do after[k] = resolvers.resolve(after[k]) end
- environment.initializearguments(after)
- fullname = gsub(fullname,"^bin:","")
- local command = fullname .. " " .. (environment.reconstructcommandline(after or "",noquote) or "")
- report()
- report("executing: %s",command)
- report()
- report()
- io.flush()
- local code = os.execute(command)
- return code == 0
- end
- end
- return false
-end
-
--- the --usekpse flag will fallback (not default) on kpse (hm, we can better update mtx-stubs)
-
-local windows_stub = '@echo off\013\010setlocal\013\010set ownpath=%%~dp0%%\013\010texlua "%%ownpath%%mtxrun.lua" --usekpse --execute %s %%*\013\010endlocal\013\010'
-local unix_stub = '#!/bin/sh\010mtxrun --usekpse --execute %s \"$@\"\010'
-
-function runners.handle_stubs(create)
- local stubpath = environment.argument('stubpath') or '.' -- 'auto' no longer subpathssupported
- local windows = environment.argument('windows') or environment.argument('mswin') or false
- local unix = environment.argument('unix') or environment.argument('linux') or false
- if not windows and not unix then
- if os.platform == "unix" then
- unix = true
- else
- windows = true
- end
- end
- for _,v in pairs(runners.registered) do
- local name, doit = v[1], v[2]
- if doit then
- local base = gsub(file.basename(name), "%.(.-)$", "")
- if create then
- if windows then
- io.savedata(file.join(stubpath,base..".bat"),format(windows_stub,name))
- report("windows stub for '%s' created",base)
- end
- if unix then
- io.savedata(file.join(stubpath,base),format(unix_stub,name))
- report("unix stub for '%s' created",base)
- end
- else
- if windows and (os.remove(file.join(stubpath,base..'.bat')) or os.remove(file.join(stubpath,base..'.cmd'))) then
- report("windows stub for '%s' removed", base)
- end
- if unix and (os.remove(file.join(stubpath,base)) or os.remove(file.join(stubpath,base..'.sh'))) then
- report("unix stub for '%s' removed",base)
- end
- end
- end
- end
-end
-
-function runners.resolve_string(filename)
- if filename and filename ~= "" then
- runners.report_location(resolvers.resolve(filename))
- end
-end
-
--- differs from texmfstart where locate appends .com .exe .bat ... todo
-
-function runners.locate_file(filename) -- was given file but only searches in tree
- if filename and filename ~= "" then
- if environment.argument("first") then
- runners.report_location(resolvers.findfile(filename))
- -- resolvers.dowithfilesandreport(resolvers.findfile,filename)
- elseif environment.argument("all") then
- local result, status = resolvers.findfiles(filename)
- if status and environment.argument("detail") then
- runners.report_location(status)
- else
- runners.report_location(result)
- end
- else
- runners.report_location(resolvers.findgivenfile(filename))
- -- resolvers.dowithfilesandreport(resolvers.findgivenfile,filename)
- end
- end
-end
-
-function runners.locate_platform()
- runners.report_location(os.platform)
-end
-
-function runners.report_location(result)
- if type(result) == "table" then
- for i=1,#result do
- if i > 1 then
- io.write("\n")
- end
- io.write(result[i])
- end
- else
- io.write(result)
- end
-end
-
-function runners.edit_script(filename) -- we assume that gvim is present on most systems (todo: also in cnf file)
- local editor = os.getenv("MTXRUN_EDITOR") or os.getenv("TEXMFSTART_EDITOR") or os.getenv("EDITOR") or 'gvim'
- local rest = resolvers.resolve(filename)
- if rest ~= "" then
- local command = editor .. " " .. rest
- if e_verbose then
- report()
- report("starting editor: %s",command)
- report()
- report()
- end
- os.launch(command)
- end
-end
-
-function runners.save_script_session(filename, list)
- if type(list) == "table" then
- local t = { }
- for i=1,#list do
- local key = list[i]
- t[key] = environment.arguments[key]
- end
- io.savedata(filename,table.serialize(t,true))
- end
-end
-
-function runners.load_script_session(filename)
- if lfs.isfile(filename) then
- local t = io.loaddata(filename)
- if t then
- t = loadstring(t)
- if t then t = t() end
- for key, value in pairs(t) do
- environment.arguments[key] = value
- end
- end
- end
-end
-
-function resolvers.launch(str)
- -- maybe we also need to test on mtxrun.launcher.suffix environment
- -- variable or on windows consult the assoc and ftype vars and such
- local launchers = runners.launchers[os.platform] if launchers then
- local suffix = file.suffix(str) if suffix then
- local runner = launchers[suffix] if runner then
- str = runner .. " " .. str
- end
- end
- end
- os.launch(str)
-end
-
-function runners.launch_file(filename)
- local allresults = environment.arguments["all"]
- local pattern = environment.arguments["pattern"]
- local listonly = environment.arguments["list"]
- if not pattern or pattern == "" then
- pattern = filename
- end
- if not pattern or pattern == "" then
- report("provide name or --pattern=")
- else
- local t = resolvers.findfiles(pattern,nil,allresults)
- if not t or #t == 0 then
- t = resolvers.findfiles("*/" .. pattern,nil,allresults)
- end
- if not t or #t == 0 then
- t = resolvers.findfiles("*/" .. pattern .. "*",nil,allresults)
- end
- if t and #t > 0 then
- for i=1,#t do
- local name = t[i]
- if listonly then
- report("% 3i: %-30s %s",i,file.basename(name),file.dirname(name))
- else
- report("launching: %s",name)
- resolvers.launch(name)
- if not allresults then
- break
- end
- end
- end
- if listonly then
- io.write("\n")
- io.write("\n[select number]\n\n>> ")
- local answer = tonumber(io.read())
- if answer then
- io.write("\n")
- local name = t[answer]
- if name then
- report("launching: %s",name)
- resolvers.launch(name)
- else
- report("invalid number")
- end
- end
- end
- else
- report("no match for %s", pattern)
- end
- end
-end
-
-local mtxprefixes = {
- { "^mtx%-", "mtx-" },
- { "^mtx%-t%-", "mtx-t-" },
-}
-
-function runners.find_mtx_script(filename)
- local function found(name)
- local path = file.dirname(name)
- if path and path ~= "" then
- return false
- else
- local fullname = own and own.path and file.join(own.path,name)
- return io.exists(fullname) and fullname
- end
- end
- filename = file.addsuffix(filename,"lua")
- local basename = file.removesuffix(file.basename(filename))
- local suffix = file.suffix(filename)
- -- qualified path, raw name
- local fullname = file.is_qualified_path(filename) and io.exists(filename) and filename
- if fullname and fullname ~= "" then
- return fullname
- end
- -- current path, raw name
- fullname = "./" .. filename
- fullname = io.exists(fullname) and fullname
- if fullname and fullname ~= "" then
- return fullname
- end
- -- mtx- prefix checking
- for i=1,#mtxprefixes do
- local mtxprefix = mtxprefixes[i]
- mtxprefix = find(filename,mtxprefix[1]) and "" or mtxprefix[2]
- -- context namespace, mtx-<filename>
- fullname = mtxprefix .. filename
- fullname = found(fullname) or resolvers.findfile(fullname)
- if fullname and fullname ~= "" then
- return fullname
- end
- -- context namespace, mtx-<filename>s
- fullname = mtxprefix .. basename .. "s" .. "." .. suffix
- fullname = found(fullname) or resolvers.findfile(fullname)
- if fullname and fullname ~= "" then
- return fullname
- end
- -- context namespace, mtx-<filename minus trailing s>
- fullname = mtxprefix .. gsub(basename,"s$","") .. "." .. suffix
- fullname = found(fullname) or resolvers.findfile(fullname)
- if fullname and fullname ~= "" then
- return fullname
- end
- end
- -- context namespace, just <filename>
- fullname = resolvers.findfile(filename)
- return fullname
-end
-
-function runners.register_arguments(...)
- local arguments = environment.arguments_after
- local passedon = { ... }
- for i=#passedon,1,-1 do
- local pi = passedon[i]
- if pi then
- table.insert(arguments,1,pi)
- end
- end
-end
-
-function runners.execute_ctx_script(filename,...)
- runners.register_arguments(...)
- local arguments = environment.arguments_after
- local fullname = runners.find_mtx_script(filename) or ""
- if file.suffix(fullname) == "cld" then
- -- handy in editors where we force --autopdf
- report("running cld script: %s",filename)
- table.insert(arguments,1,fullname)
- table.insert(arguments,"--autopdf")
- fullname = runners.find_mtx_script("context") or ""
- end
- -- retry after generate but only if --autogenerate
- if fullname == "" and environment.argument("autogenerate") then -- might become the default
- resolvers.renewcache()
- trackers.enable("resolvers.locating")
- resolvers.load()
- --
- fullname = runners.find_mtx_script(filename) or ""
- end
- -- that should do it
- if fullname ~= "" then
- local state = runners.prepare()
- if state == 'error' then
- return false
- elseif state == 'skip' then
- return true
- elseif state == "run" then
- -- load and save ... kind of undocumented
- arg = { } for _,v in pairs(arguments) do arg[#arg+1] = resolvers.resolve(v) end
- environment.initializearguments(arg)
- local loadname = environment.arguments['load']
- if loadname then
- if type(loadname) ~= "string" then loadname = file.basename(fullname) end
- loadname = file.replacesuffix(loadname,"cfg")
- runners.load_script_session(loadname)
- end
- filename = environment.files[1]
- if e_verbose then
- report("using script: %s (if --path is used don't run on path where mtxrun lives)\n",fullname)
- end
- environment.ownscript = fullname
- dofile(fullname)
- local savename = environment.arguments['save']
- if savename then
- if type(savename) ~= "string" then savename = file.basename(fullname) end
- savename = file.replacesuffix(savename,"cfg")
- runners.save_script_session(savename,save_list)
- end
- return true
- end
- else
- if filename == "" or filename == "help" then
- local context = resolvers.findfile("mtx-context.lua")
- trackers.enable("resolvers.locating")
- if context ~= "" then
- local result = dir.glob((gsub(context,"mtx%-context","mtx-*"))) -- () needed
- local valid = { }
- table.sort(result)
- for i=1,#result do
- local scriptname = result[i]
- local scriptbase = match(scriptname,".*mtx%-([^%-]-)%.lua")
- if scriptbase then
- local data = io.loaddata(scriptname)
- local application = match(data,"local application.-=.-(%{.-%})")
- if application then
- application = loadstring("return " .. application)
- if application then
- application = application()
- local banner = application.banner
- if banner then
- local description, version = match(banner,"^(.-) ([%d.]+)$")
- if description then
- valid[#valid+1] = { scriptbase, version, description }
- else
- valid[#valid+1] = { scriptbase, "", banner }
- end
- end
- end
- end
- end
- end
- if #valid > 0 then
- application.identify()
- report("no script name given, known scripts:")
- report()
- for k=1,#valid do
- local v = valid[k]
- report("%-12s %4s %s",v[1],v[2],v[3])
- end
- end
- else
- report("no script name given")
- end
- else
- filename = file.addsuffix(filename,"lua")
- if file.is_qualified_path(filename) then
- report("unknown script '%s'",filename)
- else
- report("unknown script '%s' or 'mtx-%s'",filename,filename)
- end
- end
- return false
- end
-end
-
-function runners.prefixes()
- application.identify()
- report()
- report(concat(resolvers.allprefixes(true)," "))
-end
-
-function runners.timedrun(filename) -- just for me
- if filename and filename ~= "" then
- runners.timed(function() os.execute(filename) end)
- end
-end
-
-function runners.timed(action)
- statistics.timed(action,true)
-end
-
-function runners.associate(filename)
- os.launch(filename)
-end
-
-function runners.evaluate(code,filename) -- for Luigi
- local environment = table.setmetatableindex(_G)
- if code == "loop" then
- while true do
- io.write("lua > ")
- local code = io.read()
- if code == "quit" or code == "exit" then
- break
- elseif code ~= "" then
- local temp = string.match(code,"^= (.*)$")
- if temp then
- code = "inspect("..temp..")"
- end
- local compiled, message = load(code,"console","t",environment)
- if type(compiled) ~= "function" then
- compiled = load("inspect("..code..")","console","t",environment)
- end
- if type(compiled) ~= "function" then
- io.write("! " .. (message or code).."\n")
- else
- io.write(compiled())
- end
- end
- end
- else
- if type(code) ~= "string" or code == "" then
- code = filename
- end
- if code ~= "" then
- local compiled, message = load(code,"console","t",environment)
- if type(compiled) ~= "function" then
- compiled = load("inspect("..code..")","console","t",environment)
- end
- if type(compiled) ~= "function" then
- io.write("invalid lua code: " .. (message or code))
- return
- end
- io.write(compiled())
- end
- end
-end
-
-function runners.gethelp(filename)
- local url = environment.argument("url")
- if url and url ~= "" then
- local command = string.gsub(environment.argument("command") or "unknown","^%s*\\*(.-)%s*$","%1")
- url = utilities.templates.replace(url,{ command = command })
- os.launch(url)
- else
- report("no --url given")
- end
-end
-
-function runners.systeminfo()
- report("architecture : %s",os.platform or "<unset>")
- report("operating system : %s",os.name or "<unset>")
- report("file architecture : %s",os.type or "<unset>")
- report("binary path : %s",os.selfdir or "<unset>")
- report("binary suffix : %s",os.binsuffix or "<unset>")
- report("library suffix : %s",os.libsuffix or "<unset>")
-end
-
--- this is a bit dirty ... first we store the first filename and next we
--- split the arguments so that we only see the ones meant for this script
--- ... later we will use the second half
-
-local filename = environment.files[1] or ""
-local ok = true
-
-local before, after = environment.splitarguments(filename)
-environment.arguments_before, environment.arguments_after = before, after
-environment.initializearguments(before)
-
-e_verbose = environment.arguments["verbose"] -- delayed till here (we need the ones before script)
-
-if e_verbose then
- trackers.enable("resolvers.locating")
-end
-
--- maybe the unset has to go to this level
-
-local is_mkii_stub = runners.registered[file.removesuffix(file.basename(filename))]
-
-local e_argument = environment.argument
-
-if e_argument("timedlog") then
- logs.settimedlog()
-end
-
-if e_argument("usekpse") or e_argument("forcekpse") or is_mkii_stub then
-
- resolvers.load_tree(e_argument('tree'),true) -- force resolve of TEXMFCNF
-
- os.setenv("engine","")
- os.setenv("progname","")
-
- local remapper = {
- otf = "opentype fonts",
- ttf = "truetype fonts",
- ttc = "truetype fonts",
- pfb = "type1 fonts",
- other = "other text files",
- }
-
- local progname = e_argument("progname") or 'context'
-
- local function kpse_initialized()
- texconfig.kpse_init = true
- local t = os.clock()
- local k = kpse.original.new("luatex",progname)
- local dummy = k:find_file("mtxrun.lua") -- so that we're initialized
- report("kpse fallback with progname '%s' initialized in %s seconds",progname,os.clock()-t)
- kpse_initialized = function() return k end
- return k
- end
-
- local findfile = resolvers.findfile
- local showpath = resolvers.showpath
-
- if e_argument("forcekpse") then
-
- function resolvers.findfile(name,kind)
- return (kpse_initialized():find_file(resolvers.cleanpath(name),(kind ~= "" and (remapper[kind] or kind)) or "tex") or "") or ""
- end
- function resolvers.showpath(name)
- return (kpse_initialized():show_path(name)) or ""
- end
-
- elseif e_argument("usekpse") or is_mkii_stub then
-
- resolvers.load()
-
- function resolvers.findfile(name,kind)
- local found = findfile(name,kind) or ""
- if found ~= "" then
- return found
- else
- return (kpse_initialized():find_file(resolvers.cleanpath(name),(kind ~= "" and (remapper[kind] or kind)) or "tex") or "") or ""
- end
- end
- function resolvers.showpath(name)
- local found = showpath(name) or ""
- if found ~= "" then
- return found
- else
- return (kpse_initialized():show_path(name)) or ""
- end
- end
-
- end
-
- function runners.loadbase()
- end
-
-else
-
- function runners.loadbase(...)
- if not resolvers.load(...) then
- report("forcing cache reload")
- resolvers.renewcache()
- trackers.enable("resolvers.locating")
- if not resolvers.load(...) then
- report("the resolver databases are not present or outdated")
- end
- end
- end
-
- resolvers.load_tree(e_argument('tree'),e_argument("resolve"))
-
-end
-
--- joke .. reminds me of messing with gigi terminals
-
-do
-
- local a_locale = e_argument("locale")
-
- if a_locale then
-
- -- I really hate this crap but am too tired of discussing it over and over
- -- again so for the sake of usiage outside context we will provide ways to
- -- use locales in an otherwise supposed to be locale agnostic system. And
- -- forget about support in case of interferences.
-
- report()
- report(what == "force" and "forcing locale:" or "original locale:")
- report()
- report(" collate : %s",status.lc_collate or "<unset>")
- report(" ctype : %s",status.lc_ctype or "<unset>")
- report(" monetary : %s",status.lc_monetary or "<unset>")
- report(" numeric : %s",status.lc_numeric or "<unset>")
- report(" time : %s",status.lc_time or "<unset>")
- report()
-
- end
-
- if a_locale == "force" then
- os.setlocale(status.lc_collate ,"collate")
- os.setlocale(status.lc_ctype ,"ctype")
- os.setlocale(status.lc_monetary,"monetary")
- os.setlocale(status.lc_numeric ,"numeric")
- os.setlocale(status.lc_time ,"time")
- else
- function os.setlocale()
- end
- end
-
-end
-
--- if e_argument("ansi") or e_argument("ansilog") then
-
--- logs.setformatters(e_argument("ansi") and "ansi" or "ansilog")
-
--- -- local script = e_argument("script") or e_argument("scripts")
--- --
--- -- if type(script) == "string" then
--- -- logs.writer("]0;"..script.."") -- for Alan to test
--- -- end
-
--- end
-
-if e_argument("script") or e_argument("scripts") then
-
- -- run a script by loading it (using libs), pass args
-
- if e_argument("nofiledatabase") then
- -- handy for mtx-update
- else
- runners.loadbase()
- end
- if is_mkii_stub then
- ok = runners.execute_script(filename,false,true)
- else
- ok = runners.execute_ctx_script(filename)
- end
-
-elseif e_argument("evaluate") then
-
- runners.evaluate(e_argument("evaluate"),filename)
-
-elseif e_argument("selfmerge") then
-
- -- embed used libraries
-
- runners.loadbase()
- local found = locate_libs()
-
- if found then
- local mtxrun = resolvers.findfile("mtxrun.lua") -- includes local name
- if lfs.isfile(mtxrun) then
- utilities.merger.selfmerge(mtxrun,own.libs,{ found })
- application.report("runner updated on resolved path: %s",mtxrun)
- else
- utilities.merger.selfmerge(own.name,own.libs,{ found })
- application.report("runner updated on relative path: %s",own.name)
- end
- end
-
-elseif e_argument("selfclean") then
-
- -- remove embedded libraries
-
- runners.loadbase()
-
- local mtxrun = resolvers.findfile("mtxrun.lua") -- includes local name
- if lfs.isfile(mtxrun) then
- utilities.merger.selfclean(mtxrun)
- application.report("runner cleaned on resolved path: %s",mtxrun)
- else
- utilities.merger.selfclean(own.name)
- application.report("runner cleaned on relative path: %s",own.name)
- end
-
-elseif e_argument("selfupdate") then
-
- runners.loadbase()
- trackers.enable("resolvers.locating")
- resolvers.updatescript(own.name,"mtxrun")
-
-elseif e_argument("ctxlua") or e_argument("internal") then
-
- -- run a script by loading it (using libs)
-
- runners.loadbase()
- ok = runners.execute_script(filename,true)
-
-elseif e_argument("execute") then
-
- -- execute script
-
- runners.loadbase()
- ok = runners.execute_script(filename)
-
-elseif e_argument("direct") then
-
- -- equals bin:
-
- runners.loadbase()
- ok = runners.execute_program(filename)
-
-elseif e_argument("edit") then
-
- -- edit file
-
- runners.loadbase()
- runners.edit_script(filename)
-
-elseif e_argument("launch") then
-
- runners.loadbase()
- runners.launch_file(filename)
-
-elseif e_argument("associate") then
-
- runners.associate(filename)
-
-elseif e_argument("gethelp") then
-
- runners.gethelp()
-
-elseif e_argument("makestubs") then
-
- -- make stubs (depricated)
-
- runners.handle_stubs(true)
-
-elseif e_argument("removestubs") then
-
- -- remove stub (depricated)
-
- runners.loadbase()
- runners.handle_stubs(false)
-
-elseif e_argument("resolve") then
-
- -- resolve string
-
- runners.loadbase()
- runners.resolve_string(filename)
-
-elseif e_argument("locate") then
-
- -- locate file (only database)
-
- runners.loadbase()
- runners.locate_file(filename)
-
-elseif e_argument("platform") or e_argument("show-platform") then
-
- -- locate platform
-
- runners.loadbase()
- runners.locate_platform()
-
-elseif e_argument("prefixes") then
-
- runners.loadbase()
- runners.prefixes()
-
-elseif e_argument("timedrun") then
-
- -- locate platform
-
- runners.loadbase()
- runners.timedrun(filename)
-
-elseif e_argument("variables") or e_argument("show-variables") or e_argument("expansions") or e_argument("show-expansions") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expansions",filename)
-
- resolvers.load("nofiles")
- resolvers.listers.variables(e_argument("pattern"))
-
-elseif e_argument("configurations") or e_argument("show-configurations") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--configurations",filename)
-
- resolvers.load("nofiles")
- resolvers.listers.configurations()
-
-elseif e_argument("find-file") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--find-file",filename)
-
- resolvers.load()
- local e_all = e_argument("all")
- local e_pattern = e_argument("pattern")
- local e_format = e_argument("format")
- local finder = e_all and resolvers.findfiles or resolvers.findfile
- if not e_pattern then
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(finder,environment.files,e_format)
- elseif type(e_pattern) == "string" then
- resolvers.dowithfilesandreport(finder,{ e_pattern },e_format)
- end
-
-elseif e_argument("find-path") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--find-path",filename)
-
- resolvers.load()
- local path = resolvers.findpath(filename)
- if e_verbose then
- report(path)
- else
- print(path)
- end
-
-elseif e_argument("expand-braces") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expand-braces",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.expandbraces, environment.files)
-
-elseif e_argument("expand-path") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expand-path",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.expandpath, environment.files)
-
-elseif e_argument("resolve-path") then
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.cleanedpathlist, environment.files)
-
-elseif e_argument("expand-var") or e_argument("expand-variable") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expand-var",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.expansion, environment.files)
-
-elseif e_argument("show-path") or e_argument("path-value") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--show-path",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.showpath, environment.files)
-
-elseif e_argument("var-value") or e_argument("show-value") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--show-value",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.variable,environment.files)
-
-elseif e_argument("format-path") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--format-path",filename)
-
- resolvers.load()
- report(caches.getwritablepath("format"))
-
--- elseif e_argument("pattern") then
---
--- -- luatools
---
--- runners.execute_ctx_script("mtx-base","--pattern='" .. e_argument("pattern") .. "'",filename)
-
-elseif e_argument("generate") then
-
- -- luatools
-
- if filename and filename ~= "" then
- resolvers.load("nofiles")
- trackers.enable("resolvers.locating")
- resolvers.renew(filename)
- else
- resolvers.renewcache()
- trackers.enable("resolvers.locating")
- resolvers.load()
- end
-
- e_verbose = true
-
-elseif e_argument("make") or e_argument("ini") or e_argument("compile") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--make",filename)
-
- resolvers.load()
- trackers.enable("resolvers.locating")
- environment.make_format(filename)
-
-elseif e_argument("run") then
-
- -- luatools
-
- runners.execute_ctx_script("mtx-base","--run",filename)
-
-elseif e_argument("fmt") then
-
- -- luatools
-
- runners.execute_ctx_script("mtx-base","--fmt",filename)
-
-elseif e_argument("help") and filename=='base' then
-
- -- luatools
-
- runners.execute_ctx_script("mtx-base","--help")
-
-elseif e_argument("version") then
-
- application.version()
-
- application.report("source path",environment.ownbin)
-
-elseif e_argument("directives") then
-
- directives.show()
-
-elseif e_argument("trackers") then
-
- trackers.show()
-
-elseif e_argument("experiments") then
-
- experiments.show()
-
-elseif e_argument("exporthelp") then
-
- runners.loadbase()
- application.export(e_argument("exporthelp"),filename)
-
-elseif e_argument("systeminfo") then
-
- runners.systeminfo()
-
-elseif e_argument("locale") then
-
- -- already done
-
-elseif e_argument("help") or filename=='help' or filename == "" then
-
- application.help()
-
-elseif find(filename,"^bin:") then
-
- runners.loadbase()
- ok = runners.execute_program(filename)
-
-elseif is_mkii_stub then
-
- -- execute mkii script
-
- runners.loadbase()
- ok = runners.execute_script(filename,false,true)
-
-elseif false then
-
- runners.loadbase()
- ok = runners.execute_ctx_script(filename)
- if not ok then
- ok = runners.execute_script(filename)
- end
-
-elseif environment.files[1] == 'texmfcnf.lua' then -- so that we don't need to load mtx-base
-
- resolvers.load("nofiles")
- resolvers.listers.configurations()
-
-else
- runners.loadbase()
- runners.execute_ctx_script("mtx-base",filename)
-
-end
-
-if e_verbose then
- report()
- report("elapsed lua time: %0.3f seconds",os.runtime())
-end
-
-if os.type ~= "windows" then
- texio.write("\n") -- is this still valid?
-end
-
-if ok == false then ok = 1 elseif ok == true or ok == nil then ok = 0 end
-
--- os.exit(ok,true) -- true forces a cleanup in 5.2+
-
-os.exit(ok) -- true forces a cleanup in 5.2+ but reports a wrong number then
diff --git a/Master/texmf-dist/scripts/context/stubs/unix/mtxrunjit b/Master/texmf-dist/scripts/context/stubs/unix/mtxrunjit
deleted file mode 100755
index 117105aa5c0..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/unix/mtxrunjit
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/bin/sh
-
-luajittex --luaonly $(dirname $0)/mtxrun "$@"
-
-# luajittex --luaonly ${0%jit} "$@"
diff --git a/Master/texmf-dist/scripts/context/stubs/unix/pstopdf b/Master/texmf-dist/scripts/context/stubs/unix/pstopdf
deleted file mode 100644
index 116f5f4a32e..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/unix/pstopdf
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-mtxrun --script pstopdf "$@"
diff --git a/Master/texmf-dist/scripts/context/stubs/unix/texexec b/Master/texmf-dist/scripts/context/stubs/unix/texexec
deleted file mode 100755
index cd5900ff84c..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/unix/texexec
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-mtxrun --usekpse --execute texexec "$@"
diff --git a/Master/texmf-dist/scripts/context/stubs/unix/texmfstart b/Master/texmf-dist/scripts/context/stubs/unix/texmfstart
deleted file mode 100755
index 1799b357915..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/unix/texmfstart
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-mtxrun --usekpse "$@"
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/context.exe b/Master/texmf-dist/scripts/context/stubs/win64/context.exe
deleted file mode 100755
index 93290a6e0a8..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/context.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/contextjit.exe b/Master/texmf-dist/scripts/context/stubs/win64/contextjit.exe
deleted file mode 100755
index 93290a6e0a8..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/contextjit.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/ctxtools.exe b/Master/texmf-dist/scripts/context/stubs/win64/ctxtools.exe
deleted file mode 100755
index 93290a6e0a8..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/ctxtools.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/luatools.exe b/Master/texmf-dist/scripts/context/stubs/win64/luatools.exe
deleted file mode 100755
index 93290a6e0a8..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/luatools.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/mptopdf.exe b/Master/texmf-dist/scripts/context/stubs/win64/mptopdf.exe
deleted file mode 100755
index 93290a6e0a8..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/mptopdf.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/mtxrun.dll b/Master/texmf-dist/scripts/context/stubs/win64/mtxrun.dll
deleted file mode 100755
index 91050273583..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/mtxrun.dll
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/mtxrun.exe b/Master/texmf-dist/scripts/context/stubs/win64/mtxrun.exe
deleted file mode 100755
index 93290a6e0a8..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/mtxrun.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/mtxrun.lua b/Master/texmf-dist/scripts/context/stubs/win64/mtxrun.lua
deleted file mode 100644
index 6fc17adb022..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/mtxrun.lua
+++ /dev/null
@@ -1,27376 +0,0 @@
-#!/usr/bin/env texlua
-
-if not modules then modules = { } end modules ['mtxrun'] = {
- version = 1.001,
- comment = "runner, lua replacement for texmfstart.rb",
- author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright = "PRAGMA ADE / ConTeXt Development Team",
- license = "see context related readme files"
-}
-
--- one can make a stub:
-
--- mtxrun :
---
--- #!/bin/sh
--- env LUATEXDIR=/....../texmf/scripts/context/lua luatex --luaonly mtxrun.lua "$@"
-
--- mtxrun.cmd :
---
--- @luatex --luaonly %~d0%~p0mtxrun.lua %*
-
--- filename : mtxrun.lua
--- comment : companion to context.tex
--- author : Hans Hagen, PRAGMA-ADE, Hasselt NL
--- copyright: PRAGMA ADE / ConTeXt Development Team
--- license : see context related readme files
-
--- This script is based on texmfstart.rb but does not use kpsewhich to locate files.
--- Although kpse is a library it never came to opening up its interface to other
--- programs (esp scripting languages) and so we do it ourselves. The lua variant
--- evolved out of an experimental ruby one. Interesting is that using a scripting
--- language instead of c does not have a speed penalty. Actually the lua variant is
--- more efficient, especially when multiple calls to kpsewhich are involved. The lua
--- library also gives way more control.
-
--- When libraries used here are updates you can run
---
--- mtxrun --selfmerge
---
--- to update the embedded code. After that you might need to run
---
--- mtxrun --selfupdate
---
--- to copy the new script (from scripts/context/lua) to location where
--- binaries are expected. If you want to remove the embedded code you can run
---
--- mtxxun --selfclean
-
--- to be done / considered
---
--- support for --exec or make it default
--- support for jar files (or maybe not, never used, too messy)
--- support for $RUBYINPUTS cum suis (if still needed)
--- remember for subruns: _CTX_K_V_#{original}_
--- remember for subruns: _CTX_K_S_#{original}_
--- remember for subruns: TEXMFSTART.#{original} [tex.rb texmfstart.rb]
-
--- begin library merge
-
-
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-bit32"] = package.loaded["l-bit32"] or true
-
--- original size: 3607, stripped down to: 3009
-
-if not modules then modules={} end modules ['l-bit32']={
- version=1.001,
- license="the same as regular Lua",
- source="bitwise.lua, v 1.24 2014/12/26 17:20:53 roberto",
- comment="drop-in for bit32, adapted a bit by Hans Hagen",
-}
-if bit32 then
-elseif utf8 then
- load ([[
-local select = select -- instead of: arg = { ... }
-bit32 = {
- bnot = function (a)
- return ~a & 0xFFFFFFFF
- end,
- band = function (x, y, z, ...)
- if not z then
- return ((x or -1) & (y or -1)) & 0xFFFFFFFF
- else
- local res = x & y & z
- for i=1,select("#",...) do
- res = res & select(i,...)
- end
- return res & 0xFFFFFFFF
- end
- end,
- bor = function (x, y, z, ...)
- if not z then
- return ((x or 0) | (y or 0)) & 0xFFFFFFFF
- else
- local res = x | y | z
- for i=1,select("#",...) do
- res = res | select(i,...)
- end
- return res & 0xFFFFFFFF
- end
- end,
- bxor = function (x, y, z, ...)
- if not z then
- return ((x or 0) ~ (y or 0)) & 0xFFFFFFFF
- else
- local res = x ~ y ~ z
- for i=1,select("#",...) do
- res = res ~ select(i,...)
- end
- return res & 0xFFFFFFFF
- end
- end,
- btest = function (x, y, z, ...)
- if not z then
- return (((x or -1) & (y or -1)) & 0xFFFFFFFF) ~= 0
- else
- local res = x & y & z
- for i=1,select("#",...) do
- res = res & select(i,...)
- end
- return (res & 0xFFFFFFFF) ~= 0
- end
- end,
- lshift = function (a, b)
- return ((a & 0xFFFFFFFF) << b) & 0xFFFFFFFF
- end,
- rshift = function (a, b)
- return ((a & 0xFFFFFFFF) >> b) & 0xFFFFFFFF
- end,
- arshift = function (a, b)
- a = a & 0xFFFFFFFF
- if b <= 0 or (a & 0x80000000) == 0 then
- return (a >> b) & 0xFFFFFFFF
- else
- return ((a >> b) | ~(0xFFFFFFFF >> b)) & 0xFFFFFFFF
- end
- end,
- lrotate = function (a ,b)
- b = b & 31
- a = a & 0xFFFFFFFF
- a = (a << b) | (a >> (32 - b))
- return a & 0xFFFFFFFF
- end,
- rrotate = function (a, b)
- b = -b & 31
- a = a & 0xFFFFFFFF
- a = (a << b) | (a >> (32 - b))
- return a & 0xFFFFFFFF
- end,
- extract = function (a, f, w)
- return (a >> f) & ~(-1 << (w or 1))
- end,
- replace = function (a, v, f, w)
- local mask = ~(-1 << (w or 1))
- return ((a & ~(mask << f)) | ((v & mask) << f)) & 0xFFFFFFFF
- end,
-}
- ]] ) ()
-elseif bit then
- load ([[
-local band, bnot, rshift, lshift = bit.band, bit.bnot, bit.rshift, bit.lshift
-bit32 = {
- arshift = bit.arshift,
- band = band,
- bnot = bnot,
- bor = bit.bor,
- bxor = bit.bxor,
- btest = function(...)
- return band(...) ~= 0
- end,
- extract = function(a,f,w)
- return band(rshift(a,f),2^(w or 1)-1)
- end,
- lrotate = bit.rol,
- lshift = lshift,
- replace = function(a,v,f,w)
- local mask = 2^(w or 1)-1
- return band(a,bnot(lshift(mask,f)))+lshift(band(v,mask),f)
- end,
- rrotate = bit.ror,
- rshift = rshift,
-}
- ]] ) ()
-else
- xpcall(function() local _,t=require("bit32") if t then bit32=t end return end,function() end)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-lua"] = package.loaded["l-lua"] or true
-
--- original size: 6405, stripped down to: 2865
-
-if not modules then modules={} end modules ['l-lua']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local next,type,tonumber=next,type,tonumber
-LUAMAJORVERSION,LUAMINORVERSION=string.match(_VERSION,"^[^%d]+(%d+)%.(%d+).*$")
-LUAMAJORVERSION=tonumber(LUAMAJORVERSION) or 5
-LUAMINORVERSION=tonumber(LUAMINORVERSION) or 1
-LUAVERSION=LUAMAJORVERSION+LUAMINORVERSION/10
-if LUAVERSION<5.2 and jit then
- MINORVERSION=2
- LUAVERSION=5.2
-end
-if not lpeg then
- lpeg=require("lpeg")
-end
-if loadstring then
- local loadnormal=load
- function load(first,...)
- if type(first)=="string" then
- return loadstring(first,...)
- else
- return loadnormal(first,...)
- end
- end
-else
- loadstring=load
-end
-if not ipairs then
- local function iterate(a,i)
- i=i+1
- local v=a[i]
- if v~=nil then
- return i,v
- end
- end
- function ipairs(a)
- return iterate,a,0
- end
-end
-if not pairs then
- function pairs(t)
- return next,t
- end
-end
-if not table.unpack then
- table.unpack=_G.unpack
-elseif not unpack then
- _G.unpack=table.unpack
-end
-if not package.loaders then
- package.loaders=package.searchers
-end
-local print,select,tostring=print,select,tostring
-local inspectors={}
-function setinspector(kind,inspector)
- inspectors[kind]=inspector
-end
-function inspect(...)
- for s=1,select("#",...) do
- local value=select(s,...)
- if value==nil then
- print("nil")
- else
- local done=false
- local kind=type(value)
- local inspector=inspectors[kind]
- if inspector then
- done=inspector(value)
- if done then
- break
- end
- end
- for kind,inspector in next,inspectors do
- done=inspector(value)
- if done then
- break
- end
- end
- if not done then
- print(tostring(value))
- end
- end
- end
-end
-local dummy=function() end
-function optionalrequire(...)
- local ok,result=xpcall(require,dummy,...)
- if ok then
- return result
- end
-end
-local flush=io.flush
-if flush then
- local execute=os.execute if execute then function os.execute(...) flush() return execute(...) end end
- local exec=os.exec if exec then function os.exec (...) flush() return exec (...) end end
- local spawn=os.spawn if spawn then function os.spawn (...) flush() return spawn (...) end end
- local popen=io.popen if popen then function io.popen (...) flush() return popen (...) end end
-end
-FFISUPPORTED=type(ffi)=="table" and ffi.os~="" and ffi.arch~="" and ffi.load
-if not FFISUPPORTED then
- local okay;okay,ffi=pcall(require,"ffi")
- FFISUPPORTED=type(ffi)=="table" and ffi.os~="" and ffi.arch~="" and ffi.load
-end
-if not FFISUPPORTED then
- ffi=nil
-elseif not ffi.number then
- ffi.number=tonumber
-end
-if LUAVERSION>5.3 then
-end
-if status and os.setenv then
- os.setenv("engine",string.lower(status.luatex_engine or "unknown"))
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-macro"] = package.loaded["l-macro"] or true
-
--- original size: 10130, stripped down to: 5990
-
-if not modules then modules={} end modules ['l-macros']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local S,P,R,V,C,Cs,Cc,Ct,Carg=lpeg.S,lpeg.P,lpeg.R,lpeg.V,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Ct,lpeg.Carg
-local lpegmatch=lpeg.match
-local concat=table.concat
-local format,sub,match=string.format,string.sub,string.match
-local next,load,type=next,load,type
-local newline=S("\n\r")^1
-local continue=P("\\")*newline
-local whitespace=S(" \t\n\r")
-local spaces=S(" \t")+continue
-local nametoken=R("az","AZ","__","09")
-local name=nametoken^1
-local body=((continue/""+1)-newline)^1
-local lparent=P("(")
-local rparent=P(")")
-local noparent=1-(lparent+rparent)
-local nested=P { lparent*(noparent+V(1))^0*rparent }
-local escaped=P("\\")*P(1)
-local squote=P("'")
-local dquote=P('"')
-local quoted=dquote*(escaped+(1-dquote))^0*dquote+squote*(escaped+(1-squote))^0*squote
-local arguments=lparent*Ct((Cs((nested+(quoted+1-S("),")))^1)+S(", "))^0)*rparent
-local macros=lua.macros or {}
-lua.macros=macros
-local patterns={}
-local definitions={}
-local resolve
-local subparser
-local report_lua=function(...)
- if logs and logs.reporter then
- report_lua=logs.reporter("system","lua")
- report_lua(...)
- else
- print(format(...))
- end
-end
-local safeguard=P("local")*whitespace^1*name*(whitespace+P("="))
-resolve=safeguard+C(C(name)*(arguments^-1))/function(raw,s,a)
- local d=definitions[s]
- if d then
- if a then
- local n=#a
- local p=patterns[s][n]
- if p then
- local d=d[n]
- for i=1,n do
- a[i]=lpegmatch(subparser,a[i]) or a[i]
- end
- return lpegmatch(p,d,1,a) or d
- else
- return raw
- end
- else
- return d[0] or raw
- end
- elseif a then
- for i=1,#a do
- a[i]=lpegmatch(subparser,a[i]) or a[i]
- end
- return s.."("..concat(a,",")..")"
- else
- return raw
- end
-end
-subparser=Cs((resolve+P(1))^1)
-local enddefine=P("#enddefine")/""
-local beginregister=(C(name)*(arguments+Cc(false))*C((1-enddefine)^1)*enddefine)/function(k,a,v)
- local n=0
- if a then
- n=#a
- local pattern=P(false)
- for i=1,n do
- pattern=pattern+(P(a[i])*Carg(1))/function(t) return t[i] end
- end
- pattern=Cs((pattern+P(1))^1)
- local p=patterns[k]
- if not p then
- p={ [0]=false,false,false,false,false,false,false,false,false }
- patterns[k]=p
- end
- p[n]=pattern
- end
- local d=definitions[k]
- if not d then
- d={ a=a,[0]=false,false,false,false,false,false,false,false,false }
- definitions[k]=d
- end
- d[n]=lpegmatch(subparser,v) or v
- return ""
-end
-local register=(Cs(name)*(arguments+Cc(false))*spaces^0*Cs(body))/function(k,a,v)
- local n=0
- if a then
- n=#a
- local pattern=P(false)
- for i=1,n do
- pattern=pattern+(P(a[i])*Carg(1))/function(t) return t[i] end
- end
- pattern=Cs((pattern+P(1))^1)
- local p=patterns[k]
- if not p then
- p={ [0]=false,false,false,false,false,false,false,false,false }
- patterns[k]=p
- end
- p[n]=pattern
- end
- local d=definitions[k]
- if not d then
- d={ a=a,[0]=false,false,false,false,false,false,false,false,false }
- definitions[k]=d
- end
- d[n]=lpegmatch(subparser,v) or v
- return ""
-end
-local unregister=(C(name)*spaces^0*(arguments+Cc(false)))/function(k,a)
- local n=0
- if a then
- n=#a
- local p=patterns[k]
- if p then
- p[n]=false
- end
- end
- local d=definitions[k]
- if d then
- d[n]=false
- end
- return ""
-end
-local begindefine=(P("begindefine")*spaces^0/"")*beginregister
-local define=(P("define" )*spaces^0/"")*register
-local undefine=(P("undefine" )*spaces^0/"")*unregister
-local parser=Cs((((P("#")/"")*(define+begindefine+undefine)*(newline^0/"") )+resolve+P(1) )^0 )
-function macros.reset()
- definitions={}
- patterns={}
-end
-function macros.showdefinitions()
- for name,list in table.sortedhash(definitions) do
- local arguments=list.a
- if arguments then
- arguments="("..concat(arguments,",")..")"
- else
- arguments=""
- end
- print("macro: "..name..arguments)
- for i=0,#list do
- local l=list[i]
- if l then
- print(" "..l)
- end
- end
- end
-end
-function macros.resolvestring(str)
- return lpegmatch(parser,str) or str
-end
-function macros.resolving()
- return next(patterns)
-end
-local function reload(path,name,data)
- local only=match(name,".-([^/]+)%.lua")
- if only and only~="" then
- local name=path.."/"..only
- local f=io.open(name,"wb")
- f:write(data)
- f:close()
- local f=loadfile(name)
- os.remove(name)
- return f
- end
-end
-local function reload(path,name,data)
- if path and path~="" then
- local only=string.match(name,".-([^/]+)%.lua")
- if only and only~="" then
- local name=path.."/"..only.."-macro.lua"
- local f=io.open(name,"wb")
- if f then
- f:write(data)
- f:close()
- local l=loadfile(name)
- os.remove(name)
- return l
- end
- end
- end
- return load(data,name)
-end
-local function loaded(name,trace,detail)
- local f=io.open(name,"rb")
- if not f then
- return false,format("file '%s' not found",name)
- end
- local c=f:read("*a")
- if not c then
- return false,format("file '%s' is invalid",name)
- end
- f:close()
- local n=lpegmatch(parser,c)
- if trace then
- if #n~=#c then
- report_lua("macros expanded in '%s' (%i => %i bytes)",name,#c,#n)
- if detail then
- report_lua()
- report_lua(n)
- report_lua()
- end
- elseif detail then
- report_lua("no macros expanded in '%s'",name)
- end
- end
- return reload(lfs and lfs.currentdir(),name,n)
-end
-macros.loaded=loaded
-function required(name,trace)
- local filename=file.addsuffix(name,"lua")
- local fullname=resolvers and resolvers.findfile(filename) or filename
- if not fullname or fullname=="" then
- return false
- end
- local codeblob=package.loaded[fullname]
- if codeblob then
- return codeblob
- end
- local code,message=loaded(fullname,macros,trace,trace)
- if type(code)=="function" then
- code=code()
- else
- report_lua("error when loading '%s'",fullname)
- return false,message
- end
- if code==nil then
- code=false
- end
- package.loaded[fullname]=code
- return code
-end
-macros.required=required
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-sandbox"] = package.loaded["l-sandbox"] or true
-
--- original size: 9604, stripped down to: 6394
-
-if not modules then modules={} end modules ['l-sandbox']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local global=_G
-local next=next
-local unpack=unpack or table.unpack
-local type=type
-local tprint=texio and texio.write_nl or print
-local tostring=tostring
-local format=string.format
-local concat=table.concat
-local sort=table.sort
-local gmatch=string.gmatch
-local gsub=string.gsub
-local requiem=require
-sandbox={}
-local sandboxed=false
-local overloads={}
-local skiploads={}
-local initializers={}
-local finalizers={}
-local originals={}
-local comments={}
-local trace=false
-local logger=false
-local blocked={}
-local function report(...)
- tprint("sandbox ! "..format(...))
-end
-sandbox.report=report
-function sandbox.setreporter(r)
- report=r
- sandbox.report=r
-end
-function sandbox.settrace(v)
- trace=v
-end
-function sandbox.setlogger(l)
- logger=type(l)=="function" and l or false
-end
-local function register(func,overload,comment)
- if type(func)=="function" then
- if type(overload)=="string" then
- comment=overload
- overload=nil
- end
- local function f(...)
- if sandboxed then
- local overload=overloads[f]
- if overload then
- if logger then
- local result={ overload(func,...) }
- logger {
- comment=comments[f] or tostring(f),
- arguments={... },
- result=result[1] and true or false,
- }
- return unpack(result)
- else
- return overload(func,...)
- end
- else
- end
- else
- return func(...)
- end
- end
- if comment then
- comments[f]=comment
- if trace then
- report("registering function: %s",comment)
- end
- end
- overloads[f]=overload or false
- originals[f]=func
- return f
- end
-end
-local function redefine(func,comment)
- if type(func)=="function" then
- skiploads[func]=comment or comments[func] or "unknown"
- if overloads[func]==false then
- overloads[func]=nil
- end
- end
-end
-sandbox.register=register
-sandbox.redefine=redefine
-function sandbox.original(func)
- return originals and originals[func] or func
-end
-function sandbox.overload(func,overload,comment)
- comment=comment or comments[func] or "?"
- if type(func)~="function" then
- if trace then
- report("overloading unknown function: %s",comment)
- end
- elseif type(overload)~="function" then
- if trace then
- report("overloading function with bad overload: %s",comment)
- end
- elseif overloads[func]==nil then
- if trace then
- report("function is not registered: %s",comment)
- end
- elseif skiploads[func] then
- if trace then
- report("function is not skipped: %s",comment)
- end
- else
- if trace then
- report("overloading function: %s",comment)
- end
- overloads[func]=overload
- end
- return func
-end
-local function whatever(specification,what,target)
- if type(specification)~="table" then
- report("%s needs a specification",what)
- elseif type(specification.category)~="string" or type(specification.action)~="function" then
- report("%s needs a category and action",what)
- elseif not sandboxed then
- target[#target+1]=specification
- elseif trace then
- report("already enabled, discarding %s",what)
- end
-end
-function sandbox.initializer(specification)
- whatever(specification,"initializer",initializers)
-end
-function sandbox.finalizer(specification)
- whatever(specification,"finalizer",finalizers)
-end
-function require(name)
- local n=gsub(name,"^.*[\\/]","")
- local n=gsub(n,"[%.].*$","")
- local b=blocked[n]
- if b==false then
- return nil
- elseif b then
- if trace then
- report("using blocked: %s",n)
- end
- return b
- else
- if trace then
- report("requiring: %s",name)
- end
- return requiem(name)
- end
-end
-function blockrequire(name,lib)
- if trace then
- report("preventing reload of: %s",name)
- end
- blocked[name]=lib or _G[name] or false
-end
-function sandbox.enable()
- if not sandboxed then
- debug={
- traceback=debug.traceback,
- }
- for i=1,#initializers do
- initializers[i].action()
- end
- for i=1,#finalizers do
- finalizers[i].action()
- end
- local nnot=0
- local nyes=0
- local cnot={}
- local cyes={}
- local skip={}
- for k,v in next,overloads do
- local c=comments[k]
- if v then
- if c then
- cyes[#cyes+1]=c
- else
- nyes=nyes+1
- end
- else
- if c then
- cnot[#cnot+1]=c
- else
- nnot=nnot+1
- end
- end
- end
- for k,v in next,skiploads do
- skip[#skip+1]=v
- end
- if #cyes>0 then
- sort(cyes)
- report("overloaded known: %s",concat(cyes," | "))
- end
- if nyes>0 then
- report("overloaded unknown: %s",nyes)
- end
- if #cnot>0 then
- sort(cnot)
- report("not overloaded known: %s",concat(cnot," | "))
- end
- if nnot>0 then
- report("not overloaded unknown: %s",nnot)
- end
- if #skip>0 then
- sort(skip)
- report("not overloaded redefined: %s",concat(skip," | "))
- end
- initializers=nil
- finalizers=nil
- originals=nil
- sandboxed=true
- end
-end
-blockrequire("lfs",lfs)
-blockrequire("io",io)
-blockrequire("os",os)
-blockrequire("ffi",ffi)
-local function supported(library)
- local l=_G[library]
- return l
-end
-loadfile=register(loadfile,"loadfile")
-if supported("lua") then
- lua.openfile=register(lua.openfile,"lua.openfile")
-end
-if supported("io") then
- io.open=register(io.open,"io.open")
- io.popen=register(io.popen,"io.popen")
- io.lines=register(io.lines,"io.lines")
- io.output=register(io.output,"io.output")
- io.input=register(io.input,"io.input")
-end
-if supported("os") then
- os.execute=register(os.execute,"os.execute")
- os.spawn=register(os.spawn,"os.spawn")
- os.exec=register(os.exec,"os.exec")
- os.rename=register(os.rename,"os.rename")
- os.remove=register(os.remove,"os.remove")
-end
-if supported("lfs") then
- lfs.chdir=register(lfs.chdir,"lfs.chdir")
- lfs.mkdir=register(lfs.mkdir,"lfs.mkdir")
- lfs.rmdir=register(lfs.rmdir,"lfs.rmdir")
- lfs.isfile=register(lfs.isfile,"lfs.isfile")
- lfs.isdir=register(lfs.isdir,"lfs.isdir")
- lfs.attributes=register(lfs.attributes,"lfs.attributes")
- lfs.dir=register(lfs.dir,"lfs.dir")
- lfs.lock_dir=register(lfs.lock_dir,"lfs.lock_dir")
- lfs.touch=register(lfs.touch,"lfs.touch")
- lfs.link=register(lfs.link,"lfs.link")
- lfs.setmode=register(lfs.setmode,"lfs.setmode")
- lfs.readlink=register(lfs.readlink,"lfs.readlink")
- lfs.shortname=register(lfs.shortname,"lfs.shortname")
- lfs.symlinkattributes=register(lfs.symlinkattributes,"lfs.symlinkattributes")
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-package"] = package.loaded["l-package"] or true
-
--- original size: 12566, stripped down to: 8937
-
-if not modules then modules={} end modules ['l-package']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,unpack=type,unpack
-local gsub,format,find=string.gsub,string.format,string.find
-local insert,remove=table.insert,table.remove
-local P,S,Cs,lpegmatch=lpeg.P,lpeg.S,lpeg.Cs,lpeg.match
-local package=package
-local searchers=package.searchers or package.loaders
-local filejoin=file and file.join or function(path,name) return path.."/"..name end
-local isreadable=file and file.is_readable or function(name) local f=io.open(name) if f then f:close() return true end end
-local addsuffix=file and file.addsuffix or function(name,suffix) return name.."."..suffix end
-local function cleanpath(path)
- return path
-end
-local pattern=Cs((((1-S("\\/"))^0*(S("\\/")^1/"/"))^0*(P(".")^1/"/"+P(1))^1)*-1)
-local function lualibfile(name)
- return lpegmatch(pattern,name) or name
-end
-local offset=luarocks and 1 or 0
-local helpers=package.helpers or {
- cleanpath=cleanpath,
- lualibfile=lualibfile,
- trace=false,
- report=function(...) print(format(...)) end,
- builtin={
- ["preload table"]=searchers[1+offset],
- ["path specification"]=searchers[2+offset],
- ["cpath specification"]=searchers[3+offset],
- ["all in one fallback"]=searchers[4+offset],
- },
- methods={},
- sequence={
- "reset loaded",
- "already loaded",
- "preload table",
- "qualified path",
- "lua extra list",
- "lib extra list",
- "path specification",
- "cpath specification",
- "all in one fallback",
- "not loaded",
- }
-}
-package.helpers=helpers
-local methods=helpers.methods
-local builtin=helpers.builtin
-local extraluapaths={}
-local extralibpaths={}
-local checkedfiles={}
-local luapaths=nil
-local libpaths=nil
-local oldluapath=nil
-local oldlibpath=nil
-local nofextralua=-1
-local nofextralib=-1
-local nofpathlua=-1
-local nofpathlib=-1
-local function listpaths(what,paths)
- local nofpaths=#paths
- if nofpaths>0 then
- for i=1,nofpaths do
- helpers.report("using %s path %i: %s",what,i,paths[i])
- end
- else
- helpers.report("no %s paths defined",what)
- end
- return nofpaths
-end
-local function getextraluapaths()
- if helpers.trace and #extraluapaths~=nofextralua then
- nofextralua=listpaths("extra lua",extraluapaths)
- end
- return extraluapaths
-end
-local function getextralibpaths()
- if helpers.trace and #extralibpaths~=nofextralib then
- nofextralib=listpaths("extra lib",extralibpaths)
- end
- return extralibpaths
-end
-local function getluapaths()
- local luapath=package.path or ""
- if oldluapath~=luapath then
- luapaths=file.splitpath(luapath,";")
- oldluapath=luapath
- nofpathlua=-1
- end
- if helpers.trace and #luapaths~=nofpathlua then
- nofpathlua=listpaths("builtin lua",luapaths)
- end
- return luapaths
-end
-local function getlibpaths()
- local libpath=package.cpath or ""
- if oldlibpath~=libpath then
- libpaths=file.splitpath(libpath,";")
- oldlibpath=libpath
- nofpathlib=-1
- end
- if helpers.trace and #libpaths~=nofpathlib then
- nofpathlib=listpaths("builtin lib",libpaths)
- end
- return libpaths
-end
-package.luapaths=getluapaths
-package.libpaths=getlibpaths
-package.extraluapaths=getextraluapaths
-package.extralibpaths=getextralibpaths
-local hashes={
- lua={},
- lib={},
-}
-local function registerpath(tag,what,target,...)
- local pathlist={... }
- local cleanpath=helpers.cleanpath
- local trace=helpers.trace
- local report=helpers.report
- local hash=hashes[what]
- local function add(path)
- local path=cleanpath(path)
- if not hash[path] then
- target[#target+1]=path
- hash[path]=true
- if trace then
- report("registered %s path %s: %s",tag,#target,path)
- end
- else
- if trace then
- report("duplicate %s path: %s",tag,path)
- end
- end
- end
- for p=1,#pathlist do
- local path=pathlist[p]
- if type(path)=="table" then
- for i=1,#path do
- add(path[i])
- end
- else
- add(path)
- end
- end
-end
-local function pushpath(tag,what,target,path)
- local path=helpers.cleanpath(path)
- insert(target,1,path)
- if helpers.trace then
- helpers.report("pushing %s path in front: %s",tag,path)
- end
-end
-local function poppath(tag,what,target)
- local path=remove(target,1)
- if helpers.trace then
- if path then
- helpers.report("popping %s path from front: %s",tag,path)
- else
- helpers.report("no %s path to pop",tag)
- end
- end
-end
-helpers.registerpath=registerpath
-function package.extraluapath(...)
- registerpath("extra lua","lua",extraluapaths,...)
-end
-function package.pushluapath(path)
- pushpath("extra lua","lua",extraluapaths,path)
-end
-function package.popluapath()
- poppath("extra lua","lua",extraluapaths)
-end
-function package.extralibpath(...)
- registerpath("extra lib","lib",extralibpaths,...)
-end
-function package.pushlibpath(path)
- pushpath("extra lib","lib",extralibpaths,path)
-end
-function package.poplibpath()
- poppath("extra lib","lua",extralibpaths)
-end
-local function loadedaslib(resolved,rawname)
- local base=gsub(rawname,"%.","_")
- local init="luaopen_"..gsub(base,"%.","_")
- local data={ resolved,init,"" }
- checkedfiles[#checkedfiles+1]=data
- if helpers.trace then
- helpers.report("calling loadlib with '%s' with init '%s'",resolved,init)
- end
- local a,b,c=package.loadlib(resolved,init)
- if not a and type(b)=="string" then
- data[3]=string.fullstrip(b or "unknown error")
- end
- return a,b,c
-end
-helpers.loadedaslib=loadedaslib
-local function loadedbypath(name,rawname,paths,islib,what)
- local trace=helpers.trace
- for p=1,#paths do
- local path=paths[p]
- local resolved=filejoin(path,name)
- if trace then
- helpers.report("%s path, identifying '%s' on '%s'",what,name,path)
- end
- if isreadable(resolved) then
- if trace then
- helpers.report("%s path, '%s' found on '%s'",what,name,resolved)
- end
- if islib then
- return loadedaslib(resolved,rawname)
- else
- return loadfile(resolved)
- end
- end
- end
-end
-helpers.loadedbypath=loadedbypath
-local function loadedbyname(name,rawname)
- if find(name,"^/") or find(name,"^[a-zA-Z]:/") then
- local trace=helpers.trace
- if trace then
- helpers.report("qualified name, identifying '%s'",what,name)
- end
- if isreadable(name) then
- if trace then
- helpers.report("qualified name, '%s' found",what,name)
- end
- return loadfile(name)
- end
- end
-end
-helpers.loadedbyname=loadedbyname
-methods["reset loaded"]=function(name)
- checkedfiles={}
- return false
-end
-methods["already loaded"]=function(name)
- return package.loaded[name]
-end
-methods["preload table"]=function(name)
- local f=builtin["preload table"]
- if f then
- return f(name)
- end
-end
-methods["qualified path"]=function(name)
- return loadedbyname(addsuffix(lualibfile(name),"lua"),name)
-end
-methods["lua extra list"]=function(name)
- return loadedbypath(addsuffix(lualibfile(name),"lua"),name,getextraluapaths(),false,"lua")
-end
-methods["lib extra list"]=function(name)
- return loadedbypath(addsuffix(lualibfile(name),os.libsuffix),name,getextralibpaths(),true,"lib")
-end
-methods["path specification"]=function(name)
- local f=builtin["path specification"]
- if f then
- getluapaths()
- return f(name)
- end
-end
-methods["cpath specification"]=function(name)
- local f=builtin["cpath specification"]
- if f then
- getlibpaths()
- return f(name)
- end
-end
-methods["all in one fallback"]=function(name)
- local f=builtin["all in one fallback"]
- if f then
- return f(name)
- end
-end
-methods["not loaded"]=function(name)
- if helpers.trace then
- helpers.report("unable to locate '%s'",name or "?")
- for i=1,#checkedfiles do
- helpers.report("checked file '%s', initializer '%s', message '%s'",unpack(checkedfiles[i]))
- end
- end
- return nil
-end
-local level=0
-local used={}
-helpers.traceused=false
-function helpers.loaded(name)
- local sequence=helpers.sequence
- level=level+1
- for i=1,#sequence do
- local method=sequence[i]
- local lookup=method and methods[method]
- if type(lookup)=="function" then
- if helpers.trace then
- helpers.report("%s, level '%s', method '%s', name '%s'","locating",level,method,name)
- end
- local result,rest=lookup(name)
- if type(result)=="function" then
- if helpers.trace then
- helpers.report("%s, level '%s', method '%s', name '%s'","found",level,method,name)
- end
- if helpers.traceused then
- used[#used+1]={ level=level,name=name }
- end
- level=level-1
- return result,rest
- end
- end
- end
- level=level-1
- return nil
-end
-function helpers.showused()
- local n=#used
- if n>0 then
- helpers.report("%s libraries loaded:",n)
- helpers.report()
- for i=1,n do
- local u=used[i]
- helpers.report("%i %a",u.level,u.name)
- end
- helpers.report()
- end
-end
-function helpers.unload(name)
- if helpers.trace then
- if package.loaded[name] then
- helpers.report("unloading, name '%s', %s",name,"done")
- else
- helpers.report("unloading, name '%s', %s",name,"not loaded")
- end
- end
- package.loaded[name]=nil
-end
-table.insert(searchers,1,helpers.loaded)
-if context then
- package.path=""
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-lpeg"] = package.loaded["l-lpeg"] or true
-
--- original size: 38703, stripped down to: 19489
-
-if not modules then modules={} end modules ['l-lpeg']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-lpeg=require("lpeg")
-local lpeg=lpeg
-if not lpeg.print then function lpeg.print(...) print(lpeg.pcode(...)) end end
-local type,next,tostring=type,next,tostring
-local byte,char,gmatch,format=string.byte,string.char,string.gmatch,string.format
-local floor=math.floor
-local P,R,S,V,Ct,C,Cs,Cc,Cp,Cmt=lpeg.P,lpeg.R,lpeg.S,lpeg.V,lpeg.Ct,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Cp,lpeg.Cmt
-local lpegtype,lpegmatch,lpegprint=lpeg.type,lpeg.match,lpeg.print
-if setinspector then
- setinspector("lpeg",function(v) if lpegtype(v) then lpegprint(v) return true end end)
-end
-lpeg.patterns=lpeg.patterns or {}
-local patterns=lpeg.patterns
-local anything=P(1)
-local endofstring=P(-1)
-local alwaysmatched=P(true)
-patterns.anything=anything
-patterns.endofstring=endofstring
-patterns.beginofstring=alwaysmatched
-patterns.alwaysmatched=alwaysmatched
-local sign=S('+-')
-local zero=P('0')
-local digit=R('09')
-local digits=digit^1
-local octdigit=R("07")
-local octdigits=octdigit^1
-local lowercase=R("az")
-local uppercase=R("AZ")
-local underscore=P("_")
-local hexdigit=digit+lowercase+uppercase
-local hexdigits=hexdigit^1
-local cr,lf,crlf=P("\r"),P("\n"),P("\r\n")
-local newline=P("\r")*(P("\n")+P(true))+P("\n")
-local escaped=P("\\")*anything
-local squote=P("'")
-local dquote=P('"')
-local space=P(" ")
-local period=P(".")
-local comma=P(",")
-local utfbom_32_be=P('\000\000\254\255')
-local utfbom_32_le=P('\255\254\000\000')
-local utfbom_16_be=P('\254\255')
-local utfbom_16_le=P('\255\254')
-local utfbom_8=P('\239\187\191')
-local utfbom=utfbom_32_be+utfbom_32_le+utfbom_16_be+utfbom_16_le+utfbom_8
-local utftype=utfbom_32_be*Cc("utf-32-be")+utfbom_32_le*Cc("utf-32-le")+utfbom_16_be*Cc("utf-16-be")+utfbom_16_le*Cc("utf-16-le")+utfbom_8*Cc("utf-8")+alwaysmatched*Cc("utf-8")
-local utfstricttype=utfbom_32_be*Cc("utf-32-be")+utfbom_32_le*Cc("utf-32-le")+utfbom_16_be*Cc("utf-16-be")+utfbom_16_le*Cc("utf-16-le")+utfbom_8*Cc("utf-8")
-local utfoffset=utfbom_32_be*Cc(4)+utfbom_32_le*Cc(4)+utfbom_16_be*Cc(2)+utfbom_16_le*Cc(2)+utfbom_8*Cc(3)+Cc(0)
-local utf8next=R("\128\191")
-patterns.utfbom_32_be=utfbom_32_be
-patterns.utfbom_32_le=utfbom_32_le
-patterns.utfbom_16_be=utfbom_16_be
-patterns.utfbom_16_le=utfbom_16_le
-patterns.utfbom_8=utfbom_8
-patterns.utf_16_be_nl=P("\000\r\000\n")+P("\000\r")+P("\000\n")
-patterns.utf_16_le_nl=P("\r\000\n\000")+P("\r\000")+P("\n\000")
-patterns.utf_32_be_nl=P("\000\000\000\r\000\000\000\n")+P("\000\000\000\r")+P("\000\000\000\n")
-patterns.utf_32_le_nl=P("\r\000\000\000\n\000\000\000")+P("\r\000\000\000")+P("\n\000\000\000")
-patterns.utf8one=R("\000\127")
-patterns.utf8two=R("\194\223")*utf8next
-patterns.utf8three=R("\224\239")*utf8next*utf8next
-patterns.utf8four=R("\240\244")*utf8next*utf8next*utf8next
-patterns.utfbom=utfbom
-patterns.utftype=utftype
-patterns.utfstricttype=utfstricttype
-patterns.utfoffset=utfoffset
-local utf8char=patterns.utf8one+patterns.utf8two+patterns.utf8three+patterns.utf8four
-local validutf8char=utf8char^0*endofstring*Cc(true)+Cc(false)
-local utf8character=P(1)*R("\128\191")^0
-patterns.utf8=utf8char
-patterns.utf8char=utf8char
-patterns.utf8character=utf8character
-patterns.validutf8=validutf8char
-patterns.validutf8char=validutf8char
-local eol=S("\n\r")
-local spacer=S(" \t\f\v")
-local whitespace=eol+spacer
-local nonspacer=1-spacer
-local nonwhitespace=1-whitespace
-patterns.eol=eol
-patterns.spacer=spacer
-patterns.whitespace=whitespace
-patterns.nonspacer=nonspacer
-patterns.nonwhitespace=nonwhitespace
-local stripper=spacer^0*C((spacer^0*nonspacer^1)^0)
-local fullstripper=whitespace^0*C((whitespace^0*nonwhitespace^1)^0)
-local collapser=Cs(spacer^0/""*nonspacer^0*((spacer^0/" "*nonspacer^1)^0))
-local nospacer=Cs((whitespace^1/""+nonwhitespace^1)^0)
-local b_collapser=Cs(whitespace^0/""*(nonwhitespace^1+whitespace^1/" ")^0)
-local m_collapser=Cs((nonwhitespace^1+whitespace^1/" ")^0)
-local e_collapser=Cs((whitespace^1*endofstring/""+nonwhitespace^1+whitespace^1/" ")^0)
-local x_collapser=Cs((nonwhitespace^1+whitespace^1/"" )^0)
-local b_stripper=Cs(spacer^0/""*(nonspacer^1+spacer^1/" ")^0)
-local m_stripper=Cs((nonspacer^1+spacer^1/" ")^0)
-local e_stripper=Cs((spacer^1*endofstring/""+nonspacer^1+spacer^1/" ")^0)
-local x_stripper=Cs((nonspacer^1+spacer^1/"" )^0)
-patterns.stripper=stripper
-patterns.fullstripper=fullstripper
-patterns.collapser=collapser
-patterns.nospacer=nospacer
-patterns.b_collapser=b_collapser
-patterns.m_collapser=m_collapser
-patterns.e_collapser=e_collapser
-patterns.x_collapser=x_collapser
-patterns.b_stripper=b_stripper
-patterns.m_stripper=m_stripper
-patterns.e_stripper=e_stripper
-patterns.x_stripper=x_stripper
-patterns.lowercase=lowercase
-patterns.uppercase=uppercase
-patterns.letter=patterns.lowercase+patterns.uppercase
-patterns.space=space
-patterns.tab=P("\t")
-patterns.spaceortab=patterns.space+patterns.tab
-patterns.newline=newline
-patterns.emptyline=newline^1
-patterns.equal=P("=")
-patterns.comma=comma
-patterns.commaspacer=comma*spacer^0
-patterns.period=period
-patterns.colon=P(":")
-patterns.semicolon=P(";")
-patterns.underscore=underscore
-patterns.escaped=escaped
-patterns.squote=squote
-patterns.dquote=dquote
-patterns.nosquote=(escaped+(1-squote))^0
-patterns.nodquote=(escaped+(1-dquote))^0
-patterns.unsingle=(squote/"")*patterns.nosquote*(squote/"")
-patterns.undouble=(dquote/"")*patterns.nodquote*(dquote/"")
-patterns.unquoted=patterns.undouble+patterns.unsingle
-patterns.unspacer=((patterns.spacer^1)/"")^0
-patterns.singlequoted=squote*patterns.nosquote*squote
-patterns.doublequoted=dquote*patterns.nodquote*dquote
-patterns.quoted=patterns.doublequoted+patterns.singlequoted
-patterns.digit=digit
-patterns.digits=digits
-patterns.octdigit=octdigit
-patterns.octdigits=octdigits
-patterns.hexdigit=hexdigit
-patterns.hexdigits=hexdigits
-patterns.sign=sign
-patterns.cardinal=digits
-patterns.integer=sign^-1*digits
-patterns.unsigned=digit^0*period*digits
-patterns.float=sign^-1*patterns.unsigned
-patterns.cunsigned=digit^0*comma*digits
-patterns.cpunsigned=digit^0*(period+comma)*digits
-patterns.cfloat=sign^-1*patterns.cunsigned
-patterns.cpfloat=sign^-1*patterns.cpunsigned
-patterns.number=patterns.float+patterns.integer
-patterns.cnumber=patterns.cfloat+patterns.integer
-patterns.cpnumber=patterns.cpfloat+patterns.integer
-patterns.oct=zero*octdigits
-patterns.octal=patterns.oct
-patterns.HEX=zero*P("X")*(digit+uppercase)^1
-patterns.hex=zero*P("x")*(digit+lowercase)^1
-patterns.hexadecimal=zero*S("xX")*hexdigits
-patterns.hexafloat=sign^-1*zero*S("xX")*(hexdigit^0*period*hexdigits+hexdigits*period*hexdigit^0+hexdigits)*(S("pP")*sign^-1*hexdigits)^-1
-patterns.decafloat=sign^-1*(digit^0*period*digits+digits*period*digit^0+digits)*S("eE")*sign^-1*digits
-patterns.propername=(uppercase+lowercase+underscore)*(uppercase+lowercase+underscore+digit)^0*endofstring
-patterns.somecontent=(anything-newline-space)^1
-patterns.beginline=#(1-newline)
-patterns.longtostring=Cs(whitespace^0/""*((patterns.quoted+nonwhitespace^1+whitespace^1/""*(endofstring+Cc(" ")))^0))
-local function anywhere(pattern)
- return (1-P(pattern))^0*P(pattern)
-end
-lpeg.anywhere=anywhere
-function lpeg.instringchecker(p)
- p=anywhere(p)
- return function(str)
- return lpegmatch(p,str) and true or false
- end
-end
-function lpeg.splitter(pattern,action)
- if action then
- return (((1-P(pattern))^1)/action+1)^0
- else
- return (Cs((1-P(pattern))^1)+1)^0
- end
-end
-function lpeg.tsplitter(pattern,action)
- if action then
- return Ct((((1-P(pattern))^1)/action+1)^0)
- else
- return Ct((Cs((1-P(pattern))^1)+1)^0)
- end
-end
-local splitters_s,splitters_m,splitters_t={},{},{}
-local function splitat(separator,single)
- local splitter=(single and splitters_s[separator]) or splitters_m[separator]
- if not splitter then
- separator=P(separator)
- local other=C((1-separator)^0)
- if single then
- local any=anything
- splitter=other*(separator*C(any^0)+"")
- splitters_s[separator]=splitter
- else
- splitter=other*(separator*other)^0
- splitters_m[separator]=splitter
- end
- end
- return splitter
-end
-local function tsplitat(separator)
- local splitter=splitters_t[separator]
- if not splitter then
- splitter=Ct(splitat(separator))
- splitters_t[separator]=splitter
- end
- return splitter
-end
-lpeg.splitat=splitat
-lpeg.tsplitat=tsplitat
-function string.splitup(str,separator)
- if not separator then
- separator=","
- end
- return lpegmatch(splitters_m[separator] or splitat(separator),str)
-end
-local cache={}
-function lpeg.split(separator,str)
- local c=cache[separator]
- if not c then
- c=tsplitat(separator)
- cache[separator]=c
- end
- return lpegmatch(c,str)
-end
-function string.split(str,separator)
- if separator then
- local c=cache[separator]
- if not c then
- c=tsplitat(separator)
- cache[separator]=c
- end
- return lpegmatch(c,str)
- else
- return { str }
- end
-end
-local spacing=patterns.spacer^0*newline
-local empty=spacing*Cc("")
-local nonempty=Cs((1-spacing)^1)*spacing^-1
-local content=(empty+nonempty)^1
-patterns.textline=content
-local linesplitter=tsplitat(newline)
-patterns.linesplitter=linesplitter
-function string.splitlines(str)
- return lpegmatch(linesplitter,str)
-end
-local cache={}
-function lpeg.checkedsplit(separator,str)
- local c=cache[separator]
- if not c then
- separator=P(separator)
- local other=C((1-separator)^1)
- c=Ct(separator^0*other*(separator^1*other)^0)
- cache[separator]=c
- end
- return lpegmatch(c,str)
-end
-function string.checkedsplit(str,separator)
- local c=cache[separator]
- if not c then
- separator=P(separator)
- local other=C((1-separator)^1)
- c=Ct(separator^0*other*(separator^1*other)^0)
- cache[separator]=c
- end
- return lpegmatch(c,str)
-end
-local function f2(s) local c1,c2=byte(s,1,2) return c1*64+c2-12416 end
-local function f3(s) local c1,c2,c3=byte(s,1,3) return (c1*64+c2)*64+c3-925824 end
-local function f4(s) local c1,c2,c3,c4=byte(s,1,4) return ((c1*64+c2)*64+c3)*64+c4-63447168 end
-local utf8byte=patterns.utf8one/byte+patterns.utf8two/f2+patterns.utf8three/f3+patterns.utf8four/f4
-patterns.utf8byte=utf8byte
-local cache={}
-function lpeg.stripper(str)
- if type(str)=="string" then
- local s=cache[str]
- if not s then
- s=Cs(((S(str)^1)/""+1)^0)
- cache[str]=s
- end
- return s
- else
- return Cs(((str^1)/""+1)^0)
- end
-end
-local cache={}
-function lpeg.keeper(str)
- if type(str)=="string" then
- local s=cache[str]
- if not s then
- s=Cs((((1-S(str))^1)/""+1)^0)
- cache[str]=s
- end
- return s
- else
- return Cs((((1-str)^1)/""+1)^0)
- end
-end
-function lpeg.frontstripper(str)
- return (P(str)+P(true))*Cs(anything^0)
-end
-function lpeg.endstripper(str)
- return Cs((1-P(str)*endofstring)^0)
-end
-function lpeg.replacer(one,two,makefunction,isutf)
- local pattern
- local u=isutf and utf8char or 1
- if type(one)=="table" then
- local no=#one
- local p=P(false)
- if no==0 then
- for k,v in next,one do
- p=p+P(k)/v
- end
- pattern=Cs((p+u)^0)
- elseif no==1 then
- local o=one[1]
- one,two=P(o[1]),o[2]
- pattern=Cs((one/two+u)^0)
- else
- for i=1,no do
- local o=one[i]
- p=p+P(o[1])/o[2]
- end
- pattern=Cs((p+u)^0)
- end
- else
- pattern=Cs((P(one)/(two or "")+u)^0)
- end
- if makefunction then
- return function(str)
- return lpegmatch(pattern,str)
- end
- else
- return pattern
- end
-end
-function lpeg.finder(lst,makefunction,isutf)
- local pattern
- if type(lst)=="table" then
- pattern=P(false)
- if #lst==0 then
- for k,v in next,lst do
- pattern=pattern+P(k)
- end
- else
- for i=1,#lst do
- pattern=pattern+P(lst[i])
- end
- end
- else
- pattern=P(lst)
- end
- if isutf then
- pattern=((utf8char or 1)-pattern)^0*pattern
- else
- pattern=(1-pattern)^0*pattern
- end
- if makefunction then
- return function(str)
- return lpegmatch(pattern,str)
- end
- else
- return pattern
- end
-end
-local splitters_f,splitters_s={},{}
-function lpeg.firstofsplit(separator)
- local splitter=splitters_f[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=C((1-pattern)^0)
- splitters_f[separator]=splitter
- end
- return splitter
-end
-function lpeg.secondofsplit(separator)
- local splitter=splitters_s[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=(1-pattern)^0*pattern*C(anything^0)
- splitters_s[separator]=splitter
- end
- return splitter
-end
-local splitters_s,splitters_p={},{}
-function lpeg.beforesuffix(separator)
- local splitter=splitters_s[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=C((1-pattern)^0)*pattern*endofstring
- splitters_s[separator]=splitter
- end
- return splitter
-end
-function lpeg.afterprefix(separator)
- local splitter=splitters_p[separator]
- if not splitter then
- local pattern=P(separator)
- splitter=pattern*C(anything^0)
- splitters_p[separator]=splitter
- end
- return splitter
-end
-function lpeg.balancer(left,right)
- left,right=P(left),P(right)
- return P { left*((1-left-right)+V(1))^0*right }
-end
-function lpeg.counter(pattern,action)
- local n=0
- local pattern=(P(pattern)/function() n=n+1 end+anything)^0
- if action then
- return function(str) n=0;lpegmatch(pattern,str);action(n) end
- else
- return function(str) n=0;lpegmatch(pattern,str);return n end
- end
-end
-function lpeg.is_lpeg(p)
- return p and lpegtype(p)=="pattern"
-end
-function lpeg.oneof(list,...)
- if type(list)~="table" then
- list={ list,... }
- end
- local p=P(list[1])
- for l=2,#list do
- p=p+P(list[l])
- end
- return p
-end
-local sort=table.sort
-local function copyindexed(old)
- local new={}
- for i=1,#old do
- new[i]=old
- end
- return new
-end
-local function sortedkeys(tab)
- local keys,s={},0
- for key,_ in next,tab do
- s=s+1
- keys[s]=key
- end
- sort(keys)
- return keys
-end
-function lpeg.append(list,pp,delayed,checked)
- local p=pp
- if #list>0 then
- local keys=copyindexed(list)
- sort(keys)
- for i=#keys,1,-1 do
- local k=keys[i]
- if p then
- p=P(k)+p
- else
- p=P(k)
- end
- end
- elseif delayed then
- local keys=sortedkeys(list)
- if p then
- for i=1,#keys,1 do
- local k=keys[i]
- local v=list[k]
- p=P(k)/list+p
- end
- else
- for i=1,#keys do
- local k=keys[i]
- local v=list[k]
- if p then
- p=P(k)+p
- else
- p=P(k)
- end
- end
- if p then
- p=p/list
- end
- end
- elseif checked then
- local keys=sortedkeys(list)
- for i=1,#keys do
- local k=keys[i]
- local v=list[k]
- if p then
- if k==v then
- p=P(k)+p
- else
- p=P(k)/v+p
- end
- else
- if k==v then
- p=P(k)
- else
- p=P(k)/v
- end
- end
- end
- else
- local keys=sortedkeys(list)
- for i=1,#keys do
- local k=keys[i]
- local v=list[k]
- if p then
- p=P(k)/v+p
- else
- p=P(k)/v
- end
- end
- end
- return p
-end
-local p_false=P(false)
-local p_true=P(true)
-local lower=utf and utf.lower or string.lower
-local upper=utf and utf.upper or string.upper
-function lpeg.setutfcasers(l,u)
- lower=l or lower
- upper=u or upper
-end
-local function make1(t,rest)
- local p=p_false
- local keys=sortedkeys(t)
- for i=1,#keys do
- local k=keys[i]
- if k~="" then
- local v=t[k]
- if v==true then
- p=p+P(k)*p_true
- elseif v==false then
- else
- p=p+P(k)*make1(v,v[""])
- end
- end
- end
- if rest then
- p=p+p_true
- end
- return p
-end
-local function make2(t,rest)
- local p=p_false
- local keys=sortedkeys(t)
- for i=1,#keys do
- local k=keys[i]
- if k~="" then
- local v=t[k]
- if v==true then
- p=p+(P(lower(k))+P(upper(k)))*p_true
- elseif v==false then
- else
- p=p+(P(lower(k))+P(upper(k)))*make2(v,v[""])
- end
- end
- end
- if rest then
- p=p+p_true
- end
- return p
-end
-local function utfchartabletopattern(list,insensitive)
- local tree={}
- local n=#list
- if n==0 then
- for s in next,list do
- local t=tree
- local p,pk
- for c in gmatch(s,".") do
- if t==true then
- t={ [c]=true,[""]=true }
- p[pk]=t
- p=t
- t=false
- elseif t==false then
- t={ [c]=false }
- p[pk]=t
- p=t
- t=false
- else
- local tc=t[c]
- if not tc then
- tc=false
- t[c]=false
- end
- p=t
- t=tc
- end
- pk=c
- end
- if t==false then
- p[pk]=true
- elseif t==true then
- else
- t[""]=true
- end
- end
- else
- for i=1,n do
- local s=list[i]
- local t=tree
- local p,pk
- for c in gmatch(s,".") do
- if t==true then
- t={ [c]=true,[""]=true }
- p[pk]=t
- p=t
- t=false
- elseif t==false then
- t={ [c]=false }
- p[pk]=t
- p=t
- t=false
- else
- local tc=t[c]
- if not tc then
- tc=false
- t[c]=false
- end
- p=t
- t=tc
- end
- pk=c
- end
- if t==false then
- p[pk]=true
- elseif t==true then
- else
- t[""]=true
- end
- end
- end
- return (insensitive and make2 or make1)(tree)
-end
-lpeg.utfchartabletopattern=utfchartabletopattern
-function lpeg.utfreplacer(list,insensitive)
- local pattern=Cs((utfchartabletopattern(list,insensitive)/list+utf8character)^0)
- return function(str)
- return lpegmatch(pattern,str) or str
- end
-end
-patterns.containseol=lpeg.finder(eol)
-local function nextstep(n,step,result)
- local m=n%step
- local d=floor(n/step)
- if d>0 then
- local v=V(tostring(step))
- local s=result.start
- for i=1,d do
- if s then
- s=v*s
- else
- s=v
- end
- end
- result.start=s
- end
- if step>1 and result.start then
- local v=V(tostring(step/2))
- result[tostring(step)]=v*v
- end
- if step>0 then
- return nextstep(m,step/2,result)
- else
- return result
- end
-end
-function lpeg.times(pattern,n)
- return P(nextstep(n,2^16,{ "start",["1"]=pattern }))
-end
-do
- local trailingzeros=zero^0*-digit
- local stripper=Cs((
- digits*(
- period*trailingzeros/""+period*(digit-trailingzeros)^1*(trailingzeros/"")
- )+1
- )^0)
- lpeg.patterns.stripzeros=stripper
- local nonzero=digit-zero
- local trailingzeros=zero^1*endofstring
- local stripper=Cs((1-period)^0*(
- period*trailingzeros/""+period*(nonzero^1+(trailingzeros/"")+zero^1)^0+endofstring
- ))
- lpeg.patterns.stripzero=stripper
-end
-local byte_to_HEX={}
-local byte_to_hex={}
-local byte_to_dec={}
-local hex_to_byte={}
-for i=0,255 do
- local H=format("%02X",i)
- local h=format("%02x",i)
- local d=format("%03i",i)
- local c=char(i)
- byte_to_HEX[c]=H
- byte_to_hex[c]=h
- byte_to_dec[c]=d
- hex_to_byte[h]=c
- hex_to_byte[H]=c
-end
-local hextobyte=P(2)/hex_to_byte
-local bytetoHEX=P(1)/byte_to_HEX
-local bytetohex=P(1)/byte_to_hex
-local bytetodec=P(1)/byte_to_dec
-local hextobytes=Cs(hextobyte^0)
-local bytestoHEX=Cs(bytetoHEX^0)
-local bytestohex=Cs(bytetohex^0)
-local bytestodec=Cs(bytetodec^0)
-patterns.hextobyte=hextobyte
-patterns.bytetoHEX=bytetoHEX
-patterns.bytetohex=bytetohex
-patterns.bytetodec=bytetodec
-patterns.hextobytes=hextobytes
-patterns.bytestoHEX=bytestoHEX
-patterns.bytestohex=bytestohex
-patterns.bytestodec=bytestodec
-function string.toHEX(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(bytestoHEX,s)
- end
-end
-function string.tohex(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(bytestohex,s)
- end
-end
-function string.todec(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(bytestodec,s)
- end
-end
-function string.tobytes(s)
- if not s or s=="" then
- return s
- else
- return lpegmatch(hextobytes,s)
- end
-end
-local patterns={}
-local function containsws(what)
- local p=patterns[what]
- if not p then
- local p1=P(what)*(whitespace+endofstring)*Cc(true)
- local p2=whitespace*P(p1)
- p=P(p1)+P(1-p2)^0*p2+Cc(false)
- patterns[what]=p
- end
- return p
-end
-lpeg.containsws=containsws
-function string.containsws(str,what)
- return lpegmatch(patterns[what] or containsws(what),str)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-function"] = package.loaded["l-function"] or true
-
--- original size: 361, stripped down to: 317
-
-if not modules then modules={} end modules ['l-functions']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-functions=functions or {}
-function functions.dummy() end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-string"] = package.loaded["l-string"] or true
-
--- original size: 6644, stripped down to: 3410
-
-if not modules then modules={} end modules ['l-string']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local string=string
-local sub,gmatch,format,char,byte,rep,lower=string.sub,string.gmatch,string.format,string.char,string.byte,string.rep,string.lower
-local lpegmatch,patterns=lpeg.match,lpeg.patterns
-local P,S,C,Ct,Cc,Cs=lpeg.P,lpeg.S,lpeg.C,lpeg.Ct,lpeg.Cc,lpeg.Cs
-local unquoted=patterns.squote*C(patterns.nosquote)*patterns.squote+patterns.dquote*C(patterns.nodquote)*patterns.dquote
-function string.unquoted(str)
- return lpegmatch(unquoted,str) or str
-end
-function string.quoted(str)
- return format("%q",str)
-end
-function string.count(str,pattern)
- local n=0
- for _ in gmatch(str,pattern) do
- n=n+1
- end
- return n
-end
-function string.limit(str,n,sentinel)
- if #str>n then
- sentinel=sentinel or "..."
- return sub(str,1,(n-#sentinel))..sentinel
- else
- return str
- end
-end
-local stripper=patterns.stripper
-local fullstripper=patterns.fullstripper
-local collapser=patterns.collapser
-local nospacer=patterns.nospacer
-local longtostring=patterns.longtostring
-function string.strip(str)
- return str and lpegmatch(stripper,str) or ""
-end
-function string.fullstrip(str)
- return str and lpegmatch(fullstripper,str) or ""
-end
-function string.collapsespaces(str)
- return str and lpegmatch(collapser,str) or ""
-end
-function string.nospaces(str)
- return str and lpegmatch(nospacer,str) or ""
-end
-function string.longtostring(str)
- return str and lpegmatch(longtostring,str) or ""
-end
-local pattern=P(" ")^0*P(-1)
-function string.is_empty(str)
- if not str or str=="" then
- return true
- else
- return lpegmatch(pattern,str) and true or false
- end
-end
-local anything=patterns.anything
-local moreescapes=Cc("%")*S(".-+%?()[]*$^{}")
-local allescapes=Cc("%")*S(".-+%?()[]*")
-local someescapes=Cc("%")*S(".-+%()[]")
-local matchescapes=Cc(".")*S("*?")
-local pattern_m=Cs ((moreescapes+anything )^0 )
-local pattern_a=Cs ((allescapes+anything )^0 )
-local pattern_b=Cs ((someescapes+matchescapes+anything )^0 )
-local pattern_c=Cs (Cc("^")*(someescapes+matchescapes+anything )^0*Cc("$") )
-function string.escapedpattern(str,simple)
- return lpegmatch(simple and pattern_b or pattern_a,str)
-end
-function string.topattern(str,lowercase,strict)
- if str=="" or type(str)~="string" then
- return ".*"
- elseif strict=="all" then
- str=lpegmatch(pattern_m,str)
- elseif strict then
- str=lpegmatch(pattern_c,str)
- else
- str=lpegmatch(pattern_b,str)
- end
- if lowercase then
- return lower(str)
- else
- return str
- end
-end
-function string.valid(str,default)
- return (type(str)=="string" and str~="" and str) or default or nil
-end
-string.itself=function(s) return s end
-local pattern_c=Ct(C(1)^0)
-local pattern_b=Ct((C(1)/byte)^0)
-function string.totable(str,bytes)
- return lpegmatch(bytes and pattern_b or pattern_c,str)
-end
-local replacer=lpeg.replacer("@","%%")
-function string.tformat(fmt,...)
- return format(lpegmatch(replacer,fmt),...)
-end
-string.quote=string.quoted
-string.unquote=string.unquoted
-if not string.bytetable then
- local limit=5000
- function string.bytetable(str)
- local n=#str
- if n>limit then
- local t={ byte(str,1,limit) }
- for i=limit+1,n do
- t[i]=byte(str,i)
- end
- return t
- else
- return { byte(str,1,n) }
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-table"] = package.loaded["l-table"] or true
-
--- original size: 41758, stripped down to: 22643
-
-if not modules then modules={} end modules ['l-table']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,next,tostring,tonumber,select,rawget=type,next,tostring,tonumber,select,rawget
-local table,string=table,string
-local concat,sort=table.concat,table.sort
-local format,lower,dump=string.format,string.lower,string.dump
-local getmetatable,setmetatable=getmetatable,setmetatable
-local lpegmatch,patterns=lpeg.match,lpeg.patterns
-local floor=math.floor
-local stripper=patterns.stripper
-function table.getn(t)
- return t and #t
-end
-function table.strip(tab)
- local lst={}
- local l=0
- for i=1,#tab do
- local s=lpegmatch(stripper,tab[i]) or ""
- if s=="" then
- else
- l=l+1
- lst[l]=s
- end
- end
- return lst
-end
-function table.keys(t)
- if t then
- local keys={}
- local k=0
- for key in next,t do
- k=k+1
- keys[k]=key
- end
- return keys
- else
- return {}
- end
-end
-local function compare(a,b)
- local ta=type(a)
- if ta=="number" then
- local tb=type(b)
- if ta==tb then
- return a<b
- elseif tb=="string" then
- return tostring(a)<b
- end
- elseif ta=="string" then
- local tb=type(b)
- if ta==tb then
- return a<b
- else
- return a<tostring(b)
- end
- end
- return tostring(a)<tostring(b)
-end
-local function sortedkeys(tab)
- if tab then
- local srt={}
- local category=0
- local s=0
- for key in next,tab do
- s=s+1
- srt[s]=key
- if category~=3 then
- local tkey=type(key)
- if category==1 then
- if tkey~="string" then
- category=3
- end
- elseif category==2 then
- if tkey~="number" then
- category=3
- end
- else
- if tkey=="string" then
- category=1
- elseif tkey=="number" then
- category=2
- else
- category=3
- end
- end
- end
- end
- if s<2 then
- elseif category==3 then
- sort(srt,compare)
- else
- sort(srt)
- end
- return srt
- else
- return {}
- end
-end
-local function sortedhashonly(tab)
- if tab then
- local srt={}
- local s=0
- for key in next,tab do
- if type(key)=="string" then
- s=s+1
- srt[s]=key
- end
- end
- if s>1 then
- sort(srt)
- end
- return srt
- else
- return {}
- end
-end
-local function sortedindexonly(tab)
- if tab then
- local srt={}
- local s=0
- for key in next,tab do
- if type(key)=="number" then
- s=s+1
- srt[s]=key
- end
- end
- if s>1 then
- sort(srt)
- end
- return srt
- else
- return {}
- end
-end
-local function sortedhashkeys(tab,cmp)
- if tab then
- local srt={}
- local s=0
- for key in next,tab do
- if key then
- s=s+1
- srt[s]=key
- end
- end
- if s>1 then
- sort(srt,cmp)
- end
- return srt
- else
- return {}
- end
-end
-function table.allkeys(t)
- local keys={}
- for k,v in next,t do
- for k in next,v do
- keys[k]=true
- end
- end
- return sortedkeys(keys)
-end
-table.sortedkeys=sortedkeys
-table.sortedhashonly=sortedhashonly
-table.sortedindexonly=sortedindexonly
-table.sortedhashkeys=sortedhashkeys
-local function nothing() end
-local function sortedhash(t,cmp)
- if t then
- local s
- if cmp then
- s=sortedhashkeys(t,function(a,b) return cmp(t,a,b) end)
- else
- s=sortedkeys(t)
- end
- local m=#s
- if m==1 then
- return next,t
- elseif m>0 then
- local n=0
- return function()
- if n<m then
- n=n+1
- local k=s[n]
- return k,t[k]
- end
- end
- end
- end
- return nothing
-end
-table.sortedhash=sortedhash
-table.sortedpairs=sortedhash
-function table.append(t,list)
- local n=#t
- for i=1,#list do
- n=n+1
- t[n]=list[i]
- end
- return t
-end
-function table.prepend(t,list)
- local nl=#list
- local nt=nl+#t
- for i=#t,1,-1 do
- t[nt]=t[i]
- nt=nt-1
- end
- for i=1,#list do
- t[i]=list[i]
- end
- return t
-end
-function table.merge(t,...)
- if not t then
- t={}
- end
- for i=1,select("#",...) do
- for k,v in next,(select(i,...)) do
- t[k]=v
- end
- end
- return t
-end
-function table.merged(...)
- local t={}
- for i=1,select("#",...) do
- for k,v in next,(select(i,...)) do
- t[k]=v
- end
- end
- return t
-end
-function table.imerge(t,...)
- local nt=#t
- for i=1,select("#",...) do
- local nst=select(i,...)
- for j=1,#nst do
- nt=nt+1
- t[nt]=nst[j]
- end
- end
- return t
-end
-function table.imerged(...)
- local tmp={}
- local ntmp=0
- for i=1,select("#",...) do
- local nst=select(i,...)
- for j=1,#nst do
- ntmp=ntmp+1
- tmp[ntmp]=nst[j]
- end
- end
- return tmp
-end
-local function fastcopy(old,metatabletoo)
- if old then
- local new={}
- for k,v in next,old do
- if type(v)=="table" then
- new[k]=fastcopy(v,metatabletoo)
- else
- new[k]=v
- end
- end
- if metatabletoo then
- local mt=getmetatable(old)
- if mt then
- setmetatable(new,mt)
- end
- end
- return new
- else
- return {}
- end
-end
-local function copy(t,tables)
- if not tables then
- tables={}
- end
- local tcopy={}
- if not tables[t] then
- tables[t]=tcopy
- end
- for i,v in next,t do
- if type(i)=="table" then
- if tables[i] then
- i=tables[i]
- else
- i=copy(i,tables)
- end
- end
- if type(v)~="table" then
- tcopy[i]=v
- elseif tables[v] then
- tcopy[i]=tables[v]
- else
- tcopy[i]=copy(v,tables)
- end
- end
- local mt=getmetatable(t)
- if mt then
- setmetatable(tcopy,mt)
- end
- return tcopy
-end
-table.fastcopy=fastcopy
-table.copy=copy
-function table.derive(parent)
- local child={}
- if parent then
- setmetatable(child,{ __index=parent })
- end
- return child
-end
-function table.tohash(t,value)
- local h={}
- if t then
- if value==nil then value=true end
- for _,v in next,t do
- h[v]=value
- end
- end
- return h
-end
-function table.fromhash(t)
- local hsh={}
- local h=0
- for k,v in next,t do
- if v then
- h=h+1
- hsh[h]=k
- end
- end
- return hsh
-end
-local noquotes,hexify,handle,compact,inline,functions,metacheck,accurate
-local reserved=table.tohash {
- 'and','break','do','else','elseif','end','false','for','function','if',
- 'in','local','nil','not','or','repeat','return','then','true','until','while',
- 'NaN','goto','const',
-}
-local function is_simple_table(t,hexify,accurate)
- local nt=#t
- if nt>0 then
- local n=0
- for _,v in next,t do
- n=n+1
- if type(v)=="table" then
- return nil
- end
- end
- local haszero=rawget(t,0)
- if n==nt then
- local tt={}
- for i=1,nt do
- local v=t[i]
- local tv=type(v)
- if tv=="number" then
- if hexify then
- tt[i]=format("0x%X",v)
- elseif accurate then
- tt[i]=format("%q",v)
- else
- tt[i]=v
- end
- elseif tv=="string" then
- tt[i]=format("%q",v)
- elseif tv=="boolean" then
- tt[i]=v and "true" or "false"
- else
- return nil
- end
- end
- return tt
- elseif haszero and (n==nt+1) then
- local tt={}
- for i=0,nt do
- local v=t[i]
- local tv=type(v)
- if tv=="number" then
- if hexify then
- tt[i+1]=format("0x%X",v)
- elseif accurate then
- tt[i+1]=format("%q",v)
- else
- tt[i+1]=v
- end
- elseif tv=="string" then
- tt[i+1]=format("%q",v)
- elseif tv=="boolean" then
- tt[i+1]=v and "true" or "false"
- else
- return nil
- end
- end
- tt[1]="[0] = "..tt[1]
- return tt
- end
- end
- return nil
-end
-table.is_simple_table=is_simple_table
-local propername=patterns.propername
-local function dummy() end
-local function do_serialize(root,name,depth,level,indexed)
- if level>0 then
- depth=depth.." "
- if indexed then
- handle(format("%s{",depth))
- else
- local tn=type(name)
- if tn=="number" then
- if hexify then
- handle(format("%s[0x%X]={",depth,name))
- else
- handle(format("%s[%s]={",depth,name))
- end
- elseif tn=="string" then
- if noquotes and not reserved[name] and lpegmatch(propername,name) then
- handle(format("%s%s={",depth,name))
- else
- handle(format("%s[%q]={",depth,name))
- end
- elseif tn=="boolean" then
- handle(format("%s[%s]={",depth,name and "true" or "false"))
- else
- handle(format("%s{",depth))
- end
- end
- end
- if root and next(root)~=nil then
- local first=nil
- local last=0
- if compact then
- last=#root
- for k=1,last do
- if rawget(root,k)==nil then
- last=k-1
- break
- end
- end
- if last>0 then
- first=1
- end
- end
- local sk=sortedkeys(root)
- for i=1,#sk do
- local k=sk[i]
- local v=root[k]
- local tv=type(v)
- local tk=type(k)
- if compact and first and tk=="number" and k>=first and k<=last then
- if tv=="number" then
- if hexify then
- handle(format("%s 0x%X,",depth,v))
- elseif accurate then
- handle(format("%s %q,",depth,v))
- else
- handle(format("%s %s,",depth,v))
- end
- elseif tv=="string" then
- handle(format("%s %q,",depth,v))
- elseif tv=="table" then
- if next(v)==nil then
- handle(format("%s {},",depth))
- elseif inline then
- local st=is_simple_table(v,hexify,accurate)
- if st then
- handle(format("%s { %s },",depth,concat(st,", ")))
- else
- do_serialize(v,k,depth,level+1,true)
- end
- else
- do_serialize(v,k,depth,level+1,true)
- end
- elseif tv=="boolean" then
- handle(format("%s %s,",depth,v and "true" or "false"))
- elseif tv=="function" then
- if functions then
- handle(format('%s load(%q),',depth,dump(v)))
- else
- handle(format('%s "function",',depth))
- end
- else
- handle(format("%s %q,",depth,tostring(v)))
- end
- elseif k=="__p__" then
- if false then
- handle(format("%s __p__=nil,",depth))
- end
- elseif tv=="number" then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=0x%X,",depth,k,v))
- elseif accurate then
- handle(format("%s [%s]=%q,",depth,k,v))
- else
- handle(format("%s [%s]=%s,",depth,k,v))
- end
- elseif tk=="boolean" then
- if hexify then
- handle(format("%s [%s]=0x%X,",depth,k and "true" or "false",v))
- elseif accurate then
- handle(format("%s [%s]=%q,",depth,k and "true" or "false",v))
- else
- handle(format("%s [%s]=%s,",depth,k and "true" or "false",v))
- end
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- if hexify then
- handle(format("%s %s=0x%X,",depth,k,v))
- elseif accurate then
- handle(format("%s %s=%q,",depth,k,v))
- else
- handle(format("%s %s=%s,",depth,k,v))
- end
- else
- if hexify then
- handle(format("%s [%q]=0x%X,",depth,k,v))
- elseif accurate then
- handle(format("%s [%q]=%q,",depth,k,v))
- else
- handle(format("%s [%q]=%s,",depth,k,v))
- end
- end
- elseif tv=="string" then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=%q,",depth,k,v))
- elseif accurate then
- handle(format("%s [%q]=%q,",depth,k,v))
- else
- handle(format("%s [%s]=%q,",depth,k,v))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=%q,",depth,k and "true" or "false",v))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=%q,",depth,k,v))
- else
- handle(format("%s [%q]=%q,",depth,k,v))
- end
- elseif tv=="table" then
- if next(v)==nil then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]={},",depth,k))
- elseif accurate then
- handle(format("%s [%q]={},",depth,k))
- else
- handle(format("%s [%s]={},",depth,k))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]={},",depth,k and "true" or "false"))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s={},",depth,k))
- else
- handle(format("%s [%q]={},",depth,k))
- end
- elseif inline then
- local st=is_simple_table(v,hexify,accurate)
- if st then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]={ %s },",depth,k,concat(st,", ")))
- elseif accurate then
- handle(format("%s [%q]={ %s },",depth,k,concat(st,", ")))
- else
- handle(format("%s [%s]={ %s },",depth,k,concat(st,", ")))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]={ %s },",depth,k and "true" or "false",concat(st,", ")))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s={ %s },",depth,k,concat(st,", ")))
- else
- handle(format("%s [%q]={ %s },",depth,k,concat(st,", ")))
- end
- else
- do_serialize(v,k,depth,level+1)
- end
- else
- do_serialize(v,k,depth,level+1)
- end
- elseif tv=="boolean" then
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=%s,",depth,k,v and "true" or "false"))
- elseif accurate then
- handle(format("%s [%q]=%s,",depth,k,v and "true" or "false"))
- else
- handle(format("%s [%s]=%s,",depth,k,v and "true" or "false"))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=%s,",depth,tostring(k),v and "true" or "false"))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=%s,",depth,k,v and "true" or "false"))
- else
- handle(format("%s [%q]=%s,",depth,k,v and "true" or "false"))
- end
- elseif tv=="function" then
- if functions then
- local getinfo=debug and debug.getinfo
- if getinfo then
- local f=getinfo(v).what=="C" and dump(dummy) or dump(v)
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=load(%q),",depth,k,f))
- elseif accurate then
- handle(format("%s [%q]=load(%q),",depth,k,f))
- else
- handle(format("%s [%s]=load(%q),",depth,k,f))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=load(%q),",depth,k and "true" or "false",f))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=load(%q),",depth,k,f))
- else
- handle(format("%s [%q]=load(%q),",depth,k,f))
- end
- end
- end
- else
- if tk=="number" then
- if hexify then
- handle(format("%s [0x%X]=%q,",depth,k,tostring(v)))
- elseif accurate then
- handle(format("%s [%q]=%q,",depth,k,tostring(v)))
- else
- handle(format("%s [%s]=%q,",depth,k,tostring(v)))
- end
- elseif tk=="boolean" then
- handle(format("%s [%s]=%q,",depth,k and "true" or "false",tostring(v)))
- elseif tk~="string" then
- elseif noquotes and not reserved[k] and lpegmatch(propername,k) then
- handle(format("%s %s=%q,",depth,k,tostring(v)))
- else
- handle(format("%s [%q]=%q,",depth,k,tostring(v)))
- end
- end
- end
- end
- if level>0 then
- handle(format("%s},",depth))
- end
-end
-local function serialize(_handle,root,name,specification)
- local tname=type(name)
- if type(specification)=="table" then
- noquotes=specification.noquotes
- hexify=specification.hexify
- accurate=specification.accurate
- handle=_handle or specification.handle or print
- functions=specification.functions
- compact=specification.compact
- inline=specification.inline and compact
- metacheck=specification.metacheck
- if functions==nil then
- functions=true
- end
- if compact==nil then
- compact=true
- end
- if inline==nil then
- inline=compact
- end
- if metacheck==nil then
- metacheck=true
- end
- else
- noquotes=false
- hexify=false
- handle=_handle or print
- compact=true
- inline=true
- functions=true
- metacheck=true
- end
- if tname=="string" then
- if name=="return" then
- handle("return {")
- else
- handle(name.."={")
- end
- elseif tname=="number" then
- if hexify then
- handle(format("[0x%X]={",name))
- else
- handle("["..name.."]={")
- end
- elseif tname=="boolean" then
- if name then
- handle("return {")
- else
- handle("{")
- end
- else
- handle("t={")
- end
- if root then
- if metacheck and getmetatable(root) then
- local dummy=root._w_h_a_t_e_v_e_r_
- root._w_h_a_t_e_v_e_r_=nil
- end
- if next(root)~=nil then
- do_serialize(root,name,"",0)
- end
- end
- handle("}")
-end
-function table.serialize(root,name,specification)
- local t={}
- local n=0
- local function flush(s)
- n=n+1
- t[n]=s
- end
- serialize(flush,root,name,specification)
- return concat(t,"\n")
-end
-table.tohandle=serialize
-local maxtab=2*1024
-function table.tofile(filename,root,name,specification)
- local f=io.open(filename,'w')
- if f then
- if maxtab>1 then
- local t={}
- local n=0
- local function flush(s)
- n=n+1
- t[n]=s
- if n>maxtab then
- f:write(concat(t,"\n"),"\n")
- t={}
- n=0
- end
- end
- serialize(flush,root,name,specification)
- f:write(concat(t,"\n"),"\n")
- else
- local function flush(s)
- f:write(s,"\n")
- end
- serialize(flush,root,name,specification)
- end
- f:close()
- io.flush()
- end
-end
-local function flattened(t,f,depth)
- if f==nil then
- f={}
- depth=0xFFFF
- elseif tonumber(f) then
- depth=f
- f={}
- elseif not depth then
- depth=0xFFFF
- end
- for k,v in next,t do
- if type(k)~="number" then
- if depth>0 and type(v)=="table" then
- flattened(v,f,depth-1)
- else
- f[#f+1]=v
- end
- end
- end
- for k=1,#t do
- local v=t[k]
- if depth>0 and type(v)=="table" then
- flattened(v,f,depth-1)
- else
- f[#f+1]=v
- end
- end
- return f
-end
-table.flattened=flattened
-local function collapsed(t,f,h)
- if f==nil then
- f={}
- h={}
- end
- for k=1,#t do
- local v=t[k]
- if type(v)=="table" then
- collapsed(v,f,h)
- elseif not h[v] then
- f[#f+1]=v
- h[v]=true
- end
- end
- return f
-end
-local function collapsedhash(t,h)
- if h==nil then
- h={}
- end
- for k=1,#t do
- local v=t[k]
- if type(v)=="table" then
- collapsedhash(v,h)
- else
- h[v]=true
- end
- end
- return h
-end
-table.collapsed=collapsed
-table.collapsedhash=collapsedhash
-local function unnest(t,f)
- if not f then
- f={}
- end
- for i=1,#t do
- local v=t[i]
- if type(v)=="table" then
- if type(v[1])=="table" then
- unnest(v,f)
- else
- f[#f+1]=v
- end
- else
- f[#f+1]=v
- end
- end
- return f
-end
-function table.unnest(t)
- return unnest(t)
-end
-local function are_equal(a,b,n,m)
- if a==b then
- return true
- elseif a and b and #a==#b then
- if not n then
- n=1
- end
- if not m then
- m=#a
- end
- for i=n,m do
- local ai,bi=a[i],b[i]
- if ai==bi then
- elseif type(ai)=="table" and type(bi)=="table" then
- if not are_equal(ai,bi) then
- return false
- end
- else
- return false
- end
- end
- return true
- else
- return false
- end
-end
-local function identical(a,b)
- if a~=b then
- for ka,va in next,a do
- local vb=b[ka]
- if va==vb then
- elseif type(va)=="table" and type(vb)=="table" then
- if not identical(va,vb) then
- return false
- end
- else
- return false
- end
- end
- end
- return true
-end
-table.identical=identical
-table.are_equal=are_equal
-local function sparse(old,nest,keeptables)
- local new={}
- for k,v in next,old do
- if not (v=="" or v==false) then
- if nest and type(v)=="table" then
- v=sparse(v,nest)
- if keeptables or next(v)~=nil then
- new[k]=v
- end
- else
- new[k]=v
- end
- end
- end
- return new
-end
-table.sparse=sparse
-function table.compact(t)
- return sparse(t,true,true)
-end
-function table.contains(t,v)
- if t then
- for i=1,#t do
- if t[i]==v then
- return i
- end
- end
- end
- return false
-end
-function table.count(t)
- local n=0
- for k,v in next,t do
- n=n+1
- end
- return n
-end
-function table.swapped(t,s)
- local n={}
- if s then
- for k,v in next,s do
- n[k]=v
- end
- end
- for k,v in next,t do
- n[v]=k
- end
- return n
-end
-function table.hashed(t)
- for i=1,#t do
- t[t[i]]=i
- end
- return t
-end
-function table.mirrored(t)
- local n={}
- for k,v in next,t do
- n[v]=k
- n[k]=v
- end
- return n
-end
-function table.reversed(t)
- if t then
- local tt={}
- local tn=#t
- if tn>0 then
- local ttn=0
- for i=tn,1,-1 do
- ttn=ttn+1
- tt[ttn]=t[i]
- end
- end
- return tt
- end
-end
-function table.reverse(t)
- if t then
- local n=#t
- local m=n+1
- for i=1,floor(n/2) do
- local j=m-i
- t[i],t[j]=t[j],t[i]
- end
- return t
- end
-end
-local function sequenced(t,sep,simple)
- if not t then
- return ""
- elseif type(t)~="table" then
- return t
- end
- local n=#t
- local s={}
- if n>0 then
- for i=1,n do
- local v=t[i]
- if type(v)=="table" then
- s[i]="{"..sequenced(v,sep,simple).."}"
- else
- s[i]=tostring(t[i])
- end
- end
- else
- n=0
- for k,v in sortedhash(t) do
- if simple then
- if v==true then
- n=n+1
- s[n]=k
- elseif v and v~="" then
- n=n+1
- if type(v)=="table" then
- s[n]=k.."={"..sequenced(v,sep,simple).."}"
- else
- s[n]=k.."="..tostring(v)
- end
- end
- else
- n=n+1
- if type(v)=="table" then
- s[n]=k.."={"..sequenced(v,sep,simple).."}"
- else
- s[n]=k.."="..tostring(v)
- end
- end
- end
- end
- if sep==true then
- return "{ "..concat(s,", ").." }"
- else
- return concat(s,sep or " | ")
- end
-end
-table.sequenced=sequenced
-function table.print(t,...)
- if type(t)~="table" then
- print(tostring(t))
- else
- serialize(print,t,...)
- end
-end
-if setinspector then
- setinspector("table",function(v) if type(v)=="table" then serialize(print,v,"table") return true end end)
-end
-function table.sub(t,i,j)
- return { unpack(t,i,j) }
-end
-function table.is_empty(t)
- return not t or next(t)==nil
-end
-function table.has_one_entry(t)
- return t and next(t,next(t))==nil
-end
-function table.loweredkeys(t)
- local l={}
- for k,v in next,t do
- l[lower(k)]=v
- end
- return l
-end
-function table.unique(old)
- local hash={}
- local new={}
- local n=0
- for i=1,#old do
- local oi=old[i]
- if not hash[oi] then
- n=n+1
- new[n]=oi
- hash[oi]=true
- end
- end
- return new
-end
-function table.sorted(t,...)
- sort(t,...)
- return t
-end
-function table.values(t,s)
- if t then
- local values={}
- local keys={}
- local v=0
- for key,value in next,t do
- if not keys[value] then
- v=v+1
- values[v]=value
- keys[k]=key
- end
- end
- if s then
- sort(values)
- end
- return values
- else
- return {}
- end
-end
-function table.filtered(t,pattern,sort,cmp)
- if t and type(pattern)=="string" then
- if sort then
- local s
- if cmp then
- s=sortedhashkeys(t,function(a,b) return cmp(t,a,b) end)
- else
- s=sortedkeys(t)
- end
- local n=0
- local m=#s
- local function kv(s)
- while n<m do
- n=n+1
- local k=s[n]
- if find(k,pattern) then
- return k,t[k]
- end
- end
- end
- return kv,s
- else
- local n=next(t)
- local function iterator()
- while n~=nil do
- local k=n
- n=next(t,k)
- if find(k,pattern) then
- return k,t[k]
- end
- end
- end
- return iterator,t
- end
- else
- return nothing
- end
-end
-if not table.move then
- function table.move(a1,f,e,t,a2)
- if a2 and a1~=a2 then
- for i=f,e do
- a2[t]=a1[i]
- t=t+1
- end
- return a2
- else
- t=t+e-f
- for i=e,f,-1 do
- a1[t]=a1[i]
- t=t-1
- end
- return a1
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-io"] = package.loaded["l-io"] or true
-
--- original size: 11829, stripped down to: 6331
-
-if not modules then modules={} end modules ['l-io']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local io=io
-local open,flush,write,read=io.open,io.flush,io.write,io.read
-local byte,find,gsub,format=string.byte,string.find,string.gsub,string.format
-local concat=table.concat
-local type=type
-if string.find(os.getenv("PATH") or "",";",1,true) then
- io.fileseparator,io.pathseparator="\\",";"
-else
- io.fileseparator,io.pathseparator="/",":"
-end
-local large=0x01000000
-local medium=0x00100000
-local small=0x00020000
-local function readall(f)
- local size=f:seek("end")
- if size>0 then
- f:seek("set",0)
- return f:read(size)
- else
- return ""
- end
-end
-io.readall=readall
-function io.loaddata(filename,textmode)
- local f=open(filename,(textmode and 'r') or 'rb')
- if f then
- local size=f:seek("end")
- local data=nil
- if size>0 then
- f:seek("set",0)
- data=f:read(size)
- end
- f:close()
- return data
- end
-end
-function io.copydata(source,target,action)
- local f=open(source,"rb")
- if f then
- local g=open(target,"wb")
- if g then
- local size=f:seek("end")
- if size>0 then
- f:seek("set",0)
- local data=f:read(size)
- if action then
- data=action(data)
- end
- if data then
- g:write(data)
- end
- end
- g:close()
- end
- f:close()
- flush()
- end
-end
-function io.savedata(filename,data,joiner)
- local f=open(filename,"wb")
- if f then
- if type(data)=="table" then
- f:write(concat(data,joiner or ""))
- elseif type(data)=="function" then
- data(f)
- else
- f:write(data or "")
- end
- f:close()
- flush()
- return true
- else
- return false
- end
-end
-if fio and fio.readline then
- local readline=fio.readline
- function io.loadlines(filename,n)
- local f=open(filename,'r')
- if not f then
- elseif n then
- local lines={}
- for i=1,n do
- local line=readline(f)
- if line then
- lines[i]=line
- else
- break
- end
- end
- f:close()
- lines=concat(lines,"\n")
- if #lines>0 then
- return lines
- end
- else
- local line=readline(f)
- f:close()
- if line and #line>0 then
- return line
- end
- end
- end
-else
- function io.loadlines(filename,n)
- local f=open(filename,'r')
- if not f then
- elseif n then
- local lines={}
- for i=1,n do
- local line=f:read("*lines")
- if line then
- lines[i]=line
- else
- break
- end
- end
- f:close()
- lines=concat(lines,"\n")
- if #lines>0 then
- return lines
- end
- else
- local line=f:read("*line") or ""
- f:close()
- if #line>0 then
- return line
- end
- end
- end
-end
-function io.loadchunk(filename,n)
- local f=open(filename,'rb')
- if f then
- local data=f:read(n or 1024)
- f:close()
- if #data>0 then
- return data
- end
- end
-end
-function io.exists(filename)
- local f=open(filename)
- if f==nil then
- return false
- else
- f:close()
- return true
- end
-end
-function io.size(filename)
- local f=open(filename)
- if f==nil then
- return 0
- else
- local s=f:seek("end")
- f:close()
- return s
- end
-end
-local function noflines(f)
- if type(f)=="string" then
- local f=open(filename)
- if f then
- local n=f and noflines(f) or 0
- f:close()
- return n
- else
- return 0
- end
- else
- local n=0
- for _ in f:lines() do
- n=n+1
- end
- f:seek('set',0)
- return n
- end
-end
-io.noflines=noflines
-local nextchar={
- [ 4]=function(f)
- return f:read(1,1,1,1)
- end,
- [ 2]=function(f)
- return f:read(1,1)
- end,
- [ 1]=function(f)
- return f:read(1)
- end,
- [-2]=function(f)
- local a,b=f:read(1,1)
- return b,a
- end,
- [-4]=function(f)
- local a,b,c,d=f:read(1,1,1,1)
- return d,c,b,a
- end
-}
-function io.characters(f,n)
- if f then
- return nextchar[n or 1],f
- end
-end
-local nextbyte={
- [4]=function(f)
- local a,b,c,d=f:read(1,1,1,1)
- if d then
- return byte(a),byte(b),byte(c),byte(d)
- end
- end,
- [3]=function(f)
- local a,b,c=f:read(1,1,1)
- if b then
- return byte(a),byte(b),byte(c)
- end
- end,
- [2]=function(f)
- local a,b=f:read(1,1)
- if b then
- return byte(a),byte(b)
- end
- end,
- [1]=function (f)
- local a=f:read(1)
- if a then
- return byte(a)
- end
- end,
- [-2]=function (f)
- local a,b=f:read(1,1)
- if b then
- return byte(b),byte(a)
- end
- end,
- [-3]=function(f)
- local a,b,c=f:read(1,1,1)
- if b then
- return byte(c),byte(b),byte(a)
- end
- end,
- [-4]=function(f)
- local a,b,c,d=f:read(1,1,1,1)
- if d then
- return byte(d),byte(c),byte(b),byte(a)
- end
- end
-}
-function io.bytes(f,n)
- if f then
- return nextbyte[n or 1],f
- else
- return nil,nil
- end
-end
-function io.ask(question,default,options)
- while true do
- write(question)
- if options then
- write(format(" [%s]",concat(options,"|")))
- end
- if default then
- write(format(" [%s]",default))
- end
- write(format(" "))
- flush()
- local answer=read()
- answer=gsub(answer,"^%s*(.*)%s*$","%1")
- if answer=="" and default then
- return default
- elseif not options then
- return answer
- else
- for k=1,#options do
- if options[k]==answer then
- return answer
- end
- end
- local pattern="^"..answer
- for k=1,#options do
- local v=options[k]
- if find(v,pattern) then
- return v
- end
- end
- end
- end
-end
-local function readnumber(f,n,m)
- if m then
- f:seek("set",n)
- n=m
- end
- if n==1 then
- return byte(f:read(1))
- elseif n==2 then
- local a,b=byte(f:read(2),1,2)
- return 0x100*a+b
- elseif n==3 then
- local a,b,c=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
- elseif n==4 then
- local a,b,c,d=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
- elseif n==8 then
- local a,b=readnumber(f,4),readnumber(f,4)
- return 0x100*a+b
- elseif n==12 then
- local a,b,c=readnumber(f,4),readnumber(f,4),readnumber(f,4)
- return 0x10000*a+0x100*b+c
- elseif n==-2 then
- local b,a=byte(f:read(2),1,2)
- return 0x100*a+b
- elseif n==-3 then
- local c,b,a=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
- elseif n==-4 then
- local d,c,b,a=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
- elseif n==-8 then
- local h,g,f,e,d,c,b,a=byte(f:read(8),1,8)
- return 0x100000000000000*a+0x1000000000000*b+0x10000000000*c+0x100000000*d+0x1000000*e+0x10000*f+0x100*g+h
- else
- return 0
- end
-end
-io.readnumber=readnumber
-function io.readstring(f,n,m)
- if m then
- f:seek("set",n)
- n=m
- end
- local str=gsub(f:read(n),"\000","")
- return str
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-number"] = package.loaded["l-number"] or true
-
--- original size: 5720, stripped down to: 2176
-
-if not modules then modules={} end modules ['l-number']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local tostring,tonumber=tostring,tonumber
-local format,floor,match,rep=string.format,math.floor,string.match,string.rep
-local concat,insert=table.concat,table.insert
-local lpegmatch=lpeg.match
-local floor=math.floor
-number=number or {}
-local number=number
-if bit32 then
- local bextract=bit32.extract
- local t={
- "0","0","0","0","0","0","0","0",
- "0","0","0","0","0","0","0","0",
- "0","0","0","0","0","0","0","0",
- "0","0","0","0","0","0","0","0",
- }
- function number.tobitstring(b,m,w)
- if not w then
- w=32
- end
- local n=w
- for i=0,w-1 do
- local v=bextract(b,i)
- local k=w-i
- if v==1 then
- n=k
- t[k]="1"
- else
- t[k]="0"
- end
- end
- if w then
- return concat(t,"",1,w)
- elseif m then
- m=33-m*8
- if m<1 then
- m=1
- end
- return concat(t,"",1,m)
- elseif n<8 then
- return concat(t)
- elseif n<16 then
- return concat(t,"",9)
- elseif n<24 then
- return concat(t,"",17)
- else
- return concat(t,"",25)
- end
- end
-else
- function number.tobitstring(n,m)
- if n>0 then
- local t={}
- while n>0 do
- insert(t,1,n%2>0 and 1 or 0)
- n=floor(n/2)
- end
- local nn=8-#t%8
- if nn>0 and nn<8 then
- for i=1,nn do
- insert(t,1,0)
- end
- end
- if m then
- m=m*8-#t
- if m>0 then
- insert(t,1,rep("0",m))
- end
- end
- return concat(t)
- elseif m then
- rep("00000000",m)
- else
- return "00000000"
- end
- end
-end
-function number.valid(str,default)
- return tonumber(str) or default or nil
-end
-function number.toevenhex(n)
- local s=format("%X",n)
- if #s%2==0 then
- return s
- else
- return "0"..s
- end
-end
-function number.bytetodecimal(b)
- local d=floor(b*100/255+0.5)
- if d>100 then
- return 100
- elseif d<-100 then
- return -100
- else
- return d
- end
-end
-function number.decimaltobyte(d)
- local b=floor(d*255/100+0.5)
- if b>255 then
- return 255
- elseif b<-255 then
- return -255
- else
- return b
- end
-end
-function number.idiv(i,d)
- return floor(i/d)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-set"] = package.loaded["l-set"] or true
-
--- original size: 1923, stripped down to: 1044
-
-if not modules then modules={} end modules ['l-set']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-set=set or {}
-local nums={}
-local tabs={}
-local concat=table.concat
-local next,type=next,type
-set.create=table.tohash
-function set.tonumber(t)
- if next(t) then
- local s=""
- for k,v in next,t do
- if v then
- s=s.." "..k
- end
- end
- local n=nums[s]
- if not n then
- n=#tabs+1
- tabs[n]=t
- nums[s]=n
- end
- return n
- else
- return 0
- end
-end
-function set.totable(n)
- if n==0 then
- return {}
- else
- return tabs[n] or {}
- end
-end
-function set.tolist(n)
- if n==0 or not tabs[n] then
- return ""
- else
- local t,n={},0
- for k,v in next,tabs[n] do
- if v then
- n=n+1
- t[n]=k
- end
- end
- return concat(t," ")
- end
-end
-function set.contains(n,s)
- if type(n)=="table" then
- return n[s]
- elseif n==0 then
- return false
- else
- local t=tabs[n]
- return t and t[s]
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-os"] = package.loaded["l-os"] or true
-
--- original size: 19409, stripped down to: 10419
-
-if not modules then modules={} end modules ['l-os']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local os=os
-local date,time=os.date,os.time
-local find,format,gsub,upper,gmatch=string.find,string.format,string.gsub,string.upper,string.gmatch
-local concat=table.concat
-local random,ceil,randomseed=math.random,math.ceil,math.randomseed
-local type,setmetatable,tonumber,tostring=type,setmetatable,tonumber,tostring
-do
- local selfdir=os.selfdir
- if selfdir=="" then
- selfdir=nil
- end
- if not selfdir then
- if arg then
- for i=1,#arg do
- local a=arg[i]
- if find(a,"^%-%-[c:]*texmfbinpath=") then
- selfdir=gsub(a,"^.-=","")
- break
- end
- end
- end
- if not selfdir then
- selfdir=os.selfbin or "luatex"
- if find(selfdir,"[/\\]") then
- selfdir=gsub(selfdir,"[/\\][^/\\]*$","")
- elseif os.getenv then
- local path=os.getenv("PATH")
- local name=gsub(selfdir,"^.*[/\\][^/\\]","")
- local patt="[^:]+"
- if os.type=="windows" then
- patt="[^;]+"
- name=name..".exe"
- end
- local isfile
- if lfs then
- local attributes=lfs.attributes
- isfile=function(name)
- local a=attributes(name,"mode")
- return a=="file" or a=="link" or nil
- end
- else
- local open=io.open
- isfile=function(name)
- local f=open(name)
- if f then
- f:close()
- return true
- end
- end
- end
- for p in gmatch(path,patt) do
- if isfile(p.."/"..name) then
- selfdir=p
- break
- end
- end
- end
- end
- os.selfdir=selfdir or "."
- end
-end
-math.initialseed=tonumber(string.sub(string.reverse(tostring(ceil(socket and socket.gettime()*10000 or time()))),1,6))
-randomseed(math.initialseed)
-if not os.__getenv__ then
- os.__getenv__=os.getenv
- os.__setenv__=os.setenv
- if os.env then
- local osgetenv=os.getenv
- local ossetenv=os.setenv
- local osenv=os.env local _=osenv.PATH
- function os.setenv(k,v)
- if v==nil then
- v=""
- end
- local K=upper(k)
- osenv[K]=v
- if type(v)=="table" then
- v=concat(v,";")
- end
- ossetenv(K,v)
- end
- function os.getenv(k)
- local K=upper(k)
- local v=osenv[K] or osenv[k] or osgetenv(K) or osgetenv(k)
- if v=="" then
- return nil
- else
- return v
- end
- end
- else
- local ossetenv=os.setenv
- local osgetenv=os.getenv
- local osenv={}
- function os.setenv(k,v)
- if v==nil then
- v=""
- end
- local K=upper(k)
- osenv[K]=v
- end
- function os.getenv(k)
- local K=upper(k)
- local v=osenv[K] or osgetenv(K) or osgetenv(k)
- if v=="" then
- return nil
- else
- return v
- end
- end
- local function __index(t,k)
- return os.getenv(k)
- end
- local function __newindex(t,k,v)
- os.setenv(k,v)
- end
- os.env={}
- setmetatable(os.env,{ __index=__index,__newindex=__newindex } )
- end
-end
-local execute=os.execute
-local iopopen=io.popen
-local function resultof(command)
- local handle=iopopen(command,"r")
- if handle then
- local result=handle:read("*all") or ""
- handle:close()
- return result
- else
- return ""
- end
-end
-os.resultof=resultof
-function os.pipeto(command)
- return iopopen(command,"w")
-end
-if not io.fileseparator then
- if find(os.getenv("PATH"),";",1,true) then
- io.fileseparator,io.pathseparator,os.type="\\",";",os.type or "windows"
- else
- io.fileseparator,io.pathseparator,os.type="/",":",os.type or "unix"
- end
-end
-os.type=os.type or (io.pathseparator==";" and "windows") or "unix"
-os.name=os.name or (os.type=="windows" and "mswin" ) or "linux"
-if os.type=="windows" then
- os.libsuffix,os.binsuffix,os.binsuffixes='dll','exe',{ 'exe','cmd','bat' }
-else
- os.libsuffix,os.binsuffix,os.binsuffixes='so','',{ '' }
-end
-local launchers={
- windows="start %s",
- macosx="open %s",
- unix="xdg-open %s &> /dev/null &",
-}
-function os.launch(str)
- local command=format(launchers[os.name] or launchers.unix,str)
- execute(command)
-end
-local gettimeofday=os.gettimeofday or os.clock
-os.gettimeofday=gettimeofday
-local startuptime=gettimeofday()
-function os.runtime()
- return gettimeofday()-startuptime
-end
-local resolvers=os.resolvers or {}
-os.resolvers=resolvers
-setmetatable(os,{ __index=function(t,k)
- local r=resolvers[k]
- return r and r(t,k) or nil
-end })
-local name,platform=os.name or "linux",os.getenv("MTX_PLATFORM") or ""
-if platform~="" then
- os.platform=platform
-elseif os.type=="windows" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("PROCESSOR_ARCHITECTURE") or ""
- local platform=""
- if find(architecture,"AMD64",1,true) then
- platform="win64"
- else
- platform="mswin"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="linux" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("HOSTTYPE") or resultof("uname -m") or ""
- local platform=os.getenv("MTX_PLATFORM") or ""
- local musl=find(os.selfdir or "","linuxmusl")
- if platform~="" then
- elseif find(architecture,"x86_64",1,true) then
- platform=musl and "linuxmusl" or "linux-64"
- elseif find(architecture,"ppc",1,true) then
- platform="linux-ppc"
- else
- platform=musl and "linuxmusl" or "linux"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="macosx" then
- function resolvers.platform(t,k)
- local architecture=resultof("echo $HOSTTYPE") or ""
- local platform=""
- if architecture=="" then
- platform="osx-intel"
- elseif find(architecture,"i386",1,true) then
- platform="osx-intel"
- elseif find(architecture,"x86_64",1,true) then
- platform="osx-64"
- elseif find(architecture,"arm64",1,true) then
- platform="osx-64"
- else
- platform="osx-ppc"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="sunos" then
- function resolvers.platform(t,k)
- local architecture=resultof("uname -m") or ""
- local platform=""
- if find(architecture,"sparc",1,true) then
- platform="solaris-sparc"
- else
- platform="solaris-intel"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="freebsd" then
- function resolvers.platform(t,k)
- local architecture=resultof("uname -m") or ""
- local platform=""
- if find(architecture,"amd64",1,true) then
- platform="freebsd-amd64"
- else
- platform="freebsd"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-elseif name=="kfreebsd" then
- function resolvers.platform(t,k)
- local architecture=os.getenv("HOSTTYPE") or resultof("uname -m") or ""
- local platform=""
- if find(architecture,"x86_64",1,true) then
- platform="kfreebsd-amd64"
- else
- platform="kfreebsd-i386"
- end
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-else
- function resolvers.platform(t,k)
- local platform="linux"
- os.setenv("MTX_PLATFORM",platform)
- os.platform=platform
- return platform
- end
-end
-os.newline=name=="windows" and "\013\010" or "\010"
-function resolvers.bits(t,k)
- local bits=find(os.platform,"64",1,true) and 64 or 32
- os.bits=bits
- return bits
-end
-local t={ 8,9,"a","b" }
-function os.uuid()
- return format("%04x%04x-4%03x-%s%03x-%04x-%04x%04x%04x",
- random(0xFFFF),random(0xFFFF),
- random(0x0FFF),
- t[ceil(random(4))] or 8,random(0x0FFF),
- random(0xFFFF),
- random(0xFFFF),random(0xFFFF),random(0xFFFF)
- )
-end
-local d
-function os.timezone(delta)
- d=d or ((tonumber(date("%H")) or 0)-(tonumber(date("!%H")) or 0))
- if delta then
- if d>0 then
- return format("+%02i:00",d)
- else
- return format("-%02i:00",-d)
- end
- else
- return 1
- end
-end
-local timeformat=format("%%s%s",os.timezone(true))
-local dateformat="!%Y-%m-%d %H:%M:%S"
-local lasttime=nil
-local lastdate=nil
-function os.fulltime(t,default)
- t=t and tonumber(t) or 0
- if t>0 then
- elseif default then
- return default
- else
- t=time()
- end
- if t~=lasttime then
- lasttime=t
- lastdate=format(timeformat,date(dateformat))
- end
- return lastdate
-end
-local dateformat="%Y-%m-%d %H:%M:%S"
-local lasttime=nil
-local lastdate=nil
-function os.localtime(t,default)
- t=t and tonumber(t) or 0
- if t>0 then
- elseif default then
- return default
- else
- t=time()
- end
- if t~=lasttime then
- lasttime=t
- lastdate=date(dateformat,t)
- end
- return lastdate
-end
-function os.converttime(t,default)
- local t=tonumber(t)
- if t and t>0 then
- return date(dateformat,t)
- else
- return default or "-"
- end
-end
-local memory={}
-local function which(filename)
- local fullname=memory[filename]
- if fullname==nil then
- local suffix=file.suffix(filename)
- local suffixes=suffix=="" and os.binsuffixes or { suffix }
- for directory in gmatch(os.getenv("PATH"),"[^"..io.pathseparator.."]+") do
- local df=file.join(directory,filename)
- for i=1,#suffixes do
- local dfs=file.addsuffix(df,suffixes[i])
- if io.exists(dfs) then
- fullname=dfs
- break
- end
- end
- end
- if not fullname then
- fullname=false
- end
- memory[filename]=fullname
- end
- return fullname
-end
-os.which=which
-os.where=which
-function os.today()
- return date("!*t")
-end
-function os.now()
- return date("!%Y-%m-%d %H:%M:%S")
-end
-if not os.sleep then
- local socket=socket
- function os.sleep(n)
- if not socket then
- socket=require("socket")
- end
- socket.sleep(n)
- end
-end
-local function isleapyear(year)
- return (year%4==0) and (year%100~=0 or year%400==0)
-end
-os.isleapyear=isleapyear
-local days={ 31,28,31,30,31,30,31,31,30,31,30,31 }
-local function nofdays(year,month,day)
- if not month then
- return isleapyear(year) and 365 or 364
- elseif not day then
- return month==2 and isleapyear(year) and 29 or days[month]
- else
- for i=1,month-1 do
- day=day+days[i]
- end
- if month>2 and isleapyear(year) then
- day=day+1
- end
- return day
- end
-end
-os.nofdays=nofdays
-function os.weekday(day,month,year)
- return date("%w",time { year=year,month=month,day=day })+1
-end
-function os.validdate(year,month,day)
- if month<1 then
- month=1
- elseif month>12 then
- month=12
- end
- if day<1 then
- day=1
- else
- local max=nofdays(year,month)
- if day>max then
- day=max
- end
- end
- return year,month,day
-end
-function os.date(fmt,...)
- if not fmt then
- fmt="%Y-%m-%d %H:%M"
- end
- return date(fmt,...)
-end
-local osexit=os.exit
-local exitcode=nil
-function os.setexitcode(code)
- exitcode=code
-end
-function os.exit(c)
- if exitcode~=nil then
- return osexit(exitcode)
- end
- if c~=nil then
- return osexit(c)
- end
- return osexit()
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-file"] = package.loaded["l-file"] or true
-
--- original size: 22175, stripped down to: 10302
-
-if not modules then modules={} end modules ['l-file']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-file=file or {}
-local file=file
-if not lfs then
- lfs=optionalrequire("lfs")
-end
-local insert,concat=table.insert,table.concat
-local match,find,gmatch=string.match,string.find,string.gmatch
-local lpegmatch=lpeg.match
-local getcurrentdir,attributes=lfs.currentdir,lfs.attributes
-local checkedsplit=string.checkedsplit
-local P,R,S,C,Cs,Cp,Cc,Ct=lpeg.P,lpeg.R,lpeg.S,lpeg.C,lpeg.Cs,lpeg.Cp,lpeg.Cc,lpeg.Ct
-local attributes=lfs.attributes
-function lfs.isdir(name)
- if name then
- return attributes(name,"mode")=="directory"
- end
-end
-function lfs.isfile(name)
- if name then
- local a=attributes(name,"mode")
- return a=="file" or a=="link" or nil
- end
-end
-function lfs.isfound(name)
- if name then
- local a=attributes(name,"mode")
- return (a=="file" or a=="link") and name or nil
- end
-end
-function lfs.modification(name)
- return name and attributes(name,"modification") or nil
-end
-if sandbox then
- sandbox.redefine(lfs.isfile,"lfs.isfile")
- sandbox.redefine(lfs.isdir,"lfs.isdir")
- sandbox.redefine(lfs.isfound,"lfs.isfound")
-end
-local colon=P(":")
-local period=P(".")
-local periods=P("..")
-local fwslash=P("/")
-local bwslash=P("\\")
-local slashes=S("\\/")
-local noperiod=1-period
-local noslashes=1-slashes
-local name=noperiod^1
-local suffix=period/""*(1-period-slashes)^1*-1
-local pattern=C((1-(slashes^1*noslashes^1*-1))^1)*P(1)
-local function pathpart(name,default)
- return name and lpegmatch(pattern,name) or default or ""
-end
-local pattern=(noslashes^0*slashes)^1*C(noslashes^1)*-1
-local function basename(name)
- return name and lpegmatch(pattern,name) or name
-end
-local pattern=(noslashes^0*slashes^1)^0*Cs((1-suffix)^1)*suffix^0
-local function nameonly(name)
- return name and lpegmatch(pattern,name) or name
-end
-local pattern=(noslashes^0*slashes)^0*(noperiod^1*period)^1*C(noperiod^1)*-1
-local function suffixonly(name)
- return name and lpegmatch(pattern,name) or ""
-end
-local pattern=(noslashes^0*slashes)^0*noperiod^1*((period*C(noperiod^1))^1)*-1+Cc("")
-local function suffixesonly(name)
- if name then
- return lpegmatch(pattern,name)
- else
- return ""
- end
-end
-file.pathpart=pathpart
-file.basename=basename
-file.nameonly=nameonly
-file.suffixonly=suffixonly
-file.suffix=suffixonly
-file.suffixesonly=suffixesonly
-file.suffixes=suffixesonly
-file.dirname=pathpart
-file.extname=suffixonly
-local drive=C(R("az","AZ"))*colon
-local path=C((noslashes^0*slashes)^0)
-local suffix=period*C(P(1-period)^0*P(-1))
-local base=C((1-suffix)^0)
-local rest=C(P(1)^0)
-drive=drive+Cc("")
-path=path+Cc("")
-base=base+Cc("")
-suffix=suffix+Cc("")
-local pattern_a=drive*path*base*suffix
-local pattern_b=path*base*suffix
-local pattern_c=C(drive*path)*C(base*suffix)
-local pattern_d=path*rest
-function file.splitname(str,splitdrive)
- if not str then
- elseif splitdrive then
- return lpegmatch(pattern_a,str)
- else
- return lpegmatch(pattern_b,str)
- end
-end
-function file.splitbase(str)
- if str then
- return lpegmatch(pattern_d,str)
- else
- return "",str
- end
-end
-function file.nametotable(str,splitdrive)
- if str then
- local path,drive,subpath,name,base,suffix=lpegmatch(pattern_c,str)
- if splitdrive then
- return {
- path=path,
- drive=drive,
- subpath=subpath,
- name=name,
- base=base,
- suffix=suffix,
- }
- else
- return {
- path=path,
- name=name,
- base=base,
- suffix=suffix,
- }
- end
- end
-end
-local pattern=Cs(((period*(1-period-slashes)^1*-1)/""+1)^1)
-function file.removesuffix(name)
- return name and lpegmatch(pattern,name)
-end
-local suffix=period/""*(1-period-slashes)^1*-1
-local pattern=Cs((noslashes^0*slashes^1)^0*((1-suffix)^1))*Cs(suffix)
-function file.addsuffix(filename,suffix,criterium)
- if not filename or not suffix or suffix=="" then
- return filename
- elseif criterium==true then
- return filename.."."..suffix
- elseif not criterium then
- local n,s=lpegmatch(pattern,filename)
- if not s or s=="" then
- return filename.."."..suffix
- else
- return filename
- end
- else
- local n,s=lpegmatch(pattern,filename)
- if s and s~="" then
- local t=type(criterium)
- if t=="table" then
- for i=1,#criterium do
- if s==criterium[i] then
- return filename
- end
- end
- elseif t=="string" then
- if s==criterium then
- return filename
- end
- end
- end
- return (n or filename).."."..suffix
- end
-end
-local suffix=period*(1-period-slashes)^1*-1
-local pattern=Cs((1-suffix)^0)
-function file.replacesuffix(name,suffix)
- if name and suffix and suffix~="" then
- return lpegmatch(pattern,name).."."..suffix
- else
- return name
- end
-end
-local reslasher=lpeg.replacer(P("\\"),"/")
-function file.reslash(str)
- return str and lpegmatch(reslasher,str)
-end
-if lfs.isreadablefile and lfs.iswritablefile then
- file.is_readable=lfs.isreadablefile
- file.is_writable=lfs.iswritablefile
-else
- function file.is_writable(name)
- if not name then
- elseif lfs.isdir(name) then
- name=name.."/m_t_x_t_e_s_t.tmp"
- local f=io.open(name,"wb")
- if f then
- f:close()
- os.remove(name)
- return true
- end
- elseif lfs.isfile(name) then
- local f=io.open(name,"ab")
- if f then
- f:close()
- return true
- end
- else
- local f=io.open(name,"ab")
- if f then
- f:close()
- os.remove(name)
- return true
- end
- end
- return false
- end
- local readable=P("r")*Cc(true)
- function file.is_readable(name)
- if name then
- local a=attributes(name)
- return a and lpegmatch(readable,a.permissions) or false
- else
- return false
- end
- end
-end
-file.isreadable=file.is_readable
-file.iswritable=file.is_writable
-function file.size(name)
- if name then
- local a=attributes(name)
- return a and a.size or 0
- else
- return 0
- end
-end
-function file.splitpath(str,separator)
- return str and checkedsplit(lpegmatch(reslasher,str),separator or io.pathseparator)
-end
-function file.joinpath(tab,separator)
- return tab and concat(tab,separator or io.pathseparator)
-end
-local someslash=S("\\/")
-local stripper=Cs(P(fwslash)^0/""*reslasher)
-local isnetwork=someslash*someslash*(1-someslash)+(1-fwslash-colon)^1*colon
-local isroot=fwslash^1*-1
-local hasroot=fwslash^1
-local reslasher=lpeg.replacer(S("\\/"),"/")
-local deslasher=lpeg.replacer(S("\\/")^1,"/")
-function file.join(one,two,three,...)
- if not two then
- return one=="" and one or lpegmatch(reslasher,one)
- end
- if one=="" then
- return lpegmatch(stripper,three and concat({ two,three,... },"/") or two)
- end
- if lpegmatch(isnetwork,one) then
- local one=lpegmatch(reslasher,one)
- local two=lpegmatch(deslasher,three and concat({ two,three,... },"/") or two)
- if lpegmatch(hasroot,two) then
- return one..two
- else
- return one.."/"..two
- end
- elseif lpegmatch(isroot,one) then
- local two=lpegmatch(deslasher,three and concat({ two,three,... },"/") or two)
- if lpegmatch(hasroot,two) then
- return two
- else
- return "/"..two
- end
- else
- return lpegmatch(deslasher,concat({ one,two,three,... },"/"))
- end
-end
-local drivespec=R("az","AZ")^1*colon
-local anchors=fwslash+drivespec
-local untouched=periods+(1-period)^1*P(-1)
-local mswindrive=Cs(drivespec*(bwslash/"/"+fwslash)^0)
-local mswinuncpath=(bwslash+fwslash)*(bwslash+fwslash)*Cc("//")
-local splitstarter=(mswindrive+mswinuncpath+Cc(false))*Ct(lpeg.splitat(S("/\\")^1))
-local absolute=fwslash
-function file.collapsepath(str,anchor)
- if not str then
- return
- end
- if anchor==true and not lpegmatch(anchors,str) then
- str=getcurrentdir().."/"..str
- end
- if str=="" or str=="." then
- return "."
- elseif lpegmatch(untouched,str) then
- return lpegmatch(reslasher,str)
- end
- local starter,oldelements=lpegmatch(splitstarter,str)
- local newelements={}
- local i=#oldelements
- while i>0 do
- local element=oldelements[i]
- if element=='.' then
- elseif element=='..' then
- local n=i-1
- while n>0 do
- local element=oldelements[n]
- if element~='..' and element~='.' then
- oldelements[n]='.'
- break
- else
- n=n-1
- end
- end
- if n<1 then
- insert(newelements,1,'..')
- end
- elseif element~="" then
- insert(newelements,1,element)
- end
- i=i-1
- end
- if #newelements==0 then
- return starter or "."
- elseif starter then
- return starter..concat(newelements,'/')
- elseif lpegmatch(absolute,str) then
- return "/"..concat(newelements,'/')
- else
- newelements=concat(newelements,'/')
- if anchor=="." and find(str,"^%./") then
- return "./"..newelements
- else
- return newelements
- end
- end
-end
-local validchars=R("az","09","AZ","--","..")
-local pattern_a=lpeg.replacer(1-validchars)
-local pattern_a=Cs((validchars+P(1)/"-")^1)
-local whatever=P("-")^0/""
-local pattern_b=Cs(whatever*(1-whatever*-1)^1)
-function file.robustname(str,strict)
- if str then
- str=lpegmatch(pattern_a,str) or str
- if strict then
- return lpegmatch(pattern_b,str) or str
- else
- return str
- end
- end
-end
-local loaddata=io.loaddata
-local savedata=io.savedata
-file.readdata=loaddata
-file.savedata=savedata
-function file.copy(oldname,newname)
- if oldname and newname then
- local data=loaddata(oldname)
- if data and data~="" then
- savedata(newname,data)
- end
- end
-end
-local letter=R("az","AZ")+S("_-+")
-local separator=P("://")
-local qualified=period^0*fwslash+letter*colon+letter^1*separator+letter^1*fwslash
-local rootbased=fwslash+letter*colon
-lpeg.patterns.qualified=qualified
-lpeg.patterns.rootbased=rootbased
-function file.is_qualified_path(filename)
- return filename and lpegmatch(qualified,filename)~=nil
-end
-function file.is_rootbased_path(filename)
- return filename and lpegmatch(rootbased,filename)~=nil
-end
-function file.strip(name,dir)
- if name then
- local b,a=match(name,"^(.-)"..dir.."(.*)$")
- return a~="" and a or name
- end
-end
-function lfs.mkdirs(path)
- local full=""
- for sub in gmatch(path,"(/*[^\\/]+)") do
- full=full..sub
- lfs.mkdir(full)
- end
-end
-function file.withinbase(path)
- local l=0
- if not find(path,"^/") then
- path="/"..path
- end
- for dir in gmatch(path,"/([^/]+)") do
- if dir==".." then
- l=l-1
- elseif dir~="." then
- l=l+1
- end
- if l<0 then
- return false
- end
- end
- return true
-end
-local symlinkattributes=lfs.symlinkattributes
-function lfs.readlink(name)
- return symlinkattributes(name,"target") or nil
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-gzip"] = package.loaded["l-gzip"] or true
-
--- original size: 5115, stripped down to: 1699
-
-if not modules then modules={} end modules ['l-gzip']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-gzip=gzip or {}
-if not zlib then
- zlib=xzip
-elseif not xzip then
- xzip=zlib
-end
-if zlib then
- local suffix=file.suffix
- local suffixes=file.suffixes
- local find=string.find
- local openfile=io.open
- local gzipwindow=15+16
- local gziplevel=3
- local identifier="^\x1F\x8B\x08"
- local compress=zlib.compress
- local decompress=zlib.decompress
- function gzip.load(filename)
- local f=openfile(filename,"rb")
- if not f then
- else
- local data=f:read("*all")
- f:close()
- if data and data~="" then
- if suffix(filename)=="gz" then
- data=decompress(data,gzipwindow)
- end
- return data
- end
- end
- end
- function gzip.save(filename,data,level)
- if suffix(filename)~="gz" then
- filename=filename..".gz"
- end
- local f=openfile(filename,"wb")
- if f then
- data=compress(data or "",level or gziplevel,nil,gzipwindow)
- f:write(data)
- f:close()
- return #data
- end
- end
- function gzip.suffix(filename)
- local suffix,extra=suffixes(filename)
- local gzipped=extra=="gz"
- return suffix,gzipped
- end
- function gzip.compressed(s)
- return s and find(s,identifier)
- end
- function gzip.compress(s,level)
- if s and not find(s,identifier) then
- if not level then
- level=gziplevel
- elseif level<=0 then
- return s
- elseif level>9 then
- level=9
- end
- return compress(s,level or gziplevel,nil,gzipwindow) or s
- end
- end
- function gzip.decompress(s)
- if s and find(s,identifier) then
- return decompress(s,gzipwindow)
- else
- return s
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-md5"] = package.loaded["l-md5"] or true
-
--- original size: 3414, stripped down to: 2307
-
-if not modules then modules={} end modules ['l-md5']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if not md5 then
- md5=optionalrequire("md5")
-end
-if not md5 then
- md5={
- sum=function(str) print("error: md5 is not loaded (sum ignored)") return str end,
- sumhexa=function(str) print("error: md5 is not loaded (sumhexa ignored)") return str end,
- }
-end
-local md5,file=md5,file
-local gsub=string.gsub
-local modification,isfile,touch=lfs.modification,lfs.isfile,lfs.touch
-local loaddata,savedata=io.loaddata,io.savedata
-do
- local patterns=lpeg and lpeg.patterns
- if patterns then
- local bytestoHEX=patterns.bytestoHEX
- local bytestohex=patterns.bytestohex
- local bytestodec=patterns.bytestodec
- local lpegmatch=lpeg.match
- local md5sum=md5.sum
- if not md5.HEX then function md5.HEX(str) if str then return lpegmatch(bytestoHEX,md5sum(str)) end end end
- if not md5.hex then function md5.hex(str) if str then return lpegmatch(bytestohex,md5sum(str)) end end end
- if not md5.dec then function md5.dec(str) if str then return lpegmatch(bytestodec,md5sum(str)) end end end
- md5.sumhexa=md5.hex
- md5.sumHEXA=md5.HEX
- end
-end
-local md5HEX=md5.HEX
-function file.needsupdating(oldname,newname,threshold)
- local oldtime=modification(oldname)
- if oldtime then
- local newtime=modification(newname)
- if not newtime then
- return true
- elseif newtime>=oldtime then
- return false
- elseif oldtime-newtime<(threshold or 1) then
- return false
- else
- return true
- end
- else
- return false
- end
-end
-file.needs_updating=file.needsupdating
-function file.syncmtimes(oldname,newname)
- local oldtime=modification(oldname)
- if oldtime and isfile(newname) then
- touch(newname,oldtime,oldtime)
- end
-end
-local function checksum(name)
- if md5 then
- local data=loaddata(name)
- if data then
- return md5HEX(data)
- end
- end
- return nil
-end
-file.checksum=checksum
-function file.loadchecksum(name)
- if md5 then
- local data=loaddata(name..".md5")
- return data and (gsub(data,"%s",""))
- end
- return nil
-end
-function file.savechecksum(name,checksum)
- if not checksum then checksum=checksum(name) end
- if checksum then
- savedata(name..".md5",checksum)
- return checksum
- end
- return nil
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-sha"] = package.loaded["l-sha"] or true
-
--- original size: 1085, stripped down to: 969
-
-if not modules then modules={} end modules ['l-sha']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if sha2 then
- local lpegmatch=lpeg.match
- local lpegpatterns=lpeg.patterns
- local bytestohex=lpegpatterns.bytestohex
- local bytestoHEX=lpegpatterns.bytestoHEX
- local digest256=sha2.digest256
- local digest384=sha2.digest384
- local digest512=sha2.digest512
- sha2.hash256=function(str) return lpegmatch(bytestohex,digest256(str)) end
- sha2.hash384=function(str) return lpegmatch(bytestohex,digest384(str)) end
- sha2.hash512=function(str) return lpegmatch(bytestohex,digest512(str)) end
- sha2.HASH256=function(str) return lpegmatch(bytestoHEX,digest256(str)) end
- sha2.HASH384=function(str) return lpegmatch(bytestoHEX,digest384(str)) end
- sha2.HASH512=function(str) return lpegmatch(bytestoHEX,digest512(str)) end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-url"] = package.loaded["l-url"] or true
-
--- original size: 14755, stripped down to: 6981
-
-if not modules then modules={} end modules ['l-url']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local char,format,byte=string.char,string.format,string.byte
-local concat=table.concat
-local tonumber,type,next=tonumber,type,next
-local P,C,R,S,Cs,Cc,Ct,Cf,Cg,V=lpeg.P,lpeg.C,lpeg.R,lpeg.S,lpeg.Cs,lpeg.Cc,lpeg.Ct,lpeg.Cf,lpeg.Cg,lpeg.V
-local lpegmatch,lpegpatterns,replacer=lpeg.match,lpeg.patterns,lpeg.replacer
-local sortedhash=table.sortedhash
-url=url or {}
-local url=url
-local unescapes={}
-local escapes={}
-setmetatable(unescapes,{ __index=function(t,k)
- local v=char(tonumber(k,16))
- t[k]=v
- return v
-end })
-setmetatable(escapes,{ __index=function(t,k)
- local v=format("%%%02X",byte(k))
- t[k]=v
- return v
-end })
-local colon=P(":")
-local qmark=P("?")
-local hash=P("#")
-local slash=P("/")
-local atsign=P("@")
-local percent=P("%")
-local endofstring=P(-1)
-local hexdigit=R("09","AF","af")
-local plus=P("+")
-local nothing=Cc("")
-local okay=R("09","AZ","az")+S("-_.,:=+*~!'()@&$")
-local escapedchar=(percent*C(hexdigit*hexdigit))/unescapes
-local unescapedchar=P(1)/escapes
-local escaped=(plus/" ")+escapedchar
-local noslash=P("/")/""
-local plustospace=P("+")/" "
-local decoder=Cs((
- plustospace+escapedchar+P("\r\n")/"\n"+P(1)
- )^0 )
-local encoder=Cs((
- R("09","AZ","az")^1+S("-./_")^1+P(" ")/"+"+P("\n")/"\r\n"+unescapedchar
- )^0 )
-lpegpatterns.urldecoder=decoder
-lpegpatterns.urlencoder=encoder
-function url.decode (str) return str and lpegmatch(decoder,str) or str end
-function url.encode (str) return str and lpegmatch(encoder,str) or str end
-function url.unescape(str) return str and lpegmatch(unescaper,str) or str end
-local schemestr=Cs((escaped+(1-colon-slash-qmark-hash))^2)
-local authoritystr=Cs((escaped+(1- slash-qmark-hash))^0)
-local pathstr=Cs((escaped+(1- qmark-hash))^0)
-local querystr=Cs(((1- hash))^0)
-local fragmentstr=Cs((escaped+(1- endofstring))^0)
-local scheme=schemestr*colon+nothing
-local authority=slash*slash*authoritystr+nothing
-local path=slash*pathstr+nothing
-local query=qmark*querystr+nothing
-local fragment=hash*fragmentstr+nothing
-local validurl=scheme*authority*path*query*fragment
-local parser=Ct(validurl)
-lpegpatterns.url=validurl
-lpegpatterns.urlsplitter=parser
-local escaper=Cs((R("09","AZ","az")^1+P(" ")/"%%20"+S("-./_:")^1+P(1)/escapes)^0)
-local unescaper=Cs((escapedchar+1)^0)
-local getcleaner=Cs((P("+++")/"%%2B"+P("+")/"%%20"+P(1))^1)
-lpegpatterns.urlunescaped=escapedchar
-lpegpatterns.urlescaper=escaper
-lpegpatterns.urlunescaper=unescaper
-lpegpatterns.urlgetcleaner=getcleaner
-function url.unescapeget(str)
- return lpegmatch(getcleaner,str)
-end
-local function split(str)
- return (type(str)=="string" and lpegmatch(parser,str)) or str
-end
-local isscheme=schemestr*colon*slash*slash
-local function hasscheme(str)
- if str then
- local scheme=lpegmatch(isscheme,str)
- return scheme~="" and scheme or false
- else
- return false
- end
-end
-local rootletter=R("az","AZ")+S("_-+")
-local separator=P("://")
-local qualified=P(".")^0*P("/")+rootletter*P(":")+rootletter^1*separator+rootletter^1*P("/")
-local rootbased=P("/")+rootletter*P(":")
-local barswapper=replacer("|",":")
-local backslashswapper=replacer("\\","/")
-local equal=P("=")
-local amp=P("&")
-local key=Cs(((plustospace+escapedchar+1)-equal )^0)
-local value=Cs(((plustospace+escapedchar+1)-amp-endofstring)^0)
-local splitquery=Cf (Ct("")*P { "sequence",
- sequence=V("pair")*(amp*V("pair"))^0,
- pair=Cg(key*equal*value),
-},rawset)
-local userpart=(1-atsign-colon)^1
-local serverpart=(1-colon)^1
-local splitauthority=((Cs(userpart)*colon*Cs(userpart)+Cs(userpart)*Cc(nil))*atsign+Cc(nil)*Cc(nil))*Cs(serverpart)*(colon*(serverpart/tonumber)+Cc(nil))
-local function hashed(str)
- if not str or str=="" then
- return {
- scheme="invalid",
- original=str,
- }
- end
- local detailed=split(str)
- local rawscheme=""
- local rawquery=""
- local somescheme=false
- local somequery=false
- if detailed then
- rawscheme=detailed[1]
- rawquery=detailed[4]
- somescheme=rawscheme~=""
- somequery=rawquery~=""
- end
- if not somescheme and not somequery then
- return {
- scheme="file",
- authority="",
- path=str,
- query="",
- fragment="",
- original=str,
- noscheme=true,
- filename=str,
- }
- end
- local authority=detailed[2]
- local path=detailed[3]
- local filename
- local username
- local password
- local host
- local port
- if authority~="" then
- username,password,host,port=lpegmatch(splitauthority,authority)
- end
- if authority=="" then
- filename=path
- elseif path=="" then
- filename=""
- else
- filename=authority.."/"..path
- end
- return {
- scheme=rawscheme,
- authority=authority,
- path=path,
- query=lpegmatch(unescaper,rawquery),
- queries=lpegmatch(splitquery,rawquery),
- fragment=detailed[5],
- original=str,
- noscheme=false,
- filename=filename,
- host=host,
- port=port,
- }
-end
-url.split=split
-url.hasscheme=hasscheme
-url.hashed=hashed
-function url.addscheme(str,scheme)
- if hasscheme(str) then
- return str
- elseif not scheme then
- return "file:///"..str
- else
- return scheme..":///"..str
- end
-end
-function url.construct(hash)
- local result,r={},0
- local scheme=hash.scheme
- local authority=hash.authority
- local path=hash.path
- local queries=hash.queries
- local fragment=hash.fragment
- if scheme and scheme~="" then
- r=r+1;result[r]=lpegmatch(escaper,scheme)
- r=r+1;result[r]="://"
- end
- if authority and authority~="" then
- r=r+1;result[r]=lpegmatch(escaper,authority)
- end
- if path and path~="" then
- r=r+1;result[r]="/"
- r=r+1;result[r]=lpegmatch(escaper,path)
- end
- if queries then
- local done=false
- for k,v in sortedhash(queries) do
- r=r+1;result[r]=done and "&" or "?"
- r=r+1;result[r]=lpegmatch(escaper,k)
- r=r+1;result[r]="="
- r=r+1;result[r]=lpegmatch(escaper,v)
- done=true
- end
- end
- if fragment and fragment~="" then
- r=r+1;result[r]="#"
- r=r+1;result[r]=lpegmatch(escaper,fragment)
- end
- return concat(result)
-end
-local pattern=Cs(slash^-1/""*R("az","AZ")*((S(":|")/":")+P(":"))*slash*P(1)^0)
-function url.filename(filename)
- local spec=hashed(filename)
- local path=spec.path
- return (spec.scheme=="file" and path and lpegmatch(pattern,path)) or filename
-end
-local function escapestring(str)
- return lpegmatch(escaper,str)
-end
-url.escape=escapestring
-function url.query(str)
- if type(str)=="string" then
- return lpegmatch(splitquery,str) or ""
- else
- return str
- end
-end
-function url.toquery(data)
- local td=type(data)
- if td=="string" then
- return #str and escape(data) or nil
- elseif td=="table" then
- if next(data) then
- local t={}
- for k,v in next,data do
- t[#t+1]=format("%s=%s",k,escapestring(v))
- end
- return concat(t,"&")
- end
- else
- end
-end
-local pattern=Cs(noslash^0*(1-noslash*P(-1))^0)
-function url.barepath(path)
- if not path or path=="" then
- return ""
- else
- return lpegmatch(pattern,path)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-dir"] = package.loaded["l-dir"] or true
-
--- original size: 18253, stripped down to: 10816
-
-if not modules then modules={} end modules ['l-dir']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,select=type,select
-local find,gmatch,match,gsub,sub=string.find,string.gmatch,string.match,string.gsub,string.sub
-local concat,insert,remove,unpack=table.concat,table.insert,table.remove,table.unpack
-local lpegmatch=lpeg.match
-local P,S,R,C,Cc,Cs,Ct,Cv,V=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.Cc,lpeg.Cs,lpeg.Ct,lpeg.Cv,lpeg.V
-dir=dir or {}
-local dir=dir
-local lfs=lfs
-local attributes=lfs.attributes
-local walkdir=lfs.dir
-local isdir=lfs.isdir
-local isfile=lfs.isfile
-local currentdir=lfs.currentdir
-local chdir=lfs.chdir
-local mkdir=lfs.mkdir
-local onwindows=os.type=="windows" or find(os.getenv("PATH"),";",1,true)
-if onwindows then
- local tricky=S("/\\")*P(-1)
- isdir=function(name)
- if lpegmatch(tricky,name) then
- return attributes(name,"mode")=="directory"
- else
- return attributes(name.."/.","mode")=="directory"
- end
- end
- isfile=function(name)
- return attributes(name,"mode")=="file"
- end
- lfs.isdir=isdir
- lfs.isfile=isfile
-else
- isdir=function(name)
- return attributes(name,"mode")=="directory"
- end
- isfile=function(name)
- return attributes(name,"mode")=="file"
- end
- lfs.isdir=isdir
- lfs.isfile=isfile
-end
-function dir.current()
- return (gsub(currentdir(),"\\","/"))
-end
-local function glob_pattern_function(path,patt,recurse,action)
- if isdir(path) then
- local usedpath
- if path=="/" then
- usedpath="/."
- elseif not find(path,"/$") then
- usedpath=path.."/."
- path=path.."/"
- else
- usedpath=path
- end
- local dirs
- local nofdirs=0
- for name,mode,size,time in walkdir(usedpath) do
- if name~="." and name~=".." then
- local full=path..name
- if mode==nil then
- mode=attributes(full,'mode')
- end
- if mode=='file' then
- if not patt or find(full,patt) then
- action(full,size,time)
- end
- elseif recurse and mode=="directory" then
- if dirs then
- nofdirs=nofdirs+1
- dirs[nofdirs]=full
- else
- nofdirs=1
- dirs={ full }
- end
- end
- end
- end
- if dirs then
- for i=1,nofdirs do
- glob_pattern_function(dirs[i],patt,recurse,action)
- end
- end
- end
-end
-local function glob_pattern_table(path,patt,recurse,result)
- if not result then
- result={}
- end
- local usedpath
- if path=="/" then
- usedpath="/."
- elseif not find(path,"/$") then
- usedpath=path.."/."
- path=path.."/"
- else
- usedpath=path
- end
- local dirs
- local nofdirs=0
- local noffiles=#result
- for name,mode in walkdir(usedpath) do
- if name~="." and name~=".." then
- local full=path..name
- if mode==nil then
- mode=attributes(full,'mode')
- end
- if mode=='file' then
- if not patt or find(full,patt) then
- noffiles=noffiles+1
- result[noffiles]=full
- end
- elseif recurse and mode=="directory" then
- if dirs then
- nofdirs=nofdirs+1
- dirs[nofdirs]=full
- else
- nofdirs=1
- dirs={ full }
- end
- end
- end
- end
- if dirs then
- for i=1,nofdirs do
- glob_pattern_table(dirs[i],patt,recurse,result)
- end
- end
- return result
-end
-local function globpattern(path,patt,recurse,method)
- local kind=type(method)
- if patt and sub(patt,1,-3)==path then
- patt=false
- end
- local okay=isdir(path)
- if kind=="function" then
- return okay and glob_pattern_function(path,patt,recurse,method) or {}
- elseif kind=="table" then
- return okay and glob_pattern_table(path,patt,recurse,method) or method
- else
- return okay and glob_pattern_table(path,patt,recurse,{}) or {}
- end
-end
-dir.globpattern=globpattern
-local function collectpattern(path,patt,recurse,result)
- local ok,scanner
- result=result or {}
- if path=="/" then
- ok,scanner,first=xpcall(function() return walkdir(path..".") end,function() end)
- else
- ok,scanner,first=xpcall(function() return walkdir(path) end,function() end)
- end
- if ok and type(scanner)=="function" then
- if not find(path,"/$") then
- path=path..'/'
- end
- for name in scanner,first do
- if name=="." then
- elseif name==".." then
- else
- local full=path..name
- local attr=attributes(full)
- local mode=attr.mode
- if mode=='file' then
- if find(full,patt) then
- result[name]=attr
- end
- elseif recurse and mode=="directory" then
- attr.list=collectpattern(full,patt,recurse)
- result[name]=attr
- end
- end
- end
- end
- return result
-end
-dir.collectpattern=collectpattern
-local separator,pattern
-if onwindows then
- local slash=S("/\\")/"/"
- pattern={
- [1]=(Cs(P(".")+slash^1)+Cs(R("az","AZ")*P(":")*slash^0)+Cc("./"))*V(2)*V(3),
- [2]=Cs(((1-S("*?/\\"))^0*slash)^0),
- [3]=Cs(P(1)^0)
- }
-else
- pattern={
- [1]=(C(P(".")+P("/")^1)+Cc("./"))*V(2)*V(3),
- [2]=C(((1-S("*?/"))^0*P("/"))^0),
- [3]=C(P(1)^0)
- }
-end
-local filter=Cs ((
- P("**")/".*"+P("*")/"[^/]*"+P("?")/"[^/]"+P(".")/"%%."+P("+")/"%%+"+P("-")/"%%-"+P(1)
-)^0 )
-local function glob(str,t)
- if type(t)=="function" then
- if type(str)=="table" then
- for s=1,#str do
- glob(str[s],t)
- end
- elseif isfile(str) then
- t(str)
- else
- local root,path,base=lpegmatch(pattern,str)
- if root and path and base then
- local recurse=find(base,"**",1,true)
- local start=root..path
- local result=lpegmatch(filter,start..base)
- globpattern(start,result,recurse,t)
- end
- end
- else
- if type(str)=="table" then
- local t=t or {}
- for s=1,#str do
- glob(str[s],t)
- end
- return t
- elseif isfile(str) then
- if t then
- t[#t+1]=str
- return t
- else
- return { str }
- end
- else
- local root,path,base=lpegmatch(pattern,str)
- if root and path and base then
- local recurse=find(base,"**",1,true)
- local start=root..path
- local result=lpegmatch(filter,start..base)
- return globpattern(start,result,recurse,t)
- else
- return {}
- end
- end
- end
-end
-dir.glob=glob
-local function globfiles(path,recurse,func,files)
- if type(func)=="string" then
- local s=func
- func=function(name) return find(name,s) end
- end
- files=files or {}
- local noffiles=#files
- for name,mode in walkdir(path) do
- if find(name,"^%.") then
- else
- if mode==nil then
- mode=attributes(name,'mode')
- end
- if mode=="directory" then
- if recurse then
- globfiles(path.."/"..name,recurse,func,files)
- end
- elseif mode=="file" then
- if not func or func(name) then
- noffiles=noffiles+1
- files[noffiles]=path.."/"..name
- end
- end
- end
- end
- return files
-end
-dir.globfiles=globfiles
-local function globdirs(path,recurse,func,files)
- if type(func)=="string" then
- local s=func
- func=function(name) return find(name,s) end
- end
- files=files or {}
- local noffiles=#files
- for name,mode in walkdir(path) do
- if find(name,"^%.") then
- else
- if mode==nil then
- mode=attributes(name,'mode')
- end
- if mode=="directory" then
- if not func or func(name) then
- noffiles=noffiles+1
- files[noffiles]=path.."/"..name
- if recurse then
- globdirs(path.."/"..name,recurse,func,files)
- end
- end
- end
- end
- end
- return files
-end
-dir.globdirs=globdirs
-function dir.ls(pattern)
- return concat(glob(pattern),"\n")
-end
-local make_indeed=true
-if onwindows then
- function dir.mkdirs(...)
- local n=select("#",...)
- local str
- if n==1 then
- str=select(1,...)
- if isdir(str) then
- return str,true
- end
- else
- str=""
- for i=1,n do
- local s=select(i,...)
- if s=="" then
- elseif str=="" then
- str=s
- else
- str=str.."/"..s
- end
- end
- end
- local pth=""
- local drive=false
- local first,middle,last=match(str,"^(//)(//*)(.*)$")
- if first then
- else
- first,last=match(str,"^(//)/*(.-)$")
- if first then
- middle,last=match(str,"([^/]+)/+(.-)$")
- if middle then
- pth="//"..middle
- else
- pth="//"..last
- last=""
- end
- else
- first,middle,last=match(str,"^([a-zA-Z]:)(/*)(.-)$")
- if first then
- pth,drive=first..middle,true
- else
- middle,last=match(str,"^(/*)(.-)$")
- if not middle then
- last=str
- end
- end
- end
- end
- for s in gmatch(last,"[^/]+") do
- if pth=="" then
- pth=s
- elseif drive then
- pth,drive=pth..s,false
- else
- pth=pth.."/"..s
- end
- if make_indeed and not isdir(pth) then
- mkdir(pth)
- end
- end
- return pth,(isdir(pth)==true)
- end
-else
- function dir.mkdirs(...)
- local n=select("#",...)
- local str,pth
- if n==1 then
- str=select(1,...)
- if isdir(str) then
- return str,true
- end
- else
- str=""
- for i=1,n do
- local s=select(i,...)
- if s and s~="" then
- if str~="" then
- str=str.."/"..s
- else
- str=s
- end
- end
- end
- end
- str=gsub(str,"/+","/")
- if find(str,"^/") then
- pth="/"
- for s in gmatch(str,"[^/]+") do
- local first=(pth=="/")
- if first then
- pth=pth..s
- else
- pth=pth.."/"..s
- end
- if make_indeed and not first and not isdir(pth) then
- mkdir(pth)
- end
- end
- else
- pth="."
- for s in gmatch(str,"[^/]+") do
- pth=pth.."/"..s
- if make_indeed and not isdir(pth) then
- mkdir(pth)
- end
- end
- end
- return pth,(isdir(pth)==true)
- end
-end
-dir.makedirs=dir.mkdirs
-do
- local chdir=sandbox and sandbox.original(chdir) or chdir
- if onwindows then
- local xcurrentdir=dir.current
- function dir.expandname(str)
- local first,nothing,last=match(str,"^(//)(//*)(.*)$")
- if first then
- first=xcurrentdir().."/"
- end
- if not first then
- first,last=match(str,"^(//)/*(.*)$")
- end
- if not first then
- first,last=match(str,"^([a-zA-Z]:)(.*)$")
- if first and not find(last,"^/") then
- local d=currentdir()
- if chdir(first) then
- first=xcurrentdir()
- end
- chdir(d)
- end
- end
- if not first then
- first,last=xcurrentdir(),str
- end
- last=gsub(last,"//","/")
- last=gsub(last,"/%./","/")
- last=gsub(last,"^/*","")
- first=gsub(first,"/*$","")
- if last=="" or last=="." then
- return first
- else
- return first.."/"..last
- end
- end
- else
- function dir.expandname(str)
- if not find(str,"^/") then
- str=currentdir().."/"..str
- end
- str=gsub(str,"//","/")
- str=gsub(str,"/%./","/")
- str=gsub(str,"(.)/%.$","%1")
- return str
- end
- end
-end
-file.expandname=dir.expandname
-local stack={}
-function dir.push(newdir)
- local curdir=currentdir()
- insert(stack,curdir)
- if newdir and newdir~="" and chdir(newdir) then
- return newdir
- else
- return curdir
- end
-end
-function dir.pop()
- local d=remove(stack)
- if d then
- chdir(d)
- end
- return d
-end
-local function found(...)
- for i=1,select("#",...) do
- local path=select(i,...)
- local kind=type(path)
- if kind=="string" then
- if isdir(path) then
- return path
- end
- elseif kind=="table" then
- local path=found(unpack(path))
- if path then
- return path
- end
- end
- end
-end
-dir.found=found
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-boolean"] = package.loaded["l-boolean"] or true
-
--- original size: 1850, stripped down to: 1498
-
-if not modules then modules={} end modules ['l-boolean']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,tonumber=type,tonumber
-boolean=boolean or {}
-local boolean=boolean
-function boolean.tonumber(b)
- if b then return 1 else return 0 end
-end
-function toboolean(str,tolerant)
- if str==nil then
- return false
- elseif str==false then
- return false
- elseif str==true then
- return true
- elseif str=="true" then
- return true
- elseif str=="false" then
- return false
- elseif not tolerant then
- return false
- elseif str==0 then
- return false
- elseif (tonumber(str) or 0)>0 then
- return true
- else
- return str=="yes" or str=="on" or str=="t"
- end
-end
-string.toboolean=toboolean
-function string.booleanstring(str)
- if str=="0" then
- return false
- elseif str=="1" then
- return true
- elseif str=="" then
- return false
- elseif str=="false" then
- return false
- elseif str=="true" then
- return true
- elseif (tonumber(str) or 0)>0 then
- return true
- else
- return str=="yes" or str=="on" or str=="t"
- end
-end
-function string.is_boolean(str,default,strict)
- if type(str)=="string" then
- if str=="true" or str=="yes" or str=="on" or str=="t" or (not strict and str=="1") then
- return true
- elseif str=="false" or str=="no" or str=="off" or str=="f" or (not strict and str=="0") then
- return false
- end
- end
- return default
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-unicode"] = package.loaded["l-unicode"] or true
-
--- original size: 41303, stripped down to: 17277
-
-if not modules then modules={} end modules ['l-unicode']={
- version=1.001,
- optimize=true,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utf=utf or {}
-unicode=nil
-if not string.utfcharacters then
- local gmatch=string.gmatch
- function string.characters(str)
- return gmatch(str,".[\128-\191]*")
- end
-end
-utf.characters=string.utfcharacters
-local type=type
-local char,byte,format,sub,gmatch=string.char,string.byte,string.format,string.sub,string.gmatch
-local concat=table.concat
-local P,C,R,Cs,Ct,Cmt,Cc,Carg,Cp=lpeg.P,lpeg.C,lpeg.R,lpeg.Cs,lpeg.Ct,lpeg.Cmt,lpeg.Cc,lpeg.Carg,lpeg.Cp
-local lpegmatch=lpeg.match
-local patterns=lpeg.patterns
-local tabletopattern=lpeg.utfchartabletopattern
-local bytepairs=string.bytepairs
-local finder=lpeg.finder
-local replacer=lpeg.replacer
-local p_utftype=patterns.utftype
-local p_utfstricttype=patterns.utfstricttype
-local p_utfoffset=patterns.utfoffset
-local p_utf8character=patterns.utf8character
-local p_utf8char=patterns.utf8char
-local p_utf8byte=patterns.utf8byte
-local p_utfbom=patterns.utfbom
-local p_newline=patterns.newline
-local p_whitespace=patterns.whitespace
-if not utf.char then
- utf.char=string.utfcharacter or (utf8 and utf8.char)
- if not utf.char then
- local char=string.char
- if bit32 then
- local rshift=bit32.rshift
- function utf.char(n)
- if n<0x80 then
- return char(n)
- elseif n<0x800 then
- return char(
- 0xC0+rshift(n,6),
- 0x80+(n%0x40)
- )
- elseif n<0x10000 then
- return char(
- 0xE0+rshift(n,12),
- 0x80+(rshift(n,6)%0x40),
- 0x80+(n%0x40)
- )
- elseif n<0x200000 then
- return char(
- 0xF0+rshift(n,18),
- 0x80+(rshift(n,12)%0x40),
- 0x80+(rshift(n,6)%0x40),
- 0x80+(n%0x40)
- )
- else
- return ""
- end
- end
- else
- local floor=math.floor
- function utf.char(n)
- if n<0x80 then
- return char(n)
- elseif n<0x800 then
- return char(
- 0xC0+floor(n/0x40),
- 0x80+(n%0x40)
- )
- elseif n<0x10000 then
- return char(
- 0xE0+floor(n/0x1000),
- 0x80+(floor(n/0x40)%0x40),
- 0x80+(n%0x40)
- )
- elseif n<0x200000 then
- return char(
- 0xF0+floor(n/0x40000),
- 0x80+(floor(n/0x1000)%0x40),
- 0x80+(floor(n/0x40)%0x40),
- 0x80+(n%0x40)
- )
- else
- return ""
- end
- end
- end
- end
-end
-if not utf.byte then
- utf.byte=string.utfvalue or (utf8 and utf8.codepoint)
- if not utf.byte then
- function utf.byte(c)
- return lpegmatch(p_utf8byte,c)
- end
- end
-end
-local utfchar,utfbyte=utf.char,utf.byte
-function utf.filetype(data)
- return data and lpegmatch(p_utftype,data) or "unknown"
-end
-local toentities=Cs (
- (
- patterns.utf8one+(
- patterns.utf8two+patterns.utf8three+patterns.utf8four
- )/function(s) local b=utfbyte(s) if b<127 then return s else return format("&#%X;",b) end end
- )^0
-)
-patterns.toentities=toentities
-function utf.toentities(str)
- return lpegmatch(toentities,str)
-end
-local one=P(1)
-local two=C(1)*C(1)
-local four=C(R(utfchar(0xD8),utfchar(0xFF)))*C(1)*C(1)*C(1)
-local pattern=P("\254\255")*Cs((
- four/function(a,b,c,d)
- local ab=0xFF*byte(a)+byte(b)
- local cd=0xFF*byte(c)+byte(d)
- return utfchar((ab-0xD800)*0x400+(cd-0xDC00)+0x10000)
- end+two/function(a,b)
- return utfchar(byte(a)*256+byte(b))
- end+one
- )^1 )+P("\255\254")*Cs((
- four/function(b,a,d,c)
- local ab=0xFF*byte(a)+byte(b)
- local cd=0xFF*byte(c)+byte(d)
- return utfchar((ab-0xD800)*0x400+(cd-0xDC00)+0x10000)
- end+two/function(b,a)
- return utfchar(byte(a)*256+byte(b))
- end+one
- )^1 )
-function string.toutf(s)
- return lpegmatch(pattern,s) or s
-end
-local validatedutf=Cs (
- (
- patterns.utf8one+patterns.utf8two+patterns.utf8three+patterns.utf8four+P(1)/"�"
- )^0
-)
-patterns.validatedutf=validatedutf
-function utf.is_valid(str)
- return type(str)=="string" and lpegmatch(validatedutf,str) or false
-end
-if not utf.len then
- utf.len=string.utflength or (utf8 and utf8.len)
- if not utf.len then
- local n,f=0,1
- local utfcharcounter=patterns.utfbom^-1*Cmt (
- Cc(1)*patterns.utf8one^1+Cc(2)*patterns.utf8two^1+Cc(3)*patterns.utf8three^1+Cc(4)*patterns.utf8four^1,
- function(_,t,d)
- n=n+(t-f)/d
- f=t
- return true
- end
- )^0
- function utf.len(str)
- n,f=0,1
- lpegmatch(utfcharcounter,str or "")
- return n
- end
- end
-end
-utf.length=utf.len
-if not utf.sub then
- local utflength=utf.length
- local b,e,n,first,last=0,0,0,0,0
- local function slide_zero(s,p)
- n=n+1
- if n>=last then
- e=p-1
- else
- return p
- end
- end
- local function slide_one(s,p)
- n=n+1
- if n==first then
- b=p
- end
- if n>=last then
- e=p-1
- else
- return p
- end
- end
- local function slide_two(s,p)
- n=n+1
- if n==first then
- b=p
- else
- return true
- end
- end
- local pattern_zero=Cmt(p_utf8character,slide_zero)^0
- local pattern_one=Cmt(p_utf8character,slide_one )^0
- local pattern_two=Cmt(p_utf8character,slide_two )^0
- local pattern_first=C(p_utf8character)
- function utf.sub(str,start,stop)
- if not start then
- return str
- end
- if start==0 then
- start=1
- end
- if not stop then
- if start<0 then
- local l=utflength(str)
- start=l+start
- else
- start=start-1
- end
- b,n,first=0,0,start
- lpegmatch(pattern_two,str)
- if n>=first then
- return sub(str,b)
- else
- return ""
- end
- end
- if start<0 or stop<0 then
- local l=utf.length(str)
- if start<0 then
- start=l+start
- if start<=0 then
- start=1
- else
- start=start+1
- end
- end
- if stop<0 then
- stop=l+stop
- if stop==0 then
- stop=1
- else
- stop=stop+1
- end
- end
- end
- if start==1 and stop==1 then
- return lpegmatch(pattern_first,str) or ""
- elseif start>stop then
- return ""
- elseif start>1 then
- b,e,n,first,last=0,0,0,start-1,stop
- lpegmatch(pattern_one,str)
- if n>=first and e==0 then
- e=#str
- end
- return sub(str,b,e)
- else
- b,e,n,last=1,0,0,stop
- lpegmatch(pattern_zero,str)
- if e==0 then
- e=#str
- end
- return sub(str,b,e)
- end
- end
-end
-function utf.remapper(mapping,option,action)
- local variant=type(mapping)
- if variant=="table" then
- action=action or mapping
- if option=="dynamic" then
- local pattern=false
- table.setmetatablenewindex(mapping,function(t,k,v) rawset(t,k,v) pattern=false end)
- return function(str)
- if not str or str=="" then
- return ""
- else
- if not pattern then
- pattern=Cs((tabletopattern(mapping)/action+p_utf8character)^0)
- end
- return lpegmatch(pattern,str)
- end
- end
- elseif option=="pattern" then
- return Cs((tabletopattern(mapping)/action+p_utf8character)^0)
- else
- local pattern=Cs((tabletopattern(mapping)/action+p_utf8character)^0)
- return function(str)
- if not str or str=="" then
- return ""
- else
- return lpegmatch(pattern,str)
- end
- end,pattern
- end
- elseif variant=="function" then
- if option=="pattern" then
- return Cs((p_utf8character/mapping+p_utf8character)^0)
- else
- local pattern=Cs((p_utf8character/mapping+p_utf8character)^0)
- return function(str)
- if not str or str=="" then
- return ""
- else
- return lpegmatch(pattern,str)
- end
- end,pattern
- end
- else
- return function(str)
- return str or ""
- end
- end
-end
-function utf.replacer(t)
- local r=replacer(t,false,false,true)
- return function(str)
- return lpegmatch(r,str)
- end
-end
-function utf.subtituter(t)
- local f=finder (t)
- local r=replacer(t,false,false,true)
- return function(str)
- local i=lpegmatch(f,str)
- if not i then
- return str
- elseif i>#str then
- return str
- else
- return lpegmatch(r,str)
- end
- end
-end
-local utflinesplitter=p_utfbom^-1*lpeg.tsplitat(p_newline)
-local utfcharsplitter_ows=p_utfbom^-1*Ct(C(p_utf8character)^0)
-local utfcharsplitter_iws=p_utfbom^-1*Ct((p_whitespace^1+C(p_utf8character))^0)
-local utfcharsplitter_raw=Ct(C(p_utf8character)^0)
-patterns.utflinesplitter=utflinesplitter
-function utf.splitlines(str)
- return lpegmatch(utflinesplitter,str or "")
-end
-function utf.split(str,ignorewhitespace)
- if ignorewhitespace then
- return lpegmatch(utfcharsplitter_iws,str or "")
- else
- return lpegmatch(utfcharsplitter_ows,str or "")
- end
-end
-function utf.totable(str)
- return lpegmatch(utfcharsplitter_raw,str)
-end
-function utf.magic(f)
- local str=f:read(4) or ""
- local off=lpegmatch(p_utfoffset,str)
- if off<4 then
- f:seek('set',off)
- end
- return lpegmatch(p_utftype,str)
-end
-local utf16_to_utf8_be,utf16_to_utf8_le
-local utf32_to_utf8_be,utf32_to_utf8_le
-local utf_16_be_getbom=patterns.utfbom_16_be^-1
-local utf_16_le_getbom=patterns.utfbom_16_le^-1
-local utf_32_be_getbom=patterns.utfbom_32_be^-1
-local utf_32_le_getbom=patterns.utfbom_32_le^-1
-local utf_16_be_linesplitter=utf_16_be_getbom*lpeg.tsplitat(patterns.utf_16_be_nl)
-local utf_16_le_linesplitter=utf_16_le_getbom*lpeg.tsplitat(patterns.utf_16_le_nl)
-local utf_32_be_linesplitter=utf_32_be_getbom*lpeg.tsplitat(patterns.utf_32_be_nl)
-local utf_32_le_linesplitter=utf_32_le_getbom*lpeg.tsplitat(patterns.utf_32_le_nl)
-local more=0
-local p_utf16_to_utf8_be=C(1)*C(1)/function(left,right)
- local now=256*byte(left)+byte(right)
- if more>0 then
- now=(more-0xD800)*0x400+(now-0xDC00)+0x10000
- more=0
- return utfchar(now)
- elseif now>=0xD800 and now<=0xDBFF then
- more=now
- return ""
- else
- return utfchar(now)
- end
-end
-local p_utf16_to_utf8_le=C(1)*C(1)/function(right,left)
- local now=256*byte(left)+byte(right)
- if more>0 then
- now=(more-0xD800)*0x400+(now-0xDC00)+0x10000
- more=0
- return utfchar(now)
- elseif now>=0xD800 and now<=0xDBFF then
- more=now
- return ""
- else
- return utfchar(now)
- end
-end
-local p_utf32_to_utf8_be=C(1)*C(1)*C(1)*C(1)/function(a,b,c,d)
- return utfchar(256*256*256*byte(a)+256*256*byte(b)+256*byte(c)+byte(d))
-end
-local p_utf32_to_utf8_le=C(1)*C(1)*C(1)*C(1)/function(a,b,c,d)
- return utfchar(256*256*256*byte(d)+256*256*byte(c)+256*byte(b)+byte(a))
-end
-p_utf16_to_utf8_be=P(true)/function() more=0 end*utf_16_be_getbom*Cs(p_utf16_to_utf8_be^0)
-p_utf16_to_utf8_le=P(true)/function() more=0 end*utf_16_le_getbom*Cs(p_utf16_to_utf8_le^0)
-p_utf32_to_utf8_be=P(true)/function() more=0 end*utf_32_be_getbom*Cs(p_utf32_to_utf8_be^0)
-p_utf32_to_utf8_le=P(true)/function() more=0 end*utf_32_le_getbom*Cs(p_utf32_to_utf8_le^0)
-patterns.utf16_to_utf8_be=p_utf16_to_utf8_be
-patterns.utf16_to_utf8_le=p_utf16_to_utf8_le
-patterns.utf32_to_utf8_be=p_utf32_to_utf8_be
-patterns.utf32_to_utf8_le=p_utf32_to_utf8_le
-utf16_to_utf8_be=function(s)
- if s and s~="" then
- return lpegmatch(p_utf16_to_utf8_be,s)
- else
- return s
- end
-end
-local utf16_to_utf8_be_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_16_be_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf16_to_utf8_be,s)
- end
- end
- return t
-end
-utf16_to_utf8_le=function(s)
- if s and s~="" then
- return lpegmatch(p_utf16_to_utf8_le,s)
- else
- return s
- end
-end
-local utf16_to_utf8_le_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_16_le_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf16_to_utf8_le,s)
- end
- end
- return t
-end
-utf32_to_utf8_be=function(s)
- if s and s~="" then
- return lpegmatch(p_utf32_to_utf8_be,s)
- else
- return s
- end
-end
-local utf32_to_utf8_be_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_32_be_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf32_to_utf8_be,s)
- end
- end
- return t
-end
-utf32_to_utf8_le=function(s)
- if s and s~="" then
- return lpegmatch(p_utf32_to_utf8_le,s)
- else
- return s
- end
-end
-local utf32_to_utf8_le_t=function(t)
- if not t then
- return nil
- elseif type(t)=="string" then
- t=lpegmatch(utf_32_le_linesplitter,t)
- end
- for i=1,#t do
- local s=t[i]
- if s~="" then
- t[i]=lpegmatch(p_utf32_to_utf8_le,s)
- end
- end
- return t
-end
-utf.utf16_to_utf8_le_t=utf16_to_utf8_le_t
-utf.utf16_to_utf8_be_t=utf16_to_utf8_be_t
-utf.utf32_to_utf8_le_t=utf32_to_utf8_le_t
-utf.utf32_to_utf8_be_t=utf32_to_utf8_be_t
-utf.utf16_to_utf8_le=utf16_to_utf8_le
-utf.utf16_to_utf8_be=utf16_to_utf8_be
-utf.utf32_to_utf8_le=utf32_to_utf8_le
-utf.utf32_to_utf8_be=utf32_to_utf8_be
-function utf.utf8_to_utf8_t(t)
- return type(t)=="string" and lpegmatch(utflinesplitter,t) or t
-end
-function utf.utf16_to_utf8_t(t,endian)
- return endian and utf16_to_utf8_be_t(t) or utf16_to_utf8_le_t(t) or t
-end
-function utf.utf32_to_utf8_t(t,endian)
- return endian and utf32_to_utf8_be_t(t) or utf32_to_utf8_le_t(t) or t
-end
-if bit32 then
- local rshift=bit32.rshift
- local function little(b)
- if b<0x10000 then
- return char(b%256,rshift(b,8))
- else
- b=b-0x10000
- local b1=rshift(b,10)+0xD800
- local b2=b%1024+0xDC00
- return char(b1%256,rshift(b1,8),b2%256,rshift(b2,8))
- end
- end
- local function big(b)
- if b<0x10000 then
- return char(rshift(b,8),b%256)
- else
- b=b-0x10000
- local b1=rshift(b,10)+0xD800
- local b2=b%1024+0xDC00
- return char(rshift(b1,8),b1%256,rshift(b2,8),b2%256)
- end
- end
- local l_remap=Cs((p_utf8byte/little+P(1)/"")^0)
- local b_remap=Cs((p_utf8byte/big+P(1)/"")^0)
- local function utf8_to_utf16_be(str,nobom)
- if nobom then
- return lpegmatch(b_remap,str)
- else
- return char(254,255)..lpegmatch(b_remap,str)
- end
- end
- local function utf8_to_utf16_le(str,nobom)
- if nobom then
- return lpegmatch(l_remap,str)
- else
- return char(255,254)..lpegmatch(l_remap,str)
- end
- end
- utf.utf8_to_utf16_be=utf8_to_utf16_be
- utf.utf8_to_utf16_le=utf8_to_utf16_le
- function utf.utf8_to_utf16(str,littleendian,nobom)
- if littleendian then
- return utf8_to_utf16_le(str,nobom)
- else
- return utf8_to_utf16_be(str,nobom)
- end
- end
-end
-local pattern=Cs (
- (p_utf8byte/function(unicode ) return format("0x%04X",unicode) end)*(p_utf8byte*Carg(1)/function(unicode,separator) return format("%s0x%04X",separator,unicode) end)^0
-)
-function utf.tocodes(str,separator)
- return lpegmatch(pattern,str,1,separator or " ")
-end
-function utf.ustring(s)
- return format("U+%05X",type(s)=="number" and s or utfbyte(s))
-end
-function utf.xstring(s)
- return format("0x%05X",type(s)=="number" and s or utfbyte(s))
-end
-function utf.toeight(str)
- if not str or str=="" then
- return nil
- end
- local utftype=lpegmatch(p_utfstricttype,str)
- if utftype=="utf-8" then
- return sub(str,4)
- elseif utftype=="utf-16-be" then
- return utf16_to_utf8_be(str)
- elseif utftype=="utf-16-le" then
- return utf16_to_utf8_le(str)
- else
- return str
- end
-end
-do
- local p_nany=p_utf8character/""
- local cache={}
- function utf.count(str,what)
- if type(what)=="string" then
- local p=cache[what]
- if not p then
- p=Cs((P(what)/" "+p_nany)^0)
- cache[p]=p
- end
- return #lpegmatch(p,str)
- else
- return #lpegmatch(Cs((P(what)/" "+p_nany)^0),str)
- end
- end
-end
-if not string.utfvalues then
- local find=string.find
- local dummy=function()
- end
- function string.utfvalues(str)
- local n=#str
- if n==0 then
- return dummy
- elseif n==1 then
- return function() return utfbyte(str) end
- else
- local p=1
- return function()
- local b,e=find(str,".[\128-\191]*",p)
- if b then
- p=e+1
- return utfbyte(sub(str,b,e))
- end
- end
- end
- end
-end
-utf.values=string.utfvalues
-function utf.chrlen(u)
- return
- (u<0x80 and 1) or
- (u<0xE0 and 2) or
- (u<0xF0 and 3) or
- (u<0xF8 and 4) or
- (u<0xFC and 5) or
- (u<0xFE and 6) or 0
-end
-if bit32 then
- local extract=bit32.extract
- local char=string.char
- function utf.toutf32string(n)
- if n<=0xFF then
- return
- char(n).."\000\000\000"
- elseif n<=0xFFFF then
- return
- char(extract(n,0,8))..char(extract(n,8,8)).."\000\000"
- elseif n<=0xFFFFFF then
- return
- char(extract(n,0,8))..char(extract(n,8,8))..char(extract(n,16,8)).."\000"
- else
- return
- char(extract(n,0,8))..char(extract(n,8,8))..char(extract(n,16,8))..char(extract(n,24,8))
- end
- end
-end
-local len=utf.len
-local rep=rep
-function string.utfpadd(s,n)
- if n and n~=0 then
- local l=len(s)
- if n>0 then
- local d=n-l
- if d>0 then
- return rep(c or " ",d)..s
- end
- else
- local d=- n-l
- if d>0 then
- return s..rep(c or " ",d)
- end
- end
- end
- return s
-end
-do
- local utfcharacters=utf.characters or string.utfcharacters
- local utfchar=utf.char or string.utfcharacter
- lpeg.UP=P
- if utfcharacters then
- function lpeg.US(str)
- local p=P(false)
- for uc in utfcharacters(str) do
- p=p+P(uc)
- end
- return p
- end
- else
- function lpeg.US(str)
- local p=P(false)
- local f=function(uc)
- p=p+P(uc)
- end
- lpegmatch((p_utf8char/f)^0,str)
- return p
- end
- end
- local range=p_utf8byte*p_utf8byte+Cc(false)
- function lpeg.UR(str,more)
- local first,last
- if type(str)=="number" then
- first=str
- last=more or first
- else
- first,last=lpegmatch(range,str)
- if not last then
- return P(str)
- end
- end
- if first==last then
- return P(str)
- end
- if not utfchar then
- utfchar=utf.char
- end
- if utfchar and (last-first<8) then
- local p=P(false)
- for i=first,last do
- p=p+P(utfchar(i))
- end
- return p
- else
- local f=function(b)
- return b>=first and b<=last
- end
- return p_utf8byte/f
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["l-math"] = package.loaded["l-math"] or true
-
--- original size: 2555, stripped down to: 1831
-
-if not modules then modules={} end modules ['l-math']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if not math.ceiling then
- math.ceiling=math.ceil
-end
-if not math.round then
- local floor=math.floor
- function math.round(x) return floor(x+0.5) end
-end
-if not math.div then
- local floor=math.floor
- function math.div(n,m) return floor(n/m) end
-end
-if not math.mod then
- function math.mod(n,m) return n%m end
-end
-if not math.sind then
- local sin,cos,tan=math.sin,math.cos,math.tan
- local pipi=2*math.pi/360
- function math.sind(d) return sin(d*pipi) end
- function math.cosd(d) return cos(d*pipi) end
- function math.tand(d) return tan(d*pipi) end
-end
-if not math.odd then
- function math.odd (n) return n%2~=0 end
- function math.even(n) return n%2==0 end
-end
-if not math.cosh then
- local exp=math.exp
- function math.cosh(x)
- local xx=exp(x)
- return (xx+1/xx)/2
- end
- function math.sinh(x)
- local xx=exp(x)
- return (xx-1/xx)/2
- end
- function math.tanh(x)
- local xx=exp(x)
- return (xx-1/xx)/(xx+1/xx)
- end
-end
-if not math.pow then
- function math.pow(x,y)
- return x^y
- end
-end
-if not math.atan2 then
- math.atan2=math.atan
-end
-if not math.ldexp then
- function math.ldexp(x,e)
- return x*2.0^e
- end
-end
-if not math.log10 then
- local log=math.log
- function math.log10(x)
- return log(x,10)
- end
-end
-if not math.type then
- function math.type()
- return "float"
- end
-end
-if not math.tointeger then
- math.mininteger=-0x4FFFFFFFFFFF
- math.maxinteger=0x4FFFFFFFFFFF
- local floor=math.floor
- function math.tointeger(n)
- local f=floor(n)
- return f==n and f or nil
- end
-end
-if not math.ult then
- local floor=math.floor
- function math.tointeger(m,n)
- return floor(m)<floor(n)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-str"] = package.loaded["util-str"] or true
-
--- original size: 45129, stripped down to: 23525
-
-if not modules then modules={} end modules ['util-str']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities=utilities or {}
-utilities.strings=utilities.strings or {}
-local strings=utilities.strings
-local format,gsub,rep,sub,find=string.format,string.gsub,string.rep,string.sub,string.find
-local load,dump=load,string.dump
-local tonumber,type,tostring,next,setmetatable=tonumber,type,tostring,next,setmetatable
-local unpack,concat=table.unpack,table.concat
-local P,V,C,S,R,Ct,Cs,Cp,Carg,Cc=lpeg.P,lpeg.V,lpeg.C,lpeg.S,lpeg.R,lpeg.Ct,lpeg.Cs,lpeg.Cp,lpeg.Carg,lpeg.Cc
-local patterns,lpegmatch=lpeg.patterns,lpeg.match
-local utfchar,utfbyte,utflen=utf.char,utf.byte,utf.len
-local loadstripped=function(str,shortcuts)
- if shortcuts then
- return load(dump(load(str),true),nil,nil,shortcuts)
- else
- return load(dump(load(str),true))
- end
-end
-if not number then number={} end
-local stripzero=patterns.stripzero
-local stripzeros=patterns.stripzeros
-local newline=patterns.newline
-local endofstring=patterns.endofstring
-local anything=patterns.anything
-local whitespace=patterns.whitespace
-local space=patterns.space
-local spacer=patterns.spacer
-local spaceortab=patterns.spaceortab
-local digit=patterns.digit
-local sign=patterns.sign
-local period=patterns.period
-local ptf=1/65536
-local bpf=(7200/7227)/65536
-local function points(n)
- if n==0 then
- return "0pt"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0pt"
- end
- n=n*ptf
- if n%1==0 then
- return format("%ipt",n)
- else
- return lpegmatch(stripzeros,format("%.5fpt",n))
- end
-end
-local function nupoints(n)
- if n==0 then
- return "0"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0"
- end
- n=n*ptf
- if n%1==0 then
- return format("%i",n)
- else
- return format("%.5f",n)
- end
-end
-local function basepoints(n)
- if n==0 then
- return "0bp"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0bp"
- end
- n=n*bpf
- if n%1==0 then
- return format("%ibp",n)
- else
- return lpegmatch(stripzeros,format("%.5fbp",n))
- end
-end
-local function nubasepoints(n)
- if n==0 then
- return "0"
- end
- n=tonumber(n)
- if not n or n==0 then
- return "0"
- end
- n=n*bpf
- if n%1==0 then
- return format("%i",n)
- else
- return format("%.5f",n)
- end
-end
-number.points=points
-number.nupoints=nupoints
-number.basepoints=basepoints
-number.nubasepoints=nubasepoints
-local rubish=spaceortab^0*newline
-local anyrubish=spaceortab+newline
-local stripped=(spaceortab^1/"")*newline
-local leading=rubish^0/""
-local trailing=(anyrubish^1*endofstring)/""
-local redundant=rubish^3/"\n"
-local pattern=Cs(leading*(trailing+redundant+stripped+anything)^0)
-function strings.collapsecrlf(str)
- return lpegmatch(pattern,str)
-end
-local repeaters={}
-function strings.newrepeater(str,offset)
- offset=offset or 0
- local s=repeaters[str]
- if not s then
- s={}
- repeaters[str]=s
- end
- local t=s[offset]
- if t then
- return t
- end
- t={}
- setmetatable(t,{ __index=function(t,k)
- if not k then
- return ""
- end
- local n=k+offset
- local s=n>0 and rep(str,n) or ""
- t[k]=s
- return s
- end })
- s[offset]=t
- return t
-end
-local extra,tab,start=0,0,4,0
-local nspaces=strings.newrepeater(" ")
-string.nspaces=nspaces
-local pattern=Carg(1)/function(t)
- extra,tab,start=0,t or 7,1
- end*Cs((
- Cp()*patterns.tab/function(position)
- local current=(position-start+1)+extra
- local spaces=tab-(current-1)%tab
- if spaces>0 then
- extra=extra+spaces-1
- return nspaces[spaces]
- else
- return ""
- end
- end+newline*Cp()/function(position)
- extra,start=0,position
- end+anything
- )^1)
-function strings.tabtospace(str,tab)
- return lpegmatch(pattern,str,1,tab or 7)
-end
-function string.utfpadding(s,n)
- if not n or n==0 then
- return ""
- end
- local l=utflen(s)
- if n>0 then
- return nspaces[n-l]
- else
- return nspaces[-n-l]
- end
-end
-local optionalspace=spacer^0
-local nospace=optionalspace/""
-local endofline=nospace*newline
-local stripend=(whitespace^1*endofstring)/""
-local normalline=(nospace*((1-optionalspace*(newline+endofstring))^1)*nospace)
-local stripempty=endofline^1/""
-local normalempty=endofline^1
-local singleempty=endofline*(endofline^0/"")
-local doubleempty=endofline*endofline^-1*(endofline^0/"")
-local stripstart=stripempty^0
-local intospace=whitespace^1/" "
-local noleading=whitespace^1/""
-local notrailing=noleading*endofstring
-local p_prune_normal=Cs (stripstart*(stripend+normalline+normalempty )^0 )
-local p_prune_collapse=Cs (stripstart*(stripend+normalline+doubleempty )^0 )
-local p_prune_noempty=Cs (stripstart*(stripend+normalline+singleempty )^0 )
-local p_prune_intospace=Cs (noleading*(notrailing+intospace+1 )^0 )
-local p_retain_normal=Cs ((normalline+normalempty )^0 )
-local p_retain_collapse=Cs ((normalline+doubleempty )^0 )
-local p_retain_noempty=Cs ((normalline+singleempty )^0 )
-local striplinepatterns={
- ["prune"]=p_prune_normal,
- ["prune and collapse"]=p_prune_collapse,
- ["prune and no empty"]=p_prune_noempty,
- ["prune and to space"]=p_prune_intospace,
- ["retain"]=p_retain_normal,
- ["retain and collapse"]=p_retain_collapse,
- ["retain and no empty"]=p_retain_noempty,
- ["collapse"]=patterns.collapser,
-}
-setmetatable(striplinepatterns,{ __index=function(t,k) return p_prune_collapse end })
-strings.striplinepatterns=striplinepatterns
-function strings.striplines(str,how)
- return str and lpegmatch(striplinepatterns[how],str) or str
-end
-function strings.collapse(str)
- return str and lpegmatch(p_prune_intospace,str) or str
-end
-strings.striplong=strings.striplines
-function strings.nice(str)
- str=gsub(str,"[:%-+_]+"," ")
- return str
-end
-local n=0
-local sequenced=table.sequenced
-function string.autodouble(s,sep)
- if s==nil then
- return '""'
- end
- local t=type(s)
- if t=="number" then
- return tostring(s)
- end
- if t=="table" then
- return ('"'..sequenced(s,sep or ",")..'"')
- end
- return ('"'..tostring(s)..'"')
-end
-function string.autosingle(s,sep)
- if s==nil then
- return "''"
- end
- local t=type(s)
- if t=="number" then
- return tostring(s)
- end
- if t=="table" then
- return ("'"..sequenced(s,sep or ",").."'")
- end
- return ("'"..tostring(s).."'")
-end
-local tracedchars={ [0]=
- "[null]","[soh]","[stx]","[etx]","[eot]","[enq]","[ack]","[bel]",
- "[bs]","[ht]","[lf]","[vt]","[ff]","[cr]","[so]","[si]",
- "[dle]","[dc1]","[dc2]","[dc3]","[dc4]","[nak]","[syn]","[etb]",
- "[can]","[em]","[sub]","[esc]","[fs]","[gs]","[rs]","[us]",
- "[space]",
-}
-string.tracedchars=tracedchars
-strings.tracers=tracedchars
-function string.tracedchar(b)
- if type(b)=="number" then
- return tracedchars[b] or (utfchar(b).." (U+"..format("%05X",b)..")")
- else
- local c=utfbyte(b)
- return tracedchars[c] or (b.." (U+"..(c and format("%05X",c) or "?????")..")")
- end
-end
-function number.signed(i)
- if i>0 then
- return "+",i
- else
- return "-",-i
- end
-end
-local two=digit*digit
-local three=two*digit
-local prefix=(Carg(1)*three)^1
-local splitter=Cs (
- (((1-(three^1*period))^1+C(three))*prefix+C((1-period)^1))*(anything/""*Carg(2))*C(2)
-)
-local splitter3=Cs (
- three*prefix*endofstring+two*prefix*endofstring+digit*prefix*endofstring+three+two+digit
-)
-patterns.formattednumber=splitter
-function number.formatted(n,sep1,sep2)
- if sep1==false then
- if type(n)=="number" then
- n=tostring(n)
- end
- return lpegmatch(splitter3,n,1,sep2 or ".")
- else
- if type(n)=="number" then
- n=format("%0.2f",n)
- end
- if sep1==true then
- return lpegmatch(splitter,n,1,".",",")
- elseif sep1=="." then
- return lpegmatch(splitter,n,1,sep1,sep2 or ",")
- elseif sep1=="," then
- return lpegmatch(splitter,n,1,sep1,sep2 or ".")
- else
- return lpegmatch(splitter,n,1,sep1 or ",",sep2 or ".")
- end
- end
-end
-local p=Cs(
- P("-")^0*(P("0")^1/"")^0*(1-period)^0*(period*P("0")^1*endofstring/""+period^0)*P(1-P("0")^1*endofstring)^0
- )
-function number.compactfloat(n,fmt)
- if n==0 then
- return "0"
- elseif n==1 then
- return "1"
- end
- n=lpegmatch(p,format(fmt or "%0.3f",n))
- if n=="." or n=="" or n=="-" then
- return "0"
- end
- return n
-end
-local zero=P("0")^1/""
-local plus=P("+")/""
-local minus=P("-")
-local separator=period
-local trailing=zero^1*#S("eE")
-local exponent=(S("eE")*(plus+Cs((minus*zero^0*endofstring)/"")+minus)*zero^0*(endofstring*Cc("0")+anything^1))
-local pattern_a=Cs(minus^0*digit^1*(separator/""*trailing+separator*(trailing+digit)^0)*exponent)
-local pattern_b=Cs((exponent+anything)^0)
-function number.sparseexponent(f,n)
- if not n then
- n=f
- f="%e"
- end
- local tn=type(n)
- if tn=="string" then
- local m=tonumber(n)
- if m then
- return lpegmatch((f=="%e" or f=="%E") and pattern_a or pattern_b,format(f,m))
- end
- elseif tn=="number" then
- return lpegmatch((f=="%e" or f=="%E") and pattern_a or pattern_b,format(f,n))
- end
- return tostring(n)
-end
-local hf={}
-local hs={}
-setmetatable(hf,{ __index=function(t,k)
- local v="%."..k.."f"
- t[k]=v
- return v
-end } )
-setmetatable(hs,{ __index=function(t,k)
- local v="%"..k.."s"
- t[k]=v
- return v
-end } )
-function number.formattedfloat(n,b,a)
- local s=format(hf[a],n)
- local l=(b or 0)+(a or 0)+1
- if #s<l then
- return format(hs[l],s)
- else
- return s
- end
-end
-local template=[[
-%s
-%s
-return function(%s) return %s end
-]]
-local pattern=Cs(Cc('"')*(
- (1-S('"\\\n\r'))^1+P('"')/'\\"'+P('\\')/'\\\\'+P('\n')/'\\n'+P('\r')/'\\r'
-)^0*Cc('"'))
-patterns.escapedquotes=pattern
-function string.escapedquotes(s)
- return lpegmatch(pattern,s)
-end
-local preamble=""
-local environment={
- global=global or _G,
- lpeg=lpeg,
- type=type,
- tostring=tostring,
- tonumber=tonumber,
- format=string.format,
- concat=table.concat,
- signed=number.signed,
- points=number.points,
- nupoints=number.nupoints,
- basepoints=number.basepoints,
- nubasepoints=number.nubasepoints,
- utfchar=utf.char,
- utfbyte=utf.byte,
- lpegmatch=lpeg.match,
- nspaces=string.nspaces,
- utfpadding=string.utfpadding,
- tracedchar=string.tracedchar,
- autosingle=string.autosingle,
- autodouble=string.autodouble,
- sequenced=table.sequenced,
- formattednumber=number.formatted,
- sparseexponent=number.sparseexponent,
- formattedfloat=number.formattedfloat,
- stripzero=patterns.stripzero,
- stripzeros=patterns.stripzeros,
- escapedquotes=string.escapedquotes,
- FORMAT=string.f6,
-}
-local arguments={ "a1" }
-setmetatable(arguments,{ __index=function(t,k)
- local v=t[k-1]..",a"..k
- t[k]=v
- return v
- end
-})
-local prefix_any=C((sign+space+period+digit)^0)
-local prefix_sub=(C((sign+digit)^0)+Cc(0))*period*(C((sign+digit)^0)+Cc(0))
-local prefix_tab=P("{")*C((1-P("}"))^0)*P("}")+C((1-R("az","AZ","09","%%"))^0)
-local format_s=function(f)
- n=n+1
- if f and f~="" then
- return format("format('%%%ss',a%s)",f,n)
- else
- return format("(a%s or '')",n)
- end
-end
-local format_S=function(f)
- n=n+1
- if f and f~="" then
- return format("format('%%%ss',tostring(a%s))",f,n)
- else
- return format("tostring(a%s)",n)
- end
-end
-local format_right=function(f)
- n=n+1
- f=tonumber(f)
- if not f or f==0 then
- return format("(a%s or '')",n)
- elseif f>0 then
- return format("utfpadding(a%s,%i)..a%s",n,f,n)
- else
- return format("a%s..utfpadding(a%s,%i)",n,n,f)
- end
-end
-local format_left=function(f)
- n=n+1
- f=tonumber(f)
- if not f or f==0 then
- return format("(a%s or '')",n)
- end
- if f<0 then
- return format("utfpadding(a%s,%i)..a%s",n,-f,n)
- else
- return format("a%s..utfpadding(a%s,%i)",n,n,-f)
- end
-end
-local format_q=JITSUPPORTED and function()
- n=n+1
- return format("(a%s ~= nil and format('%%q',tostring(a%s)) or '')",n,n)
-end or function()
- n=n+1
- return format("(a%s ~= nil and format('%%q',a%s) or '')",n,n)
-end
-local format_Q=function()
- n=n+1
- return format("escapedquotes(tostring(a%s))",n)
-end
-local format_i=function(f)
- n=n+1
- if f and f~="" then
- return format("format('%%%si',a%s)",f,n)
- else
- return format("format('%%i',a%s)",n)
- end
-end
-local format_d=format_i
-local format_I=function(f)
- n=n+1
- return format("format('%%s%%%si',signed(a%s))",f,n)
-end
-local format_f=function(f)
- n=n+1
- return format("format('%%%sf',a%s)",f,n)
-end
-local format_F=function(f)
- n=n+1
- if not f or f=="" then
- return format("(((a%s > -0.0000000005 and a%s < 0.0000000005) and '0') or format((a%s %% 1 == 0) and '%%i' or '%%.9f',a%s))",n,n,n,n)
- else
- return format("format((a%s %% 1 == 0) and '%%i' or '%%%sf',a%s)",n,f,n)
- end
-end
-local format_k=function(b,a)
- n=n+1
- return format("formattedfloat(a%s,%s,%s)",n,b or 0,a or 0)
-end
-local format_g=function(f)
- n=n+1
- return format("format('%%%sg',a%s)",f,n)
-end
-local format_G=function(f)
- n=n+1
- return format("format('%%%sG',a%s)",f,n)
-end
-local format_e=function(f)
- n=n+1
- return format("format('%%%se',a%s)",f,n)
-end
-local format_E=function(f)
- n=n+1
- return format("format('%%%sE',a%s)",f,n)
-end
-local format_j=function(f)
- n=n+1
- return format("sparseexponent('%%%se',a%s)",f,n)
-end
-local format_J=function(f)
- n=n+1
- return format("sparseexponent('%%%sE',a%s)",f,n)
-end
-local format_x=function(f)
- n=n+1
- return format("format('%%%sx',a%s)",f,n)
-end
-local format_X=function(f)
- n=n+1
- return format("format('%%%sX',a%s)",f,n)
-end
-local format_o=function(f)
- n=n+1
- return format("format('%%%so',a%s)",f,n)
-end
-local format_c=function()
- n=n+1
- return format("utfchar(a%s)",n)
-end
-local format_C=function()
- n=n+1
- return format("tracedchar(a%s)",n)
-end
-local format_r=function(f)
- n=n+1
- return format("format('%%%s.0f',a%s)",f,n)
-end
-local format_h=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('0x%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_H=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('0x%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_u=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('u+%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_U=function(f)
- n=n+1
- if f=="-" then
- f=sub(f,2)
- return format("format('%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- else
- return format("format('U+%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f=="" and "05" or f,n,n,n)
- end
-end
-local format_p=function()
- n=n+1
- return format("points(a%s)",n)
-end
-local format_P=function()
- n=n+1
- return format("nupoints(a%s)",n)
-end
-local format_b=function()
- n=n+1
- return format("basepoints(a%s)",n)
-end
-local format_B=function()
- n=n+1
- return format("nubasepoints(a%s)",n)
-end
-local format_t=function(f)
- n=n+1
- if f and f~="" then
- return format("concat(a%s,%q)",n,f)
- else
- return format("concat(a%s)",n)
- end
-end
-local format_T=function(f)
- n=n+1
- if f and f~="" then
- return format("sequenced(a%s,%q)",n,f)
- else
- return format("sequenced(a%s)",n)
- end
-end
-local format_l=function()
- n=n+1
- return format("(a%s and 'true' or 'false')",n)
-end
-local format_L=function()
- n=n+1
- return format("(a%s and 'TRUE' or 'FALSE')",n)
-end
-local format_n=function()
- n=n+1
- return format("((a%s %% 1 == 0) and format('%%i',a%s) or tostring(a%s))",n,n,n)
-end
-local format_N if environment.FORMAT then
- format_N=function(f)
- n=n+1
- if not f or f=="" then
- return format("FORMAT(a%s,'%%.9f')",n)
- elseif f==".6" or f=="0.6" then
- return format("FORMAT(a%s)",n)
- else
- return format("FORMAT(a%s,'%%%sf')",n,f)
- end
- end
-else
- format_N=function(f)
- n=n+1
- if not f or f=="" then
- f=".9"
- end
- return format("(((a%s %% 1 == 0) and format('%%i',a%s)) or lpegmatch(stripzero,format('%%%sf',a%s)))",n,n,f,n)
- end
-end
-local format_a=function(f)
- n=n+1
- if f and f~="" then
- return format("autosingle(a%s,%q)",n,f)
- else
- return format("autosingle(a%s)",n)
- end
-end
-local format_A=function(f)
- n=n+1
- if f and f~="" then
- return format("autodouble(a%s,%q)",n,f)
- else
- return format("autodouble(a%s)",n)
- end
-end
-local format_w=function(f)
- n=n+1
- f=tonumber(f)
- if f then
- return format("nspaces[%s+a%s]",f,n)
- else
- return format("nspaces[a%s]",n)
- end
-end
-local format_W=function(f)
- return format("nspaces[%s]",tonumber(f) or 0)
-end
-local format_m=function(f)
- n=n+1
- if not f or f=="" then
- f=","
- end
- if f=="0" then
- return format([[formattednumber(a%s,false)]],n)
- else
- return format([[formattednumber(a%s,%q,".")]],n,f)
- end
-end
-local format_M=function(f)
- n=n+1
- if not f or f=="" then
- f="."
- end
- if f=="0" then
- return format([[formattednumber(a%s,false)]],n)
- else
- return format([[formattednumber(a%s,%q,",")]],n,f)
- end
-end
-local format_z=function(f)
- n=n+(tonumber(f) or 1)
- return "''"
-end
-local format_rest=function(s)
- return format("%q",s)
-end
-local format_extension=function(extensions,f,name)
- local extension=extensions[name] or "tostring(%s)"
- local f=tonumber(f) or 1
- local w=find(extension,"%.%.%.")
- if f==0 then
- if w then
- extension=gsub(extension,"%.%.%.","")
- end
- return extension
- elseif f==1 then
- if w then
- extension=gsub(extension,"%.%.%.","%%s")
- end
- n=n+1
- local a="a"..n
- return format(extension,a,a)
- elseif f<0 then
- if w then
- extension=gsub(extension,"%.%.%.","")
- return extension
- else
- local a="a"..(n+f+1)
- return format(extension,a,a)
- end
- else
- if w then
- extension=gsub(extension,"%.%.%.",rep("%%s,",f-1).."%%s")
- end
- local t={}
- for i=1,f do
- n=n+1
- t[i]="a"..n
- end
- return format(extension,unpack(t))
- end
-end
-local builder=Cs { "start",
- start=(
- (
- P("%")/""*(
- V("!")
-+V("s")+V("q")+V("i")+V("d")+V("f")+V("F")+V("g")+V("G")+V("e")+V("E")+V("x")+V("X")+V("o")
-+V("c")+V("C")+V("S")
-+V("Q")
-+V("n")
-+V("N")
-+V("k")
-+V("r")+V("h")+V("H")+V("u")+V("U")+V("p")+V("P")+V("b")+V("B")+V("t")+V("T")+V("l")+V("L")+V("I")+V("w")
-+V("W")
-+V("a")
-+V("A")
-+V("j")+V("J")
-+V("m")+V("M")
-+V("z")
-+V(">")
-+V("<")
- )+V("*")
- )*(endofstring+Carg(1))
- )^0,
- ["s"]=(prefix_any*P("s"))/format_s,
- ["q"]=(prefix_any*P("q"))/format_q,
- ["i"]=(prefix_any*P("i"))/format_i,
- ["d"]=(prefix_any*P("d"))/format_d,
- ["f"]=(prefix_any*P("f"))/format_f,
- ["F"]=(prefix_any*P("F"))/format_F,
- ["g"]=(prefix_any*P("g"))/format_g,
- ["G"]=(prefix_any*P("G"))/format_G,
- ["e"]=(prefix_any*P("e"))/format_e,
- ["E"]=(prefix_any*P("E"))/format_E,
- ["x"]=(prefix_any*P("x"))/format_x,
- ["X"]=(prefix_any*P("X"))/format_X,
- ["o"]=(prefix_any*P("o"))/format_o,
- ["S"]=(prefix_any*P("S"))/format_S,
- ["Q"]=(prefix_any*P("Q"))/format_Q,
- ["n"]=(prefix_any*P("n"))/format_n,
- ["N"]=(prefix_any*P("N"))/format_N,
- ["k"]=(prefix_sub*P("k"))/format_k,
- ["c"]=(prefix_any*P("c"))/format_c,
- ["C"]=(prefix_any*P("C"))/format_C,
- ["r"]=(prefix_any*P("r"))/format_r,
- ["h"]=(prefix_any*P("h"))/format_h,
- ["H"]=(prefix_any*P("H"))/format_H,
- ["u"]=(prefix_any*P("u"))/format_u,
- ["U"]=(prefix_any*P("U"))/format_U,
- ["p"]=(prefix_any*P("p"))/format_p,
- ["P"]=(prefix_any*P("P"))/format_P,
- ["b"]=(prefix_any*P("b"))/format_b,
- ["B"]=(prefix_any*P("B"))/format_B,
- ["t"]=(prefix_tab*P("t"))/format_t,
- ["T"]=(prefix_tab*P("T"))/format_T,
- ["l"]=(prefix_any*P("l"))/format_l,
- ["L"]=(prefix_any*P("L"))/format_L,
- ["I"]=(prefix_any*P("I"))/format_I,
- ["w"]=(prefix_any*P("w"))/format_w,
- ["W"]=(prefix_any*P("W"))/format_W,
- ["j"]=(prefix_any*P("j"))/format_j,
- ["J"]=(prefix_any*P("J"))/format_J,
- ["m"]=(prefix_any*P("m"))/format_m,
- ["M"]=(prefix_any*P("M"))/format_M,
- ["z"]=(prefix_any*P("z"))/format_z,
- ["a"]=(prefix_any*P("a"))/format_a,
- ["A"]=(prefix_any*P("A"))/format_A,
- ["<"]=(prefix_any*P("<"))/format_left,
- [">"]=(prefix_any*P(">"))/format_right,
- ["*"]=Cs(((1-P("%"))^1+P("%%")/"%%")^1)/format_rest,
- ["?"]=Cs(((1-P("%"))^1 )^1)/format_rest,
- ["!"]=Carg(2)*prefix_any*P("!")*C((1-P("!"))^1)*P("!")/format_extension,
-}
-local xx=setmetatable({},{ __index=function(t,k) local v=format("%02x",k) t[k]=v return v end })
-local XX=setmetatable({},{ __index=function(t,k) local v=format("%02X",k) t[k]=v return v end })
-local preset={
- ["%02x"]=function(n) return xx[n] end,
- ["%02X"]=function(n) return XX[n] end,
-}
-local direct=P("%")*(sign+space+period+digit)^0*S("sqidfgGeExXo")*endofstring/[[local format = string.format return function(str) return format("%0",str) end]]
-local function make(t,str)
- local f=preset[str]
- if f then
- return f
- end
- local p=lpegmatch(direct,str)
- if p then
- f=loadstripped(p)()
- else
- n=0
- p=lpegmatch(builder,str,1,t._connector_,t._extensions_)
- if n>0 then
- p=format(template,preamble,t._preamble_,arguments[n],p)
- f=loadstripped(p,t._environment_)()
- else
- f=function() return str end
- end
- end
- t[str]=f
- return f
-end
-local function use(t,fmt,...)
- return t[fmt](...)
-end
-strings.formatters={}
-function strings.formatters.new(noconcat)
- local e={}
- for k,v in next,environment do
- e[k]=v
- end
- local t={
- _type_="formatter",
- _connector_=noconcat and "," or "..",
- _extensions_={},
- _preamble_="",
- _environment_=e,
- }
- setmetatable(t,{ __index=make,__call=use })
- return t
-end
-local formatters=strings.formatters.new()
-string.formatters=formatters
-string.formatter=function(str,...) return formatters[str](...) end
-local function add(t,name,template,preamble)
- if type(t)=="table" and t._type_=="formatter" then
- t._extensions_[name]=template or "%s"
- if type(preamble)=="string" then
- t._preamble_=preamble.."\n"..t._preamble_
- elseif type(preamble)=="table" then
- for k,v in next,preamble do
- t._environment_[k]=v
- end
- end
- end
-end
-strings.formatters.add=add
-patterns.xmlescape=Cs((P("<")/"&lt;"+P(">")/"&gt;"+P("&")/"&amp;"+P('"')/"&quot;"+anything)^0)
-patterns.texescape=Cs((C(S("#$%\\{}"))/"\\%1"+anything)^0)
-patterns.luaescape=Cs(((1-S('"\n'))^1+P('"')/'\\"'+P('\n')/'\\n"')^0)
-patterns.luaquoted=Cs(Cc('"')*((1-S('"\n'))^1+P('"')/'\\"'+P('\n')/'\\n"')^0*Cc('"'))
-add(formatters,"xml",[[lpegmatch(xmlescape,%s)]],{ xmlescape=patterns.xmlescape })
-add(formatters,"tex",[[lpegmatch(texescape,%s)]],{ texescape=patterns.texescape })
-add(formatters,"lua",[[lpegmatch(luaescape,%s)]],{ luaescape=patterns.luaescape })
-local dquote=patterns.dquote
-local equote=patterns.escaped+dquote/'\\"'+1
-local cquote=Cc('"')
-local pattern=Cs(dquote*(equote-P(-2))^0*dquote)
-+Cs(cquote*(equote-space)^0*space*equote^0*cquote)
-function string.optionalquoted(str)
- return lpegmatch(pattern,str) or str
-end
-local pattern=Cs((newline/(os.newline or "\r")+1)^0)
-function string.replacenewlines(str)
- return lpegmatch(pattern,str)
-end
-function strings.newcollector()
- local result,r={},0
- return
- function(fmt,str,...)
- r=r+1
- result[r]=str==nil and fmt or formatters[fmt](str,...)
- end,
- function(connector)
- if result then
- local str=concat(result,connector)
- result,r={},0
- return str
- end
- end
-end
-local f_16_16=formatters["%0.5N"]
-function number.to16dot16(n)
- return f_16_16(n/65536.0)
-end
-if not string.explode then
- local tsplitat=lpeg.tsplitat
- local p_utf=patterns.utf8character
- local p_check=C(p_utf)*(P("+")*Cc(true))^0
- local p_split=Ct(C(p_utf)^0)
- local p_space=Ct((C(1-P(" ")^1)+P(" ")^1)^0)
- function string.explode(str,symbol)
- if symbol=="" then
- return lpegmatch(p_split,str)
- elseif symbol then
- local a,b=lpegmatch(p_check,symbol)
- if b then
- return lpegmatch(tsplitat(P(a)^1),str)
- else
- return lpegmatch(tsplitat(a),str)
- end
- else
- return lpegmatch(p_space,str)
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-tab"] = package.loaded["util-tab"] or true
-
--- original size: 32815, stripped down to: 18257
-
-if not modules then modules={} end modules ['util-tab']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities=utilities or {}
-utilities.tables=utilities.tables or {}
-local tables=utilities.tables
-local format,gmatch,gsub,sub=string.format,string.gmatch,string.gsub,string.sub
-local concat,insert,remove,sort=table.concat,table.insert,table.remove,table.sort
-local setmetatable,getmetatable,tonumber,tostring,rawget=setmetatable,getmetatable,tonumber,tostring,rawget
-local type,next,rawset,tonumber,tostring,load,select=type,next,rawset,tonumber,tostring,load,select
-local lpegmatch,P,Cs,Cc=lpeg.match,lpeg.P,lpeg.Cs,lpeg.Cc
-local sortedkeys,sortedpairs=table.sortedkeys,table.sortedpairs
-local formatters=string.formatters
-local utftoeight=utf.toeight
-local splitter=lpeg.tsplitat(".")
-function utilities.tables.definetable(target,nofirst,nolast)
- local composed=nil
- local t={}
- local snippets=lpegmatch(splitter,target)
- for i=1,#snippets-(nolast and 1 or 0) do
- local name=snippets[i]
- if composed then
- composed=composed.."."..name
- t[#t+1]=formatters["if not %s then %s = { } end"](composed,composed)
- else
- composed=name
- if not nofirst then
- t[#t+1]=formatters["%s = %s or { }"](composed,composed)
- end
- end
- end
- if composed then
- if nolast then
- composed=composed.."."..snippets[#snippets]
- end
- return concat(t,"\n"),composed
- else
- return "",target
- end
-end
-function tables.definedtable(...)
- local t=_G
- for i=1,select("#",...) do
- local li=select(i,...)
- local tl=t[li]
- if not tl then
- tl={}
- t[li]=tl
- end
- t=tl
- end
- return t
-end
-function tables.accesstable(target,root)
- local t=root or _G
- for name in gmatch(target,"([^%.]+)") do
- t=t[name]
- if not t then
- return
- end
- end
- return t
-end
-function tables.migratetable(target,v,root)
- local t=root or _G
- local names=lpegmatch(splitter,target)
- for i=1,#names-1 do
- local name=names[i]
- t[name]=t[name] or {}
- t=t[name]
- if not t then
- return
- end
- end
- t[names[#names]]=v
-end
-function tables.removevalue(t,value)
- if value then
- for i=1,#t do
- if t[i]==value then
- remove(t,i)
- end
- end
- end
-end
-function tables.replacevalue(t,oldvalue,newvalue)
- if oldvalue and newvalue then
- for i=1,#t do
- if t[i]==oldvalue then
- t[i]=newvalue
- end
- end
- end
-end
-function tables.insertbeforevalue(t,value,extra)
- for i=1,#t do
- if t[i]==extra then
- remove(t,i)
- end
- end
- for i=1,#t do
- if t[i]==value then
- insert(t,i,extra)
- return
- end
- end
- insert(t,1,extra)
-end
-function tables.insertaftervalue(t,value,extra)
- for i=1,#t do
- if t[i]==extra then
- remove(t,i)
- end
- end
- for i=1,#t do
- if t[i]==value then
- insert(t,i+1,extra)
- return
- end
- end
- insert(t,#t+1,extra)
-end
-local escape=Cs(Cc('"')*((P('"')/'""'+P(1))^0)*Cc('"'))
-function table.tocsv(t,specification)
- if t and #t>0 then
- local result={}
- local r={}
- specification=specification or {}
- local fields=specification.fields
- if type(fields)~="string" then
- fields=sortedkeys(t[1])
- end
- local separator=specification.separator or ","
- local noffields=#fields
- if specification.preamble==true then
- for f=1,noffields do
- r[f]=lpegmatch(escape,tostring(fields[f]))
- end
- result[1]=concat(r,separator)
- end
- for i=1,#t do
- local ti=t[i]
- for f=1,noffields do
- local field=ti[fields[f]]
- if type(field)=="string" then
- r[f]=lpegmatch(escape,field)
- else
- r[f]=tostring(field)
- end
- end
- result[i+1]=concat(r,separator)
- end
- return concat(result,"\n")
- else
- return ""
- end
-end
-local nspaces=utilities.strings.newrepeater(" ")
-local function toxml(t,d,result,step)
- local r=#result
- for k,v in sortedpairs(t) do
- local s=nspaces[d]
- local tk=type(k)
- local tv=type(v)
- if tv=="table" then
- if tk=="number" then
- r=r+1 result[r]=formatters["%s<entry n='%s'>"](s,k)
- toxml(v,d+step,result,step)
- r=r+1 result[r]=formatters["%s</entry>"](s,k)
- else
- r=r+1 result[r]=formatters["%s<%s>"](s,k)
- toxml(v,d+step,result,step)
- r=r+1 result[r]=formatters["%s</%s>"](s,k)
- end
- elseif tv=="string" then
- if tk=="number" then
- r=r+1 result[r]=formatters["%s<entry n='%s'>%!xml!</entry>"](s,k,v,k)
- else
- r=r+1 result[r]=formatters["%s<%s>%!xml!</%s>"](s,k,v,k)
- end
- elseif tk=="number" then
- r=r+1 result[r]=formatters["%s<entry n='%s'>%S</entry>"](s,k,v,k)
- else
- r=r+1 result[r]=formatters["%s<%s>%S</%s>"](s,k,v,k)
- end
- end
-end
-function table.toxml(t,specification)
- specification=specification or {}
- local name=specification.name
- local noroot=name==false
- local result=(specification.nobanner or noroot) and {} or { "<?xml version='1.0' standalone='yes' ?>" }
- local indent=specification.indent or 0
- local spaces=specification.spaces or 1
- if noroot then
- toxml(t,indent,result,spaces)
- else
- toxml({ [name or "data"]=t },indent,result,spaces)
- end
- return concat(result,"\n")
-end
-function tables.encapsulate(core,capsule,protect)
- if type(capsule)~="table" then
- protect=true
- capsule={}
- end
- for key,value in next,core do
- if capsule[key] then
- print(formatters["\ninvalid %s %a in %a"]("inheritance",key,core))
- os.exit()
- else
- capsule[key]=value
- end
- end
- if protect then
- for key,value in next,core do
- core[key]=nil
- end
- setmetatable(core,{
- __index=capsule,
- __newindex=function(t,key,value)
- if capsule[key] then
- print(formatters["\ninvalid %s %a' in %a"]("overload",key,core))
- os.exit()
- else
- rawset(t,key,value)
- end
- end
- } )
- end
-end
-if JITSUPPORTED then
- local f_hashed_string=formatters["[%Q]=%Q,"]
- local f_hashed_number=formatters["[%Q]=%s,"]
- local f_hashed_boolean=formatters["[%Q]=%l,"]
- local f_hashed_table=formatters["[%Q]="]
- local f_indexed_string=formatters["[%s]=%Q,"]
- local f_indexed_number=formatters["[%s]=%s,"]
- local f_indexed_boolean=formatters["[%s]=%l,"]
- local f_indexed_table=formatters["[%s]="]
- local f_ordered_string=formatters["%Q,"]
- local f_ordered_number=formatters["%s,"]
- local f_ordered_boolean=formatters["%l,"]
- function table.fastserialize(t,prefix)
- local r={ type(prefix)=="string" and prefix or "return" }
- local m=1
- local function fastserialize(t,outer)
- local n=#t
- m=m+1
- r[m]="{"
- if n>0 then
- local v=t[0]
- if v then
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_indexed_string(0,v)
- elseif tv=="number" then
- m=m+1 r[m]=f_indexed_number(0,v)
- elseif tv=="table" then
- m=m+1 r[m]=f_indexed_table(0)
- fastserialize(v)
- m=m+1 r[m]=f_indexed_table(0)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_indexed_boolean(0,v)
- end
- end
- for i=1,n do
- local v=t[i]
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_ordered_string(v)
- elseif tv=="number" then
- m=m+1 r[m]=f_ordered_number(v)
- elseif tv=="table" then
- fastserialize(v)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_ordered_boolean(v)
- end
- end
- end
- for k,v in next,t do
- local tk=type(k)
- if tk=="number" then
- if k>n or k<0 then
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_indexed_string(k,v)
- elseif tv=="number" then
- m=m+1 r[m]=f_indexed_number(k,v)
- elseif tv=="table" then
- m=m+1 r[m]=f_indexed_table(k)
- fastserialize(v)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_indexed_boolean(k,v)
- end
- end
- else
- local tv=type(v)
- if tv=="string" then
- m=m+1 r[m]=f_hashed_string(k,v)
- elseif tv=="number" then
- m=m+1 r[m]=f_hashed_number(k,v)
- elseif tv=="table" then
- m=m+1 r[m]=f_hashed_table(k)
- fastserialize(v)
- elseif tv=="boolean" then
- m=m+1 r[m]=f_hashed_boolean(k,v)
- end
- end
- end
- m=m+1
- if outer then
- r[m]="}"
- else
- r[m]="},"
- end
- return r
- end
- return concat(fastserialize(t,true))
- end
-else
- local f_v=formatters["[%q]=%q,"]
- local f_t=formatters["[%q]="]
- local f_q=formatters["%q,"]
- function table.fastserialize(t,prefix)
- local r={ type(prefix)=="string" and prefix or "return" }
- local m=1
- local function fastserialize(t,outer)
- local n=#t
- m=m+1
- r[m]="{"
- if n>0 then
- local v=t[0]
- if v then
- m=m+1
- r[m]="[0]='"
- if type(v)=="table" then
- fastserialize(v)
- else
- r[m]=format("%q,",v)
- end
- end
- for i=1,n do
- local v=t[i]
- m=m+1
- if type(v)=="table" then
- r[m]=format("[%i]=",i)
- fastserialize(v)
- else
- r[m]=format("[%i]=%q,",i,v)
- end
- end
- end
- for k,v in next,t do
- local tk=type(k)
- if tk=="number" then
- if k>n or k<0 then
- m=m+1
- if type(v)=="table" then
- r[m]=format("[%i]=",k)
- fastserialize(v)
- else
- r[m]=format("[%i]=%q,",k,v)
- end
- end
- else
- m=m+1
- if type(v)=="table" then
- r[m]=format("[%q]=",k)
- fastserialize(v)
- else
- r[m]=format("[%q]=%q,",k,v)
- end
- end
- end
- m=m+1
- if outer then
- r[m]="}"
- else
- r[m]="},"
- end
- return r
- end
- return concat(fastserialize(t,true))
- end
-end
-function table.deserialize(str)
- if not str or str=="" then
- return
- end
- local code=load(str)
- if not code then
- return
- end
- code=code()
- if not code then
- return
- end
- return code
-end
-function table.load(filename,loader)
- if filename then
- local t=(loader or io.loaddata)(filename)
- if t and t~="" then
- local t=utftoeight(t)
- t=load(t)
- if type(t)=="function" then
- t=t()
- if type(t)=="table" then
- return t
- end
- end
- end
- end
-end
-function table.save(filename,t,n,...)
- io.savedata(filename,table.serialize(t,n==nil and true or n,...))
-end
-local f_key_value=formatters["%s=%q"]
-local f_add_table=formatters[" {%t},\n"]
-local f_return_table=formatters["return {\n%t}"]
-local function slowdrop(t)
- local r={}
- local l={}
- for i=1,#t do
- local ti=t[i]
- local j=0
- for k,v in next,ti do
- j=j+1
- l[j]=f_key_value(k,v)
- end
- r[i]=f_add_table(l)
- end
- return f_return_table(r)
-end
-local function fastdrop(t)
- local r={ "return {\n" }
- local m=1
- for i=1,#t do
- local ti=t[i]
- m=m+1 r[m]=" {"
- for k,v in next,ti do
- m=m+1 r[m]=f_key_value(k,v)
- end
- m=m+1 r[m]="},\n"
- end
- m=m+1
- r[m]="}"
- return concat(r)
-end
-function table.drop(t,slow)
- if #t==0 then
- return "return { }"
- elseif slow==true then
- return slowdrop(t)
- else
- return fastdrop(t)
- end
-end
-local selfmapper={ __index=function(t,k) t[k]=k return k end }
-function table.twowaymapper(t)
- if not t then
- t={}
- else
- local zero=rawget(t,0)
- for i=zero and 0 or 1,#t do
- local ti=t[i]
- if ti then
- local i=tostring(i)
- t[i]=ti
- t[ti]=i
- end
- end
- end
- setmetatable(t,selfmapper)
- return t
-end
-local f_start_key_idx=formatters["%w{"]
-local f_start_key_num=JITSUPPORTED and formatters["%w[%s]={"] or formatters["%w[%q]={"]
-local f_start_key_str=formatters["%w[%q]={"]
-local f_start_key_boo=formatters["%w[%l]={"]
-local f_start_key_nop=formatters["%w{"]
-local f_stop=formatters["%w},"]
-local f_key_num_value_num=JITSUPPORTED and formatters["%w[%s]=%s,"] or formatters["%w[%s]=%q,"]
-local f_key_str_value_num=JITSUPPORTED and formatters["%w[%Q]=%s,"] or formatters["%w[%Q]=%q,"]
-local f_key_boo_value_num=JITSUPPORTED and formatters["%w[%l]=%s,"] or formatters["%w[%l]=%q,"]
-local f_key_num_value_str=JITSUPPORTED and formatters["%w[%s]=%Q,"] or formatters["%w[%q]=%Q,"]
-local f_key_str_value_str=formatters["%w[%Q]=%Q,"]
-local f_key_boo_value_str=formatters["%w[%l]=%Q,"]
-local f_key_num_value_boo=JITSUPPORTED and formatters["%w[%s]=%l,"] or formatters["%w[%q]=%l,"]
-local f_key_str_value_boo=formatters["%w[%Q]=%l,"]
-local f_key_boo_value_boo=formatters["%w[%l]=%l,"]
-local f_key_num_value_not=JITSUPPORTED and formatters["%w[%s]={},"] or formatters["%w[%q]={},"]
-local f_key_str_value_not=formatters["%w[%Q]={},"]
-local f_key_boo_value_not=formatters["%w[%l]={},"]
-local f_key_num_value_seq=JITSUPPORTED and formatters["%w[%s]={ %, t },"] or formatters["%w[%q]={ %, t },"]
-local f_key_str_value_seq=formatters["%w[%Q]={ %, t },"]
-local f_key_boo_value_seq=formatters["%w[%l]={ %, t },"]
-local f_val_num=JITSUPPORTED and formatters["%w%s,"] or formatters["%w%q,"]
-local f_val_str=formatters["%w%Q,"]
-local f_val_boo=formatters["%w%l,"]
-local f_val_not=formatters["%w{},"]
-local f_val_seq=formatters["%w{ %, t },"]
-local f_fin_seq=formatters[" %, t }"]
-local f_table_return=formatters["return {"]
-local f_table_name=formatters["%s={"]
-local f_table_direct=formatters["{"]
-local f_table_entry=formatters["[%Q]={"]
-local f_table_finish=formatters["}"]
-local spaces=utilities.strings.newrepeater(" ")
-local original_serialize=table.serialize
-local is_simple_table=table.is_simple_table
-local function serialize(root,name,specification)
- if type(specification)=="table" then
- return original_serialize(root,name,specification)
- end
- local t
- local n=1
- local unknown=false
- local function do_serialize(root,name,depth,level,indexed)
- if level>0 then
- n=n+1
- if indexed then
- t[n]=f_start_key_idx(depth)
- else
- local tn=type(name)
- if tn=="number" then
- t[n]=f_start_key_num(depth,name)
- elseif tn=="string" then
- t[n]=f_start_key_str(depth,name)
- elseif tn=="boolean" then
- t[n]=f_start_key_boo(depth,name)
- else
- t[n]=f_start_key_nop(depth)
- end
- end
- depth=depth+1
- end
- if root and next(root)~=nil then
- local first=nil
- local last=#root
- if last>0 then
- for k=1,last do
- if rawget(root,k)==nil then
- last=k-1
- break
- end
- end
- if last>0 then
- first=1
- end
- end
- local sk=sortedkeys(root)
- for i=1,#sk do
- local k=sk[i]
- local v=root[k]
- local tv=type(v)
- local tk=type(k)
- if first and tk=="number" and k<=last and k>=first then
- if tv=="number" then
- n=n+1 t[n]=f_val_num(depth,v)
- elseif tv=="string" then
- n=n+1 t[n]=f_val_str(depth,v)
- elseif tv=="table" then
- if next(v)==nil then
- n=n+1 t[n]=f_val_not(depth)
- else
- local st=is_simple_table(v)
- if st then
- n=n+1 t[n]=f_val_seq(depth,st)
- else
- do_serialize(v,k,depth,level+1,true)
- end
- end
- elseif tv=="boolean" then
- n=n+1 t[n]=f_val_boo(depth,v)
- elseif unknown then
- n=n+1 t[n]=f_val_str(depth,tostring(v))
- end
- elseif tv=="number" then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_num(depth,k,v)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_num(depth,k,v)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_num(depth,k,v)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_num(depth,tostring(k),v)
- end
- elseif tv=="string" then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_str(depth,k,v)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_str(depth,k,v)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_str(depth,k,v)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_str(depth,tostring(k),v)
- end
- elseif tv=="table" then
- if next(v)==nil then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_not(depth,k)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_not(depth,k)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_not(depth,k)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_not(depth,tostring(k))
- end
- else
- local st=is_simple_table(v)
- if not st then
- do_serialize(v,k,depth,level+1)
- elseif tk=="number" then
- n=n+1 t[n]=f_key_num_value_seq(depth,k,st)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_seq(depth,k,st)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_seq(depth,k,st)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_seq(depth,tostring(k),st)
- end
- end
- elseif tv=="boolean" then
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_boo(depth,k,v)
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_boo(depth,k,v)
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_boo(depth,k,v)
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_boo(depth,tostring(k),v)
- end
- else
- if tk=="number" then
- n=n+1 t[n]=f_key_num_value_str(depth,k,tostring(v))
- elseif tk=="string" then
- n=n+1 t[n]=f_key_str_value_str(depth,k,tostring(v))
- elseif tk=="boolean" then
- n=n+1 t[n]=f_key_boo_value_str(depth,k,tostring(v))
- elseif unknown then
- n=n+1 t[n]=f_key_str_value_str(depth,tostring(k),tostring(v))
- end
- end
- end
- end
- if level>0 then
- n=n+1 t[n]=f_stop(depth-1)
- end
- end
- local tname=type(name)
- if tname=="string" then
- if name=="return" then
- t={ f_table_return() }
- else
- t={ f_table_name(name) }
- end
- elseif tname=="number" then
- t={ f_table_entry(name) }
- elseif tname=="boolean" then
- if name then
- t={ f_table_return() }
- else
- t={ f_table_direct() }
- end
- else
- t={ f_table_name("t") }
- end
- if root then
- if getmetatable(root) then
- local dummy=root._w_h_a_t_e_v_e_r_
- root._w_h_a_t_e_v_e_r_=nil
- end
- if next(root)~=nil then
- local st=is_simple_table(root)
- if st then
- return t[1]..f_fin_seq(st)
- else
- do_serialize(root,name,1,0)
- end
- end
- end
- n=n+1
- t[n]=f_table_finish()
- return concat(t,"\n")
-end
-table.serialize=serialize
-if setinspector then
- setinspector("table",function(v)
- if type(v)=="table" then
- print(serialize(v,"table",{ metacheck=false }))
- return true
- end
- end)
-end
-local mt={
- __newindex=function(t,k,v)
- local n=t.last+1
- t.last=n
- t.list[n]=k
- t.hash[k]=v
- end,
- __index=function(t,k)
- return t.hash[k]
- end,
- __len=function(t)
- return t.last
- end,
-}
-function table.orderedhash()
- return setmetatable({ list={},hash={},last=0 },mt)
-end
-function table.ordered(t)
- local n=t.last
- if n>0 then
- local l=t.list
- local i=1
- local h=t.hash
- local f=function()
- if i<=n then
- local k=i
- local v=h[l[k]]
- i=i+1
- return k,v
- end
- end
- return f,1,h[l[1]]
- else
- return function() end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-fil"] = package.loaded["util-fil"] or true
-
--- original size: 11552, stripped down to: 9023
-
-if not modules then modules={} end modules ['util-fil']={
- version=1.001,
- optimize=true,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local tonumber=tonumber
-local byte=string.byte
-local char=string.char
-utilities=utilities or {}
-local files={}
-utilities.files=files
-local zerobased={}
-function files.open(filename,zb)
- local f=io.open(filename,"rb")
- if f then
- zerobased[f]=zb or false
- end
- return f
-end
-function files.close(f)
- zerobased[f]=nil
- f:close()
-end
-function files.size(f)
- local current=f:seek()
- local size=f:seek("end")
- f:seek("set",current)
- return size
-end
-files.getsize=files.size
-function files.setposition(f,n)
- if zerobased[f] then
- f:seek("set",n)
- else
- f:seek("set",n-1)
- end
-end
-function files.getposition(f)
- if zerobased[f] then
- return f:seek()
- else
- return f:seek()+1
- end
-end
-function files.look(f,n,chars)
- local p=f:seek()
- local s=f:read(n)
- f:seek("set",p)
- if chars then
- return s
- else
- return byte(s,1,#s)
- end
-end
-function files.skip(f,n)
- if n==1 then
- f:read(n)
- else
- f:seek("set",f:seek()+n)
- end
-end
-function files.readbyte(f)
- return byte(f:read(1))
-end
-function files.readbytes(f,n)
- return byte(f:read(n),1,n)
-end
-function files.readbytetable(f,n)
- local s=f:read(n or 1)
- return { byte(s,1,#s) }
-end
-function files.readchar(f)
- return f:read(1)
-end
-function files.readstring(f,n)
- return f:read(n or 1)
-end
-function files.readinteger1(f)
- local n=byte(f:read(1))
- if n>=0x80 then
- return n-0x100
- else
- return n
- end
-end
-files.readcardinal1=files.readbyte
-files.readcardinal=files.readcardinal1
-files.readinteger=files.readinteger1
-files.readsignedbyte=files.readinteger1
-function files.readcardinal2(f)
- local a,b=byte(f:read(2),1,2)
- return 0x100*a+b
-end
-function files.readcardinal2le(f)
- local b,a=byte(f:read(2),1,2)
- return 0x100*a+b
-end
-function files.readinteger2(f)
- local a,b=byte(f:read(2),1,2)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function files.readinteger2le(f)
- local b,a=byte(f:read(2),1,2)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function files.readcardinal3(f)
- local a,b,c=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
-end
-function files.readcardinal3le(f)
- local c,b,a=byte(f:read(3),1,3)
- return 0x10000*a+0x100*b+c
-end
-function files.readinteger3(f)
- local a,b,c=byte(f:read(3),1,3)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function files.readinteger3le(f)
- local c,b,a=byte(f:read(3),1,3)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function files.readcardinal4(f)
- local a,b,c,d=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function files.readcardinal4le(f)
- local d,c,b,a=byte(f:read(4),1,4)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function files.readinteger4(f)
- local a,b,c,d=byte(f:read(4),1,4)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function files.readinteger4le(f)
- local d,c,b,a=byte(f:read(4),1,4)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function files.readfixed2(f)
- local a,b=byte(f:read(2),1,2)
- if a>=0x80 then
- tonumber((a-0x100).."."..b)
- else
- tonumber((a ).."."..b)
- end
-end
-function files.readfixed4(f)
- local a,b,c,d=byte(f:read(4),1,4)
- if a>=0x80 then
- tonumber((0x100*a+b-0x10000).."."..(0x100*c+d))
- else
- tonumber((0x100*a+b ).."."..(0x100*c+d))
- end
-end
-if bit32 then
- local extract=bit32.extract
- local band=bit32.band
- function files.read2dot14(f)
- local a,b=byte(f:read(2),1,2)
- if a>=0x80 then
- local n=-(0x100*a+b)
- return-(extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- else
- local n=0x100*a+b
- return (extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- end
- end
-end
-function files.skipshort(f,n)
- f:read(2*(n or 1))
-end
-function files.skiplong(f,n)
- f:read(4*(n or 1))
-end
-if bit32 then
- local rshift=bit32.rshift
- function files.writecardinal2(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- f:write(b,a)
- end
- function files.writecardinal4(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- n=rshift(n,8)
- local c=char(n%256)
- n=rshift(n,8)
- local d=char(n%256)
- f:write(d,c,b,a)
- end
- function files.writecardinal2le(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- f:write(a,b)
- end
- function files.writecardinal4le(f,n)
- local a=char(n%256)
- n=rshift(n,8)
- local b=char(n%256)
- n=rshift(n,8)
- local c=char(n%256)
- n=rshift(n,8)
- local d=char(n%256)
- f:write(a,b,c,d)
- end
-else
- local floor=math.floor
- function files.writecardinal2(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- f:write(b,a)
- end
- function files.writecardinal4(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- n=floor(n/256)
- local c=char(n%256)
- n=floor(n/256)
- local d=char(n%256)
- f:write(d,c,b,a)
- end
- function files.writecardinal2le(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- f:write(a,b)
- end
- function files.writecardinal4le(f,n)
- local a=char(n%256)
- n=floor(n/256)
- local b=char(n%256)
- n=floor(n/256)
- local c=char(n%256)
- n=floor(n/256)
- local d=char(n%256)
- f:write(a,b,c,d)
- end
-end
-function files.writestring(f,s)
- f:write(char(byte(s,1,#s)))
-end
-function files.writebyte(f,b)
- f:write(char(b))
-end
-if fio and fio.readcardinal1 then
- files.readcardinal1=fio.readcardinal1
- files.readcardinal2=fio.readcardinal2
- files.readcardinal3=fio.readcardinal3
- files.readcardinal4=fio.readcardinal4
- files.readcardinal1le=fio.readcardinal1le or files.readcardinal1le
- files.readcardinal2le=fio.readcardinal2le or files.readcardinal2le
- files.readcardinal3le=fio.readcardinal3le or files.readcardinal3le
- files.readcardinal4le=fio.readcardinal4le or files.readcardinal4le
- files.readinteger1=fio.readinteger1
- files.readinteger2=fio.readinteger2
- files.readinteger3=fio.readinteger3
- files.readinteger4=fio.readinteger4
- files.readinteger1le=fio.readinteger1le or files.readinteger1le
- files.readinteger2le=fio.readinteger2le or files.readinteger2le
- files.readinteger3le=fio.readinteger3le or files.readinteger3le
- files.readinteger4le=fio.readinteger4le or files.readinteger4le
- files.readfixed2=fio.readfixed2
- files.readfixed4=fio.readfixed4
- files.read2dot14=fio.read2dot14
- files.setposition=fio.setposition
- files.getposition=fio.getposition
- files.readbyte=files.readcardinal1
- files.readsignedbyte=files.readinteger1
- files.readcardinal=files.readcardinal1
- files.readinteger=files.readinteger1
- local skipposition=fio.skipposition
- files.skipposition=skipposition
- files.readbytes=fio.readbytes
- files.readbytetable=fio.readbytetable
- function files.skipshort(f,n)
- skipposition(f,2*(n or 1))
- end
- function files.skiplong(f,n)
- skipposition(f,4*(n or 1))
- end
-end
-if fio and fio.writecardinal1 then
- files.writecardinal1=fio.writecardinal1
- files.writecardinal2=fio.writecardinal2
- files.writecardinal3=fio.writecardinal3
- files.writecardinal4=fio.writecardinal4
- files.writecardinal1le=fio.writecardinal1le
- files.writecardinal2le=fio.writecardinal2le
- files.writecardinal3le=fio.writecardinal3le
- files.writecardinal4le=fio.writecardinal4le
- files.writeinteger1=fio.writeinteger1 or fio.writecardinal1
- files.writeinteger2=fio.writeinteger2 or fio.writecardinal2
- files.writeinteger3=fio.writeinteger3 or fio.writecardinal3
- files.writeinteger4=fio.writeinteger4 or fio.writecardinal4
- files.writeinteger1le=files.writeinteger1le or fio.writecardinal1le
- files.writeinteger2le=files.writeinteger2le or fio.writecardinal2le
- files.writeinteger3le=files.writeinteger3le or fio.writecardinal3le
- files.writeinteger4le=files.writeinteger4le or fio.writecardinal4le
-end
-if fio and fio.readcardinaltable then
- files.readcardinaltable=fio.readcardinaltable
- files.readintegertable=fio.readintegertable
-else
- local readcardinal1=files.readcardinal1
- local readcardinal2=files.readcardinal2
- local readcardinal3=files.readcardinal3
- local readcardinal4=files.readcardinal4
- function files.readcardinaltable(f,n,b)
- local t={}
- if b==1 then for i=1,n do t[i]=readcardinal1(f) end
- elseif b==2 then for i=1,n do t[i]=readcardinal2(f) end
- elseif b==3 then for i=1,n do t[i]=readcardinal3(f) end
- elseif b==4 then for i=1,n do t[i]=readcardinal4(f) end end
- return t
- end
- local readinteger1=files.readinteger1
- local readinteger2=files.readinteger2
- local readinteger3=files.readinteger3
- local readinteger4=files.readinteger4
- function files.readintegertable(f,n,b)
- local t={}
- if b==1 then for i=1,n do t[i]=readinteger1(f) end
- elseif b==2 then for i=1,n do t[i]=readinteger2(f) end
- elseif b==3 then for i=1,n do t[i]=readinteger3(f) end
- elseif b==4 then for i=1,n do t[i]=readinteger4(f) end end
- return t
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-sac"] = package.loaded["util-sac"] or true
-
--- original size: 12968, stripped down to: 9523
-
-if not modules then modules={} end modules ['util-sac']={
- version=1.001,
- optimize=true,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local byte,sub=string.byte,string.sub
-local tonumber=tonumber
-utilities=utilities or {}
-local streams={}
-utilities.streams=streams
-function streams.open(filename,zerobased)
- local f=filename and io.loaddata(filename)
- if f then
- return { f,1,#f,zerobased or false }
- end
-end
-function streams.openstring(f,zerobased)
- if f then
- return { f,1,#f,zerobased or false }
- end
-end
-function streams.getstring(f)
- if f then
- return f[1]
- end
-end
-function streams.close()
-end
-function streams.size(f)
- return f and f[3] or 0
-end
-streams.getsize=streams.size
-function streams.setposition(f,i)
- if f[4] then
- if i<=0 then
- f[2]=1
- else
- f[2]=i+1
- end
- else
- if i<=1 then
- f[2]=1
- else
- f[2]=i
- end
- end
-end
-function streams.getposition(f)
- if f[4] then
- return f[2]-1
- else
- return f[2]
- end
-end
-function streams.look(f,n,chars)
- local b=f[2]
- local e=b+n-1
- if chars then
- return sub(f[1],b,e)
- else
- return byte(f[1],b,e)
- end
-end
-function streams.skip(f,n)
- f[2]=f[2]+n
-end
-function streams.readbyte(f)
- local i=f[2]
- f[2]=i+1
- return byte(f[1],i)
-end
-function streams.readbytes(f,n)
- local i=f[2]
- local j=i+n
- f[2]=j
- return byte(f[1],i,j-1)
-end
-function streams.readbytetable(f,n)
- local i=f[2]
- local j=i+n
- f[2]=j
- return { byte(f[1],i,j-1) }
-end
-function streams.skipbytes(f,n)
- f[2]=f[2]+n
-end
-function streams.readchar(f)
- local i=f[2]
- f[2]=i+1
- return sub(f[1],i,i)
-end
-function streams.readstring(f,n)
- local i=f[2]
- local j=i+n
- f[2]=j
- return sub(f[1],i,j-1)
-end
-function streams.readinteger1(f)
- local i=f[2]
- f[2]=i+1
- local n=byte(f[1],i)
- if n>=0x80 then
- return n-0x100
- else
- return n
- end
-end
-streams.readcardinal1=streams.readbyte
-streams.readcardinal=streams.readcardinal1
-streams.readinteger=streams.readinteger1
-function streams.readcardinal2(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- return 0x100*a+b
-end
-function streams.readcardinal2le(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local b,a=byte(f[1],i,j)
- return 0x100*a+b
-end
-function streams.readinteger2(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function streams.readinteger2le(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local b,a=byte(f[1],i,j)
- if a>=0x80 then
- return 0x100*a+b-0x10000
- else
- return 0x100*a+b
- end
-end
-function streams.readcardinal3(f)
- local i=f[2]
- local j=i+2
- f[2]=j+1
- local a,b,c=byte(f[1],i,j)
- return 0x10000*a+0x100*b+c
-end
-function streams.readcardinal3le(f)
- local i=f[2]
- local j=i+2
- f[2]=j+1
- local c,b,a=byte(f[1],i,j)
- return 0x10000*a+0x100*b+c
-end
-function streams.readinteger3(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c=byte(f[1],i,j)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function streams.readinteger3le(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local c,b,a=byte(f[1],i,j)
- if a>=0x80 then
- return 0x10000*a+0x100*b+c-0x1000000
- else
- return 0x10000*a+0x100*b+c
- end
-end
-function streams.readcardinal4(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c,d=byte(f[1],i,j)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function streams.readcardinal4le(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local d,c,b,a=byte(f[1],i,j)
- return 0x1000000*a+0x10000*b+0x100*c+d
-end
-function streams.readinteger4(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c,d=byte(f[1],i,j)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function streams.readinteger4le(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local d,c,b,a=byte(f[1],i,j)
- if a>=0x80 then
- return 0x1000000*a+0x10000*b+0x100*c+d-0x100000000
- else
- return 0x1000000*a+0x10000*b+0x100*c+d
- end
-end
-function streams.readfixed2(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- if a>=0x80 then
- return tonumber((a-0x100).."."..b) or 0
- else
- return tonumber((a ).."."..b) or 0
- end
-end
-function streams.readfixed4(f)
- local i=f[2]
- local j=i+3
- f[2]=j+1
- local a,b,c,d=byte(f[1],i,j)
- if a>=0x80 then
- return tonumber((0x100*a+b-0x10000).."."..(0x100*c+d)) or 0
- else
- return tonumber((0x100*a+b ).."."..(0x100*c+d)) or 0
- end
-end
-if bit32 then
- local extract=bit32.extract
- local band=bit32.band
- function streams.read2dot14(f)
- local i=f[2]
- local j=i+1
- f[2]=j+1
- local a,b=byte(f[1],i,j)
- if a>=0x80 then
- local n=-(0x100*a+b)
- return-(extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- else
- local n=0x100*a+b
- return (extract(n,14,2)+(band(n,0x3FFF)/16384.0))
- end
- end
-end
-function streams.skipshort(f,n)
- f[2]=f[2]+2*(n or 1)
-end
-function streams.skiplong(f,n)
- f[2]=f[2]+4*(n or 1)
-end
-if sio and sio.readcardinal2 then
- local readcardinal1=sio.readcardinal1
- local readcardinal2=sio.readcardinal2
- local readcardinal3=sio.readcardinal3
- local readcardinal4=sio.readcardinal4
- local readinteger1=sio.readinteger1
- local readinteger2=sio.readinteger2
- local readinteger3=sio.readinteger3
- local readinteger4=sio.readinteger4
- local readfixed2=sio.readfixed2
- local readfixed4=sio.readfixed4
- local read2dot14=sio.read2dot14
- local readbytes=sio.readbytes
- local readbytetable=sio.readbytetable
- function streams.readcardinal1(f)
- local i=f[2]
- f[2]=i+1
- return readcardinal1(f[1],i)
- end
- function streams.readcardinal2(f)
- local i=f[2]
- f[2]=i+2
- return readcardinal2(f[1],i)
- end
- function streams.readcardinal3(f)
- local i=f[2]
- f[2]=i+3
- return readcardinal3(f[1],i)
- end
- function streams.readcardinal4(f)
- local i=f[2]
- f[2]=i+4
- return readcardinal4(f[1],i)
- end
- function streams.readinteger1(f)
- local i=f[2]
- f[2]=i+1
- return readinteger1(f[1],i)
- end
- function streams.readinteger2(f)
- local i=f[2]
- f[2]=i+2
- return readinteger2(f[1],i)
- end
- function streams.readinteger3(f)
- local i=f[2]
- f[2]=i+3
- return readinteger3(f[1],i)
- end
- function streams.readinteger4(f)
- local i=f[2]
- f[2]=i+4
- return readinteger4(f[1],i)
- end
- function streams.readfixed2(f)
- local i=f[2]
- f[2]=i+2
- return readfixed2(f[1],i)
- end
- function streams.readfixed4(f)
- local i=f[2]
- f[2]=i+4
- return readfixed4(f[1],i)
- end
- function streams.read2dot4(f)
- local i=f[2]
- f[2]=i+2
- return read2dot4(f[1],i)
- end
- function streams.readbytes(f,n)
- local i=f[2]
- local s=f[3]
- local p=i+n
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readbytes(f[1],i,n)
- end
- function streams.readbytetable(f,n)
- local i=f[2]
- local s=f[3]
- local p=i+n
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readbytetable(f[1],i,n)
- end
- streams.readbyte=streams.readcardinal1
- streams.readsignedbyte=streams.readinteger1
- streams.readcardinal=streams.readcardinal1
- streams.readinteger=streams.readinteger1
-end
-if sio and sio.readcardinaltable then
- local readcardinaltable=sio.readcardinaltable
- local readintegertable=sio.readintegertable
- function utilities.streams.readcardinaltable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readcardinaltable(f[1],i,n,b)
- end
- function utilities.streams.readintegertable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- return readintegertable(f[1],i,n,b)
- end
-else
- local readcardinal1=streams.readcardinal1
- local readcardinal2=streams.readcardinal2
- local readcardinal3=streams.readcardinal3
- local readcardinal4=streams.readcardinal4
- function streams.readcardinaltable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- local t={}
- if b==1 then for i=1,n do t[i]=readcardinal1(f[1],i) end
- elseif b==2 then for i=1,n do t[i]=readcardinal2(f[1],i) end
- elseif b==3 then for i=1,n do t[i]=readcardinal3(f[1],i) end
- elseif b==4 then for i=1,n do t[i]=readcardinal4(f[1],i) end end
- return t
- end
- local readinteger1=streams.readinteger1
- local readinteger2=streams.readinteger2
- local readinteger3=streams.readinteger3
- local readinteger4=streams.readinteger4
- function streams.readintegertable(f,n,b)
- local i=f[2]
- local s=f[3]
- local p=i+n*b
- if p>s then
- f[2]=s+1
- else
- f[2]=p
- end
- local t={}
- if b==1 then for i=1,n do t[i]=readinteger1(f[1],i) end
- elseif b==2 then for i=1,n do t[i]=readinteger2(f[1],i) end
- elseif b==3 then for i=1,n do t[i]=readinteger3(f[1],i) end
- elseif b==4 then for i=1,n do t[i]=readinteger4(f[1],i) end end
- return t
- end
-end
-do
- local files=utilities.files
- if files then
- local openfile=files.open
- local openstream=streams.open
- local openstring=streams.openstring
- local setmetatable=setmetatable
- function io.newreader(str,method)
- local f,m
- if method=="string" then
- f=openstring(str)
- m=streams
- elseif method=="stream" then
- f=openstream(str)
- m=streams
- else
- f=openfile(str,"rb")
- m=files
- end
- if f then
- local t={}
- setmetatable(t,{
- __index=function(t,k)
- local r=m[k]
- if k=="close" then
- if f then
- m.close(f)
- f=nil
- end
- return function() end
- elseif r then
- local v=function(_,a,b) return r(f,a,b) end
- t[k]=v
- return v
- else
- print("unknown key",k)
- end
- end
- } )
- return t
- end
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-sto"] = package.loaded["util-sto"] or true
-
--- original size: 6661, stripped down to: 3074
-
-if not modules then modules={} end modules ['util-sto']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local setmetatable,getmetatable,rawset,type=setmetatable,getmetatable,rawset,type
-utilities=utilities or {}
-utilities.storage=utilities.storage or {}
-local storage=utilities.storage
-function storage.mark(t)
- if not t then
- print("\nfatal error: storage cannot be marked\n")
- os.exit()
- return
- end
- local m=getmetatable(t)
- if not m then
- m={}
- setmetatable(t,m)
- end
- m.__storage__=true
- return t
-end
-function storage.allocate(t)
- t=t or {}
- local m=getmetatable(t)
- if not m then
- m={}
- setmetatable(t,m)
- end
- m.__storage__=true
- return t
-end
-function storage.marked(t)
- local m=getmetatable(t)
- return m and m.__storage__
-end
-function storage.checked(t)
- if not t then
- report("\nfatal error: storage has not been allocated\n")
- os.exit()
- return
- end
- return t
-end
-function storage.setinitializer(data,initialize)
- local m=getmetatable(data) or {}
- m.__index=function(data,k)
- m.__index=nil
- initialize()
- return data[k]
- end
- setmetatable(data,m)
-end
-local keyisvalue={ __index=function(t,k)
- t[k]=k
- return k
-end }
-function storage.sparse(t)
- t=t or {}
- setmetatable(t,keyisvalue)
- return t
-end
-local function f_empty () return "" end
-local function f_self (t,k) t[k]=k return k end
-local function f_table (t,k) local v={} t[k]=v return v end
-local function f_number(t,k) t[k]=0 return 0 end
-local function f_ignore() end
-local f_index={
- ["empty"]=f_empty,
- ["self"]=f_self,
- ["table"]=f_table,
- ["number"]=f_number,
-}
-function table.setmetatableindex(t,f)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- local i=f_index[f] or f
- if m then
- m.__index=i
- else
- setmetatable(t,{ __index=i })
- end
- return t
-end
-local f_index={
- ["ignore"]=f_ignore,
-}
-function table.setmetatablenewindex(t,f)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- local i=f_index[f] or f
- if m then
- m.__newindex=i
- else
- setmetatable(t,{ __newindex=i })
- end
- return t
-end
-function table.setmetatablecall(t,f)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- if m then
- m.__call=f
- else
- setmetatable(t,{ __call=f })
- end
- return t
-end
-function table.setmetatableindices(t,f,n,c)
- if type(t)~="table" then
- f,t=t,{}
- end
- local m=getmetatable(t)
- local i=f_index[f] or f
- if m then
- m.__index=i
- m.__newindex=n
- m.__call=c
- else
- setmetatable(t,{
- __index=i,
- __newindex=n,
- __call=c,
- })
- end
- return t
-end
-function table.setmetatablekey(t,key,value)
- local m=getmetatable(t)
- if not m then
- m={}
- setmetatable(t,m)
- end
- m[key]=value
- return t
-end
-function table.getmetatablekey(t,key,value)
- local m=getmetatable(t)
- return m and m[key]
-end
-function table.makeweak(t)
- if not t then
- t={}
- end
- local m=getmetatable(t)
- if m then
- m.__mode="v"
- else
- setmetatable(t,{ __mode="v" })
- end
- return t
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-prs"] = package.loaded["util-prs"] or true
-
--- original size: 24683, stripped down to: 16431
-
-if not modules then modules={} end modules ['util-prs']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local lpeg,table,string=lpeg,table,string
-local P,R,V,S,C,Ct,Cs,Carg,Cc,Cg,Cf,Cp=lpeg.P,lpeg.R,lpeg.V,lpeg.S,lpeg.C,lpeg.Ct,lpeg.Cs,lpeg.Carg,lpeg.Cc,lpeg.Cg,lpeg.Cf,lpeg.Cp
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local concat,gmatch,find=table.concat,string.gmatch,string.find
-local tonumber,tostring,type,next,rawset=tonumber,tostring,type,next,rawset
-local mod,div=math.mod,math.div
-utilities=utilities or {}
-local parsers=utilities.parsers or {}
-utilities.parsers=parsers
-local patterns=parsers.patterns or {}
-parsers.patterns=patterns
-local setmetatableindex=table.setmetatableindex
-local sortedhash=table.sortedhash
-local sortedkeys=table.sortedkeys
-local tohash=table.tohash
-local hashes={}
-parsers.hashes=hashes
-local digit=R("09")
-local space=P(' ')
-local equal=P("=")
-local colon=P(":")
-local comma=P(",")
-local lbrace=P("{")
-local rbrace=P("}")
-local lparent=P("(")
-local rparent=P(")")
-local lbracket=P("[")
-local rbracket=P("]")
-local period=S(".")
-local punctuation=S(".,:;")
-local spacer=lpegpatterns.spacer
-local whitespace=lpegpatterns.whitespace
-local newline=lpegpatterns.newline
-local anything=lpegpatterns.anything
-local endofstring=lpegpatterns.endofstring
-local nobrace=1-(lbrace+rbrace )
-local noparent=1-(lparent+rparent)
-local nobracket=1-(lbracket+rbracket)
-local escape,left,right=P("\\"),P('{'),P('}')
-lpegpatterns.balanced=P {
- [1]=((escape*(left+right))+(1-(left+right))+V(2))^0,
- [2]=left*V(1)*right
-}
-local nestedbraces=P { lbrace*(nobrace+V(1))^0*rbrace }
-local nestedparents=P { lparent*(noparent+V(1))^0*rparent }
-local nestedbrackets=P { lbracket*(nobracket+V(1))^0*rbracket }
-local spaces=space^0
-local argument=Cs((lbrace/"")*((nobrace+nestedbraces)^0)*(rbrace/""))
-local content=(1-endofstring)^0
-lpegpatterns.nestedbraces=nestedbraces
-lpegpatterns.nestedparents=nestedparents
-lpegpatterns.nested=nestedbraces
-lpegpatterns.argument=argument
-lpegpatterns.content=content
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+(1-comma))^0)
-local key=C((1-equal-comma)^1)
-local pattern_a=(space+comma)^0*(key*equal*value+key*C(""))
-local pattern_c=(space+comma)^0*(key*equal*value)
-local pattern_d=(space+comma)^0*(key*(equal+colon)*value+key*C(""))
-local key=C((1-space-equal-comma)^1)
-local pattern_b=spaces*comma^0*spaces*(key*((spaces*equal*spaces*value)+C("")))
-local hash={}
-local function set(key,value)
- hash[key]=value
-end
-local pattern_a_s=(pattern_a/set)^1
-local pattern_b_s=(pattern_b/set)^1
-local pattern_c_s=(pattern_c/set)^1
-local pattern_d_s=(pattern_d/set)^1
-patterns.settings_to_hash_a=pattern_a_s
-patterns.settings_to_hash_b=pattern_b_s
-patterns.settings_to_hash_c=pattern_c_s
-patterns.settings_to_hash_d=pattern_d_s
-function parsers.make_settings_to_hash_pattern(set,how)
- if how=="strict" then
- return (pattern_c/set)^1
- elseif how=="tolerant" then
- return (pattern_b/set)^1
- else
- return (pattern_a/set)^1
- end
-end
-function parsers.settings_to_hash(str,existing)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- if existing then
- for k,v in next,str do
- existing[k]=v
- end
- return exiting
- else
- return str
- end
- else
- hash=existing or {}
- lpegmatch(pattern_a_s,str)
- return hash
- end
-end
-function parsers.settings_to_hash_colon_too(str)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- return str
- else
- hash={}
- lpegmatch(pattern_d_s,str)
- return hash
- end
-end
-function parsers.settings_to_hash_tolerant(str,existing)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- if existing then
- for k,v in next,str do
- existing[k]=v
- end
- return exiting
- else
- return str
- end
- else
- hash=existing or {}
- lpegmatch(pattern_b_s,str)
- return hash
- end
-end
-function parsers.settings_to_hash_strict(str,existing)
- if not str or str=="" then
- return nil
- elseif type(str)=="table" then
- if existing then
- for k,v in next,str do
- existing[k]=v
- end
- return exiting
- else
- return str
- end
- elseif str and str~="" then
- hash=existing or {}
- lpegmatch(pattern_c_s,str)
- return next(hash) and hash
- end
-end
-local separator=comma*space^0
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+(1-comma))^0)
-local pattern=spaces*Ct(value*(separator*value)^0)
-patterns.settings_to_array=pattern
-function parsers.settings_to_array(str,strict)
- if not str or str=="" then
- return {}
- elseif type(str)=="table" then
- return str
- elseif strict then
- if find(str,"{",1,true) then
- return lpegmatch(pattern,str)
- else
- return { str }
- end
- elseif find(str,",",1,true) then
- return lpegmatch(pattern,str)
- else
- return { str }
- end
-end
-function parsers.settings_to_numbers(str)
- if not str or str=="" then
- return {}
- end
- if type(str)=="table" then
- elseif find(str,",",1,true) then
- str=lpegmatch(pattern,str)
- else
- return { tonumber(str) }
- end
- for i=1,#str do
- str[i]=tonumber(str[i])
- end
- return str
-end
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+nestedbrackets+nestedparents+(1-comma))^0)
-local pattern=spaces*Ct(value*(separator*value)^0)
-function parsers.settings_to_array_obey_fences(str)
- return lpegmatch(pattern,str)
-end
-local cache_a={}
-local cache_b={}
-function parsers.groupedsplitat(symbol,withaction)
- if not symbol then
- symbol=","
- end
- local pattern=(withaction and cache_b or cache_a)[symbol]
- if not pattern then
- local symbols=S(symbol)
- local separator=space^0*symbols*space^0
- local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace+C((nestedbraces+(1-(space^0*(symbols+P(-1)))))^0)
- if withaction then
- local withvalue=Carg(1)*value/function(f,s) return f(s) end
- pattern=spaces*withvalue*(separator*withvalue)^0
- cache_b[symbol]=pattern
- else
- pattern=spaces*Ct(value*(separator*value)^0)
- cache_a[symbol]=pattern
- end
- end
- return pattern
-end
-local pattern_a=parsers.groupedsplitat(",",false)
-local pattern_b=parsers.groupedsplitat(",",true)
-function parsers.stripped_settings_to_array(str)
- if not str or str=="" then
- return {}
- else
- return lpegmatch(pattern_a,str)
- end
-end
-function parsers.process_stripped_settings(str,action)
- if not str or str=="" then
- return {}
- else
- return lpegmatch(pattern_b,str,1,action)
- end
-end
-local function set(t,v)
- t[#t+1]=v
-end
-local value=P(Carg(1)*value)/set
-local pattern=value*(separator*value)^0*Carg(1)
-function parsers.add_settings_to_array(t,str)
- return lpegmatch(pattern,str,nil,t)
-end
-function parsers.hash_to_string(h,separator,yes,no,strict,omit)
- if h then
- local t={}
- local tn=0
- local s=sortedkeys(h)
- omit=omit and tohash(omit)
- for i=1,#s do
- local key=s[i]
- if not omit or not omit[key] then
- local value=h[key]
- if type(value)=="boolean" then
- if yes and no then
- if value then
- tn=tn+1
- t[tn]=key..'='..yes
- elseif not strict then
- tn=tn+1
- t[tn]=key..'='..no
- end
- elseif value or not strict then
- tn=tn+1
- t[tn]=key..'='..tostring(value)
- end
- else
- tn=tn+1
- t[tn]=key..'='..value
- end
- end
- end
- return concat(t,separator or ",")
- else
- return ""
- end
-end
-function parsers.array_to_string(a,separator)
- if a then
- return concat(a,separator or ",")
- else
- return ""
- end
-end
-local pattern=Cf(Ct("")*Cg(C((1-S(", "))^1)*S(", ")^0*Cc(true))^1,rawset)
-function parsers.settings_to_set(str)
- return str and lpegmatch(pattern,str) or {}
-end
-hashes.settings_to_set=table.setmetatableindex(function(t,k)
- local v=k and lpegmatch(pattern,k) or {}
- t[k]=v
- return v
-end)
-getmetatable(hashes.settings_to_set).__mode="kv"
-function parsers.simple_hash_to_string(h,separator)
- local t={}
- local tn=0
- for k,v in sortedhash(h) do
- if v then
- tn=tn+1
- t[tn]=k
- end
- end
- return concat(t,separator or ",")
-end
-local str=Cs(lpegpatterns.unquoted)+C((1-whitespace-equal)^1)
-local setting=Cf(Carg(1)*(whitespace^0*Cg(str*whitespace^0*(equal*whitespace^0*str+Cc(""))))^1,rawset)
-local splitter=setting^1
-function parsers.options_to_hash(str,target)
- return str and lpegmatch(splitter,str,1,target or {}) or {}
-end
-local splitter=lpeg.tsplitat(" ")
-function parsers.options_to_array(str)
- return str and lpegmatch(splitter,str) or {}
-end
-local value=P(lbrace*C((nobrace+nestedbraces)^0)*rbrace)+C(digit^1*lparent*(noparent+nestedparents)^1*rparent)+C((nestedbraces+(1-comma))^1)
-local pattern_a=spaces*Ct(value*(separator*value)^0)
-local function repeater(n,str)
- if not n then
- return str
- else
- local s=lpegmatch(pattern_a,str)
- if n==1 then
- return unpack(s)
- else
- local t={}
- local tn=0
- for i=1,n do
- for j=1,#s do
- tn=tn+1
- t[tn]=s[j]
- end
- end
- return unpack(t)
- end
- end
-end
-local value=P(lbrace*C((nobrace+nestedbraces)^0)*rbrace)+(C(digit^1)/tonumber*lparent*Cs((noparent+nestedparents)^1)*rparent)/repeater+C((nestedbraces+(1-comma))^1)
-local pattern_b=spaces*Ct(value*(separator*value)^0)
-function parsers.settings_to_array_with_repeat(str,expand)
- if expand then
- return lpegmatch(pattern_b,str) or {}
- else
- return lpegmatch(pattern_a,str) or {}
- end
-end
-local value=lbrace*C((nobrace+nestedbraces)^0)*rbrace
-local pattern=Ct((space+value)^0)
-function parsers.arguments_to_table(str)
- return lpegmatch(pattern,str)
-end
-function parsers.getparameters(self,class,parentclass,settings)
- local sc=self[class]
- if not sc then
- sc={}
- self[class]=sc
- if parentclass then
- local sp=self[parentclass]
- if not sp then
- sp={}
- self[parentclass]=sp
- end
- setmetatableindex(sc,sp)
- end
- end
- parsers.settings_to_hash(settings,sc)
-end
-function parsers.listitem(str)
- return gmatch(str,"[^, ]+")
-end
-local pattern=Cs { "start",
- start=V("one")+V("two")+V("three"),
- rest=(Cc(",")*V("thousand"))^0*(P(".")+endofstring)*anything^0,
- thousand=digit*digit*digit,
- one=digit*V("rest"),
- two=digit*digit*V("rest"),
- three=V("thousand")*V("rest"),
-}
-lpegpatterns.splitthousands=pattern
-function parsers.splitthousands(str)
- return lpegmatch(pattern,str) or str
-end
-local optionalwhitespace=whitespace^0
-lpegpatterns.words=Ct((Cs((1-punctuation-whitespace)^1)+anything)^1)
-lpegpatterns.sentences=Ct((optionalwhitespace*Cs((1-period)^0*period))^1)
-lpegpatterns.paragraphs=Ct((optionalwhitespace*Cs((whitespace^1*endofstring/""+1-(spacer^0*newline*newline))^1))^1)
-local dquote=P('"')
-local equal=P('=')
-local escape=P('\\')
-local separator=S(' ,')
-local key=C((1-equal)^1)
-local value=dquote*C((1-dquote-escape*dquote)^0)*dquote
-local pattern=Cf(Ct("")*(Cg(key*equal*value)*separator^0)^1,rawset)^0*P(-1)
-function parsers.keq_to_hash(str)
- if str and str~="" then
- return lpegmatch(pattern,str)
- else
- return {}
- end
-end
-local defaultspecification={ separator=",",quote='"' }
-function parsers.csvsplitter(specification)
- specification=specification and setmetatableindex(specification,defaultspecification) or defaultspecification
- local separator=specification.separator
- local quotechar=specification.quote
- local numbers=specification.numbers
- local separator=S(separator~="" and separator or ",")
- local whatever=C((1-separator-newline)^0)
- if quotechar and quotechar~="" then
- local quotedata=nil
- for chr in gmatch(quotechar,".") do
- local quotechar=P(chr)
- local quoteitem=(1-quotechar)^0
- local quoteword=quotechar*(numbers and (quoteitem/tonumber) or C(quoteitem))*quotechar
- if quotedata then
- quotedata=quotedata+quoteword
- else
- quotedata=quoteword
- end
- end
- whatever=quotedata+whatever
- end
- local parser=Ct((Ct(whatever*(separator*whatever)^0)*S("\n\r")^1)^0 )
- return function(data)
- return lpegmatch(parser,data)
- end
-end
-function parsers.rfc4180splitter(specification)
- specification=specification and setmetatableindex(specification,defaultspecification) or defaultspecification
- local numbers=specification.numbers
- local separator=specification.separator
- local quotechar=P(specification.quote)
- local dquotechar=quotechar*quotechar
-/specification.quote
- local separator=S(separator~="" and separator or ",")
- local whatever=(dquotechar+(1-quotechar))^0
- local escaped=quotechar*(numbers and (whatever/tonumber) or Cs(whatever))*quotechar
- local non_escaped=C((1-quotechar-newline-separator)^1)
- local field=escaped+non_escaped+Cc("")
- local record=Ct(field*(separator*field)^1)
- local headerline=record*Cp()
- local morerecords=(newline^(specification.strict and -1 or 1)*record)^0
- local headeryes=Ct(morerecords)
- local headernop=Ct(record*morerecords)
- return function(data,getheader)
- if getheader then
- local header,position=lpegmatch(headerline,data)
- local data=lpegmatch(headeryes,data,position)
- return data,header
- else
- return lpegmatch(headernop,data)
- end
- end
-end
-local function ranger(first,last,n,action)
- if not first then
- elseif last==true then
- for i=first,n or first do
- action(i)
- end
- elseif last then
- for i=first,last do
- action(i)
- end
- else
- action(first)
- end
-end
-local cardinal=lpegpatterns.cardinal/tonumber
-local spacers=lpegpatterns.spacer^0
-local endofstring=lpegpatterns.endofstring
-local stepper=spacers*(cardinal*(spacers*S(":-")*spacers*(cardinal+Cc(true) )+Cc(false) )*Carg(1)*Carg(2)/ranger*S(", ")^0 )^1
-local stepper=spacers*(cardinal*(spacers*S(":-")*spacers*(cardinal+(P("*")+endofstring)*Cc(true) )+Cc(false) )*Carg(1)*Carg(2)/ranger*S(", ")^0 )^1*endofstring
-function parsers.stepper(str,n,action)
- if type(n)=="function" then
- lpegmatch(stepper,str,1,false,n or print)
- else
- lpegmatch(stepper,str,1,n,action or print)
- end
-end
-local pattern_math=Cs((P("%")/"\\percent "+P("^")*Cc("{")*lpegpatterns.integer*Cc("}")+anything)^0)
-local pattern_text=Cs((P("%")/"\\percent "+(P("^")/"\\high")*Cc("{")*lpegpatterns.integer*Cc("}")+anything)^0)
-patterns.unittotex=pattern
-function parsers.unittotex(str,textmode)
- return lpegmatch(textmode and pattern_text or pattern_math,str)
-end
-local pattern=Cs((P("^")/"<sup>"*lpegpatterns.integer*Cc("</sup>")+anything)^0)
-function parsers.unittoxml(str)
- return lpegmatch(pattern,str)
-end
-local cache={}
-local spaces=lpegpatterns.space^0
-local dummy=function() end
-setmetatableindex(cache,function(t,k)
- local separator=P(k)
- local value=(1-separator)^0
- local pattern=spaces*C(value)*separator^0*Cp()
- t[k]=pattern
- return pattern
-end)
-local commalistiterator=cache[","]
-function parsers.iterator(str,separator)
- local n=#str
- if n==0 then
- return dummy
- else
- local pattern=separator and cache[separator] or commalistiterator
- local p=1
- return function()
- if p<=n then
- local s,e=lpegmatch(pattern,str,p)
- if e then
- p=e
- return s
- end
- end
- end
- end
-end
-local function initialize(t,name)
- local source=t[name]
- if source then
- local result={}
- for k,v in next,t[name] do
- result[k]=v
- end
- return result
- else
- return {}
- end
-end
-local function fetch(t,name)
- return t[name] or {}
-end
-local function process(result,more)
- for k,v in next,more do
- result[k]=v
- end
- return result
-end
-local name=C((1-S(", "))^1)
-local parser=(Carg(1)*name/initialize)*(S(", ")^1*(Carg(1)*name/fetch))^0
-local merge=Cf(parser,process)
-function parsers.mergehashes(hash,list)
- return lpegmatch(merge,list,1,hash)
-end
-function parsers.runtime(time)
- if not time then
- time=os.runtime()
- end
- local days=div(time,24*60*60)
- time=mod(time,24*60*60)
- local hours=div(time,60*60)
- time=mod(time,60*60)
- local minutes=div(time,60)
- local seconds=mod(time,60)
- return days,hours,minutes,seconds
-end
-local spacing=whitespace^0
-local apply=P("->")
-local method=C((1-apply)^1)
-local token=lbrace*C((1-rbrace)^1)*rbrace+C(anything^1)
-local pattern=spacing*(method*spacing*apply+Carg(1))*spacing*token
-function parsers.splitmethod(str,default)
- if str then
- return lpegmatch(pattern,str,1,default or false)
- else
- return default or false,""
- end
-end
-local p_year=lpegpatterns.digit^4/tonumber
-local pattern=Cf(Ct("")*(
- (Cg(Cc("year")*p_year)*S("-/")*Cg(Cc("month")*cardinal)*S("-/")*Cg(Cc("day")*cardinal)
- )+(Cg(Cc("day")*cardinal)*S("-/")*Cg(Cc("month")*cardinal)*S("-/")*Cg(Cc("year")*p_year)
- )
- )*P(" ")*Cg(Cc("hour")*cardinal)*P(":")*Cg(Cc("min")*cardinal)*(P(":")*Cg(Cc("sec")*cardinal))^-1
-,rawset)
-lpegpatterns.splittime=pattern
-function parsers.totime(str)
- return lpegmatch(pattern,str)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-fmt"] = package.loaded["util-fmt"] or true
-
--- original size: 2541, stripped down to: 1624
-
-if not modules then modules={} end modules ['util-fmt']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities=utilities or {}
-utilities.formatters=utilities.formatters or {}
-local formatters=utilities.formatters
-local concat,format=table.concat,string.format
-local tostring,type=tostring,type
-local strip=string.strip
-local lpegmatch=lpeg.match
-local stripper=lpeg.patterns.stripzeros
-function formatters.stripzeros(str)
- return lpegmatch(stripper,str)
-end
-function formatters.formatcolumns(result,between)
- if result and #result>0 then
- between=between or " "
- local widths,numbers={},{}
- local first=result[1]
- local n=#first
- for i=1,n do
- widths[i]=0
- end
- for i=1,#result do
- local r=result[i]
- for j=1,n do
- local rj=r[j]
- local tj=type(rj)
- if tj=="number" then
- numbers[j]=true
- rj=tostring(rj)
- elseif tj~="string" then
- rj=tostring(rj)
- r[j]=rj
- end
- local w=#rj
- if w>widths[j] then
- widths[j]=w
- end
- end
- end
- for i=1,n do
- local w=widths[i]
- if numbers[i] then
- if w>80 then
- widths[i]="%s"..between
- else
- widths[i]="%0"..w.."i"..between
- end
- else
- if w>80 then
- widths[i]="%s"..between
- elseif w>0 then
- widths[i]="%-"..w.."s"..between
- else
- widths[i]="%s"
- end
- end
- end
- local template=strip(concat(widths))
- for i=1,#result do
- local str=format(template,unpack(result[i]))
- result[i]=strip(str)
- end
- end
- return result
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-reset"] = package.loaded["util-soc-imp-reset"] or true
-
--- original size: 374, stripped down to: 282
-
-local loaded=package.loaded
-loaded["socket"]=nil
-loaded["copas"]=nil
-loaded["ltn12"]=nil
-loaded["mbox"]=nil
-loaded["mime"]=nil
-loaded["socket.url"]=nil
-loaded["socket.headers"]=nil
-loaded["socket.tp"]=nil
-loaded["socket.http"]=nil
-loaded["socket.ftp"]=nil
-loaded["socket.smtp"]=nil
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-socket"] = package.loaded["util-soc-imp-socket"] or true
-
--- original size: 4905, stripped down to: 3562
-
-
-local type,tostring,setmetatable=type,tostring,setmetatable
-local min=math.min
-local format=string.format
-local socket=socket or package.loaded.socket or require("socket.core")
-local connect=socket.connect
-local tcp4=socket.tcp4
-local tcp6=socket.tcp6
-local getaddrinfo=socket.dns.getaddrinfo
-local defaulthost="0.0.0.0"
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("socket")
- report(fmt,first,...)
- elseif fmt then
- fmt="socket: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-socket.report=report
-function socket.connect4(address,port,laddress,lport)
- return connect(address,port,laddress,lport,"inet")
-end
-function socket.connect6(address,port,laddress,lport)
- return connect(address,port,laddress,lport,"inet6")
-end
-function socket.bind(host,port,backlog)
- if host=="*" or host=="" then
- host=defaulthost
- end
- local addrinfo,err=getaddrinfo(host)
- if not addrinfo then
- return nil,err
- end
- for i=1,#addrinfo do
- local alt=addrinfo[i]
- local sock,err=(alt.family=="inet" and tcp4 or tcp6)()
- if not sock then
- return nil,err or "unknown error"
- end
- sock:setoption("reuseaddr",true)
- local res,err=sock:bind(alt.addr,port)
- if res then
- res,err=sock:listen(backlog)
- if res then
- return sock
- else
- sock:close()
- end
- else
- sock:close()
- end
- end
- return nil,"invalid address"
-end
-socket.try=socket.newtry()
-function socket.choose(list)
- return function(name,opt1,opt2)
- if type(name)~="string" then
- name,opt1,opt2="default",name,opt1
- end
- local f=list[name or "nil"]
- if f then
- return f(opt1,opt2)
- else
- report("error: unknown key '%s'",tostring(name))
- end
- end
-end
-local sourcet={}
-local sinkt={}
-socket.sourcet=sourcet
-socket.sinkt=sinkt
-socket.BLOCKSIZE=2048
-sinkt["close-when-done"]=function(sock)
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },
- {
- __call=function(self,chunk,err)
- if chunk then
- return sock:send(chunk)
- else
- sock:close()
- return 1
- end
- end
- }
- )
-end
-sinkt["keep-open"]=function(sock)
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },{
- __call=function(self,chunk,err)
- if chunk then
- return sock:send(chunk)
- else
- return 1
- end
- end
- }
- )
-end
-sinkt["default"]=sinkt["keep-open"]
-socket.sink=socket.choose(sinkt)
-sourcet["by-length"]=function(sock,length)
- local blocksize=socket.BLOCKSIZE
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },
- {
- __call=function()
- if length<=0 then
- return nil
- end
- local chunk,err=sock:receive(min(blocksize,length))
- if err then
- return nil,err
- end
- length=length-#chunk
- return chunk
- end
- }
- )
-end
-sourcet["until-closed"]=function(sock)
- local blocksize=socket.BLOCKSIZE
- local done=false
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },{
- __call=function()
- if done then
- return nil
- end
- local chunk,status,partial=sock:receive(blocksize)
- if not status then
- return chunk
- elseif status=="closed" then
- sock:close()
- done=true
- return partial
- else
- return nil,status
- end
- end
- }
- )
-end
-sourcet["default"]=sourcet["until-closed"]
-socket.source=socket.choose(sourcet)
-_G.socket=socket
-package.loaded["socket"]=socket
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-copas"] = package.loaded["util-soc-imp-copas"] or true
-
--- original size: 26186, stripped down to: 14893
-
-
-local socket=socket or require("socket")
-local ssl=ssl or nil
-local WATCH_DOG_TIMEOUT=120
-local UDP_DATAGRAM_MAX=8192
-local type,next,pcall,getmetatable,tostring=type,next,pcall,getmetatable,tostring
-local min,max,random=math.min,math.max,math.random
-local find=string.find
-local insert,remove=table.insert,table.remove
-local gettime=socket.gettime
-local selectsocket=socket.select
-local createcoroutine=coroutine.create
-local resumecoroutine=coroutine.resume
-local yieldcoroutine=coroutine.yield
-local runningcoroutine=coroutine.running
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("copas")
- report(fmt,first,...)
- elseif fmt then
- fmt="copas: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-local copas={
- _COPYRIGHT="Copyright (C) 2005-2016 Kepler Project",
- _DESCRIPTION="Coroutine Oriented Portable Asynchronous Services",
- _VERSION="Copas 2.0.1",
- autoclose=true,
- running=false,
- report=report,
- trace=false,
-}
-local function statushandler(status,...)
- if status then
- return...
- end
- local err=(...)
- if type(err)=="table" then
- err=err[1]
- end
- if copas.trace then
- report("error: %s",tostring(err))
- end
- return nil,err
-end
-function socket.protect(func)
- return function(...)
- return statushandler(pcall(func,...))
- end
-end
-function socket.newtry(finalizer)
- return function (...)
- local status=(...)
- if not status then
- local detail=select(2,...)
- pcall(finalizer,detail)
- if copas.trace then
- report("error: %s",tostring(detail))
- end
- return
- end
- return...
- end
-end
-local function newset()
- local reverse={}
- local set={}
- local queue={}
- setmetatable(set,{
- __index={
- insert=function(set,value)
- if not reverse[value] then
- local n=#set+1
- set[n]=value
- reverse[value]=n
- end
- end,
- remove=function(set,value)
- local index=reverse[value]
- if index then
- reverse[value]=nil
- local n=#set
- local top=set[n]
- set[n]=nil
- if top~=value then
- reverse[top]=index
- set[index]=top
- end
- end
- end,
- push=function (set,key,itm)
- local entry=queue[key]
- if entry==nil then
- queue[key]={ itm }
- else
- entry[#entry+1]=itm
- end
- end,
- pop=function (set,key)
- local top=queue[key]
- if top~=nil then
- local ret=remove(top,1)
- if top[1]==nil then
- queue[key]=nil
- end
- return ret
- end
- end
- }
- } )
- return set
-end
-local _sleeping={
- times={},
- cos={},
- lethargy={},
- insert=function()
- end,
- remove=function()
- end,
- push=function(self,sleeptime,co)
- if not co then
- return
- end
- if sleeptime<0 then
- self.lethargy[co]=true
- return
- else
- sleeptime=gettime()+sleeptime
- end
- local t=self.times
- local c=self.cos
- local i=1
- local n=#t
- while i<=n and t[i]<=sleeptime do
- i=i+1
- end
- insert(t,i,sleeptime)
- insert(c,i,co)
- end,
- getnext=
- function(self)
- local t=self.times
- local delay=t[1] and t[1]-gettime() or nil
- return delay and max(delay,0) or nil
- end,
- pop=
- function(self,time)
- local t=self.times
- local c=self.cos
- if #t==0 or time<t[1] then
- return
- end
- local co=c[1]
- remove(t,1)
- remove(c,1)
- return co
- end,
- wakeup=function(self,co)
- local let=self.lethargy
- if let[co] then
- self:push(0,co)
- let[co]=nil
- else
- local c=self.cos
- local t=self.times
- for i=1,#c do
- if c[i]==co then
- remove(c,i)
- remove(t,i)
- self:push(0,co)
- return
- end
- end
- end
- end
-}
-local _servers=newset()
-local _reading=newset()
-local _writing=newset()
-local _reading_log={}
-local _writing_log={}
-local _is_timeout={
- timeout=true,
- wantread=true,
- wantwrite=true,
-}
-local function isTCP(socket)
- return not find(tostring(socket),"^udp")
-end
-local function copasreceive(client,pattern,part)
- if not pattern or pattern=="" then
- pattern="*l"
- end
- local current_log=_reading_log
- local s,err
- repeat
- s,err,part=client:receive(pattern,part)
- if s or (not _is_timeout[err]) then
- current_log[client]=nil
- return s,err,part
- end
- if err=="wantwrite" then
- current_log=_writing_log
- current_log[client]=gettime()
- yieldcoroutine(client,_writing)
- else
- current_log=_reading_log
- current_log[client]=gettime()
- yieldcoroutine(client,_reading)
- end
- until false
-end
-local function copasreceivefrom(client,size)
- local s,err,port
- if not size or size==0 then
- size=UDP_DATAGRAM_MAX
- end
- repeat
- s,err,port=client:receivefrom(size)
- if s or err~="timeout" then
- _reading_log[client]=nil
- return s,err,port
- end
- _reading_log[client]=gettime()
- yieldcoroutine(client,_reading)
- until false
-end
-local function copasreceivepartial(client,pattern,part)
- if not pattern or pattern=="" then
- pattern="*l"
- end
- local logger=_reading_log
- local queue=_reading
- local s,err
- repeat
- s,err,part=client:receive(pattern,part)
- if s or (type(pattern)=="number" and part~="" and part) or not _is_timeout[err] then
- logger[client]=nil
- return s,err,part
- end
- if err=="wantwrite" then
- logger=_writing_log
- queue=_writing
- else
- logger=_reading_log
- queue=_reading
- end
- logger[client]=gettime()
- yieldcoroutine(client,queue)
- until false
-end
-local function copassend(client,data,from,to)
- if not from then
- from=1
- end
- local lastIndex=from-1
- local logger=_writing_log
- local queue=_writing
- local s,err
- repeat
- s,err,lastIndex=client:send(data,lastIndex+1,to)
- if random(100)>90 then
- logger[client]=gettime()
- yieldcoroutine(client,queue)
- end
- if s or not _is_timeout[err] then
- logger[client]=nil
- return s,err,lastIndex
- end
- if err=="wantread" then
- logger=_reading_log
- queue=_reading
- else
- logger=_writing_log
- queue=_writing
- end
- logger[client]=gettime()
- yieldcoroutine(client,queue)
- until false
-end
-local function copassendto(client,data,ip,port)
- repeat
- local s,err=client:sendto(data,ip,port)
- if random(100)>90 then
- _writing_log[client]=gettime()
- yieldcoroutine(client,_writing)
- end
- if s or err~="timeout" then
- _writing_log[client]=nil
- return s,err
- end
- _writing_log[client]=gettime()
- yieldcoroutine(client,_writing)
- until false
-end
-local function copasconnect(skt,host,port)
- skt:settimeout(0)
- local ret,err,tried_more_than_once
- repeat
- ret,err=skt:connect (host,port)
- if ret or (err~="timeout" and err~="Operation already in progress") then
- if not ret and err=="already connected" and tried_more_than_once then
- ret=1
- err=nil
- end
- _writing_log[skt]=nil
- return ret,err
- end
- tried_more_than_once=tried_more_than_once or true
- _writing_log[skt]=gettime()
- yieldcoroutine(skt,_writing)
- until false
-end
-local function copasdohandshake(skt,sslt)
- if not ssl then
- ssl=require("ssl")
- end
- if not ssl then
- report("error: no ssl library")
- return
- end
- local nskt,err=ssl.wrap(skt,sslt)
- if not nskt then
- report("error: %s",tostring(err))
- return
- end
- nskt:settimeout(0)
- local queue
- repeat
- local success,err=nskt:dohandshake()
- if success then
- return nskt
- elseif err=="wantwrite" then
- queue=_writing
- elseif err=="wantread" then
- queue=_reading
- else
- report("error: %s",tostring(err))
- return
- end
- yieldcoroutine(nskt,queue)
- until false
-end
-local function copasflush(client)
-end
-copas.connect=copassconnect
-copas.send=copassend
-copas.sendto=copassendto
-copas.receive=copasreceive
-copas.receivefrom=copasreceivefrom
-copas.copasreceivepartial=copasreceivepartial
-copas.copasreceivePartial=copasreceivepartial
-copas.dohandshake=copasdohandshake
-copas.flush=copasflush
-local function _skt_mt_tostring(self)
- return tostring(self.socket).." (copas wrapped)"
-end
-local _skt_mt_tcp_index={
- send=function(self,data,from,to)
- return copassend (self.socket,data,from,to)
- end,
- receive=function (self,pattern,prefix)
- if self.timeout==0 then
- return copasreceivePartial(self.socket,pattern,prefix)
- else
- return copasreceive(self.socket,pattern,prefix)
- end
- end,
- flush=function (self)
- return copasflush(self.socket)
- end,
- settimeout=function (self,time)
- self.timeout=time
- return true
- end,
- connect=function(self,...)
- local res,err=copasconnect(self.socket,...)
- if res and self.ssl_params then
- res,err=self:dohandshake()
- end
- return res,err
- end,
- close=function(self,...)
- return self.socket:close(...)
- end,
- bind=function(self,...)
- return self.socket:bind(...)
- end,
- getsockname=function(self,...)
- return self.socket:getsockname(...)
- end,
- getstats=function(self,...)
- return self.socket:getstats(...)
- end,
- setstats=function(self,...)
- return self.socket:setstats(...)
- end,
- listen=function(self,...)
- return self.socket:listen(...)
- end,
- accept=function(self,...)
- return self.socket:accept(...)
- end,
- setoption=function(self,...)
- return self.socket:setoption(...)
- end,
- getpeername=function(self,...)
- return self.socket:getpeername(...)
- end,
- shutdown=function(self,...)
- return self.socket:shutdown(...)
- end,
- dohandshake=function(self,sslt)
- self.ssl_params=sslt or self.ssl_params
- local nskt,err=copasdohandshake(self.socket,self.ssl_params)
- if not nskt then
- return nskt,err
- end
- self.socket=nskt
- return self
- end,
-}
-local _skt_mt_tcp={
- __tostring=_skt_mt_tostring,
- __index=_skt_mt_tcp_index,
-}
-local _skt_mt_udp_index={
- sendto=function (self,...)
- return copassendto(self.socket,...)
- end,
- receive=function (self,size)
- return copasreceive(self.socket,size or UDP_DATAGRAM_MAX)
- end,
- receivefrom=function (self,size)
- return copasreceivefrom(self.socket,size or UDP_DATAGRAM_MAX)
- end,
- setpeername=function(self,...)
- return self.socket:getpeername(...)
- end,
- setsockname=function(self,...)
- return self.socket:setsockname(...)
- end,
- close=function(self,...)
- return true
- end
-}
-local _skt_mt_udp={
- __tostring=_skt_mt_tostring,
- __index=_skt_mt_udp_index,
-}
-for k,v in next,_skt_mt_tcp_index do
- if not _skt_mt_udp_index[k] then
- _skt_mt_udp_index[k]=v
- end
-end
-local function wrap(skt,sslt)
- if getmetatable(skt)==_skt_mt_tcp or getmetatable(skt)==_skt_mt_udp then
- return skt
- end
- skt:settimeout(0)
- if isTCP(skt) then
- return setmetatable ({ socket=skt,ssl_params=sslt },_skt_mt_tcp)
- else
- return setmetatable ({ socket=skt },_skt_mt_udp)
- end
-end
-copas.wrap=wrap
-function copas.handler(handler,sslparams)
- return function (skt,...)
- skt=wrap(skt)
- if sslparams then
- skt:dohandshake(sslparams)
- end
- return handler(skt,...)
- end
-end
-local _errhandlers={}
-function copas.setErrorHandler(err)
- local co=runningcoroutine()
- if co then
- _errhandlers[co]=err
- end
-end
-local function _deferror (msg,co,skt)
- report("%s (%s) (%s)",msg,tostring(co),tostring(skt))
-end
-local function _doTick (co,skt,...)
- if not co then
- return
- end
- local ok,res,new_q=resumecoroutine(co,skt,...)
- if ok and res and new_q then
- new_q:insert(res)
- new_q:push(res,co)
- else
- if not ok then
- pcall(_errhandlers[co] or _deferror,res,co,skt)
- end
- if skt and copas.autoclose and isTCP(skt) then
- skt:close()
- end
- _errhandlers[co]=nil
- end
-end
-local function _accept(input,handler)
- local client=input:accept()
- if client then
- client:settimeout(0)
- local co=createcoroutine(handler)
- _doTick (co,client)
- end
- return client
-end
-local function _tickRead(skt)
- _doTick(_reading:pop(skt),skt)
-end
-local function _tickWrite(skt)
- _doTick(_writing:pop(skt),skt)
-end
-local function addTCPserver(server,handler,timeout)
- server:settimeout(timeout or 0)
- _servers[server]=handler
- _reading:insert(server)
-end
-local function addUDPserver(server,handler,timeout)
- server:settimeout(timeout or 0)
- local co=createcoroutine(handler)
- _reading:insert(server)
- _doTick(co,server)
-end
-function copas.addserver(server,handler,timeout)
- if isTCP(server) then
- addTCPserver(server,handler,timeout)
- else
- addUDPserver(server,handler,timeout)
- end
-end
-function copas.removeserver(server,keep_open)
- local s=server
- local mt=getmetatable(server)
- if mt==_skt_mt_tcp or mt==_skt_mt_udp then
- s=server.socket
- end
- _servers[s]=nil
- _reading:remove(s)
- if keep_open then
- return true
- end
- return server:close()
-end
-function copas.addthread(handler,...)
- local thread=createcoroutine(function(_,...) return handler(...) end)
- _doTick(thread,nil,...)
- return thread
-end
-local _tasks={}
-local function addtaskRead(task)
- task.def_tick=_tickRead
- _tasks[task]=true
-end
-local function addtaskWrite(task)
- task.def_tick=_tickWrite
- _tasks[task]=true
-end
-local function tasks()
- return next,_tasks
-end
-local _readable_t={
- events=function(self)
- local i=0
- return function ()
- i=i+1
- return self._evs[i]
- end
- end,
- tick=function(self,input)
- local handler=_servers[input]
- if handler then
- input=_accept(input,handler)
- else
- _reading:remove(input)
- self.def_tick(input)
- end
- end
-}
-addtaskRead(_readable_t)
-local _writable_t={
- events=function(self)
- local i=0
- return function()
- i=i+1
- return self._evs[i]
- end
- end,
- tick=function(self,output)
- _writing:remove(output)
- self.def_tick(output)
- end
-}
-addtaskWrite(_writable_t)
-local _sleeping_t={
- tick=function(self,time,...)
- _doTick(_sleeping:pop(time),...)
- end
-}
-function copas.sleep(sleeptime)
- yieldcoroutine((sleeptime or 0),_sleeping)
-end
-function copas.wakeup(co)
- _sleeping:wakeup(co)
-end
-local last_cleansing=0
-local function _select(timeout)
- local now=gettime()
- local r_evs,w_evs,err=selectsocket(_reading,_writing,timeout)
- _readable_t._evs=r_evs
- _writable_t._evs=w_evs
- if (last_cleansing-now)>WATCH_DOG_TIMEOUT then
- last_cleansing=now
- for skt,time in next,_reading_log do
- if not r_evs[skt] and (time-now)>WATCH_DOG_TIMEOUT then
- local n=#r_evs+1
- _reading_log[skt]=nil
- r_evs[n]=skt
- r_evs[skt]=n
- end
- end
- for skt,time in next,_writing_log do
- if not w_evs[skt] and (time-now)>WATCH_DOG_TIMEOUT then
- local n=#w_evs+1
- _writing_log[skt]=nil
- w_evs[n]=skt
- w_evs[skt]=n
- end
- end
- end
- if err=="timeout" and #r_evs+#w_evs>0 then
- return nil
- else
- return err
- end
-end
-local function copasfinished()
- return not (next(_reading) or next(_writing) or _sleeping:getnext())
-end
-local function copasstep(timeout)
- _sleeping_t:tick(gettime())
- local nextwait=_sleeping:getnext()
- if nextwait then
- timeout=timeout and min(nextwait,timeout) or nextwait
- elseif copasfinished() then
- return false
- end
- local err=_select(timeout)
- if err then
- if err=="timeout" then
- return false
- end
- return nil,err
- end
- for task in tasks() do
- for event in task:events() do
- task:tick(event)
- end
- end
- return true
-end
-copas.finished=copasfinished
-copas.step=copasstep
-function copas.loop(timeout)
- copas.running=true
- while not copasfinished() do
- copasstep(timeout)
- end
- copas.running=false
-end
-package.loaded["copas"]=copas
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-ltn12"] = package.loaded["util-soc-imp-ltn12"] or true
-
--- original size: 8709, stripped down to: 5411
-
-
-local select,unpack=select,unpack
-local insert,remove=table.insert,table.remove
-local sub=string.sub
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("ltn12")
- report(fmt,first,...)
- elseif fmt then
- fmt="ltn12: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-local filter={}
-local source={}
-local sink={}
-local pump={}
-local ltn12={
- _VERSION="LTN12 1.0.3",
- BLOCKSIZE=2048,
- filter=filter,
- source=source,
- sink=sink,
- pump=pump,
- report=report,
-}
-function filter.cycle(low,ctx,extra)
- if low then
- return function(chunk)
- return (low(ctx,chunk,extra))
- end
- end
-end
-function filter.chain(...)
- local arg={... }
- local n=select('#',...)
- local top=1
- local index=1
- local retry=""
- return function(chunk)
- retry=chunk and retry
- while true do
- local action=arg[index]
- if index==top then
- chunk=action(chunk)
- if chunk=="" or top==n then
- return chunk
- elseif chunk then
- index=index+1
- else
- top=top+1
- index=top
- end
- else
- chunk=action(chunk or "")
- if chunk=="" then
- index=index-1
- chunk=retry
- elseif chunk then
- if index==n then
- return chunk
- else
- index=index+1
- end
- else
- report("error: filter returned inappropriate 'nil'")
- return
- end
- end
- end
- end
-end
-local function empty()
- return nil
-end
-function source.empty()
- return empty
-end
-local function sourceerror(err)
- return function()
- return nil,err
- end
-end
-source.error=sourceerror
-function source.file(handle,io_err)
- if handle then
- local blocksize=ltn12.BLOCKSIZE
- return function()
- local chunk=handle:read(blocksize)
- if not chunk then
- handle:close()
- end
- return chunk
- end
- else
- return sourceerror(io_err or "unable to open file")
- end
-end
-function source.simplify(src)
- return function()
- local chunk,err_or_new=src()
- if err_or_new then
- src=err_or_new
- end
- if chunk then
- return chunk
- else
- return nil,err_or_new
- end
- end
-end
-function source.string(s)
- if s then
- local blocksize=ltn12.BLOCKSIZE
- local i=1
- return function()
- local nexti=i+blocksize
- local chunk=sub(s,i,nexti-1)
- i=nexti
- if chunk~="" then
- return chunk
- else
- return nil
- end
- end
- else return source.empty() end
-end
-function source.rewind(src)
- local t={}
- return function(chunk)
- if chunk then
- insert(t,chunk)
- else
- chunk=remove(t)
- if chunk then
- return chunk
- else
- return src()
- end
- end
- end
-end
-function source.chain(src,f,...)
- if... then
- f=filter.chain(f,...)
- end
- local last_in=""
- local last_out=""
- local state="feeding"
- local err
- return function()
- if not last_out then
- report("error: source is empty")
- return
- end
- while true do
- if state=="feeding" then
- last_in,err=src()
- if err then
- return nil,err
- end
- last_out=f(last_in)
- if not last_out then
- if last_in then
- report("error: filter returned inappropriate 'nil'")
- end
- return nil
- elseif last_out~="" then
- state="eating"
- if last_in then
- last_in=""
- end
- return last_out
- end
- else
- last_out=f(last_in)
- if last_out=="" then
- if last_in=="" then
- state="feeding"
- else
- report("error: filter returned nothing")
- return
- end
- elseif not last_out then
- if last_in then
- report("filter returned inappropriate 'nil'")
- end
- return nil
- else
- return last_out
- end
- end
- end
- end
-end
-function source.cat(...)
- local arg={... }
- local src=remove(arg,1)
- return function()
- while src do
- local chunk,err=src()
- if chunk then
- return chunk
- end
- if err then
- return nil,err
- end
- src=remove(arg,1)
- end
- end
-end
-function sink.table(t)
- if not t then
- t={}
- end
- local f=function(chunk,err)
- if chunk then
- insert(t,chunk)
- end
- return 1
- end
- return f,t
-end
-function sink.simplify(snk)
- return function(chunk,err)
- local ret,err_or_new=snk(chunk,err)
- if not ret then
- return nil,err_or_new
- end
- if err_or_new then
- snk=err_or_new
- end
- return 1
- end
-end
-local function null()
- return 1
-end
-function sink.null()
- return null
-end
-local function sinkerror(err)
- return function()
- return nil,err
- end
-end
-sink.error=sinkerror
-function sink.file(handle,io_err)
- if handle then
- return function(chunk,err)
- if not chunk then
- handle:close()
- return 1
- else
- return handle:write(chunk)
- end
- end
- else
- return sinkerror(io_err or "unable to open file")
- end
-end
-function sink.chain(f,snk,...)
- if... then
- local args={ f,snk,... }
- snk=remove(args,#args)
- f=filter.chain(unpack(args))
- end
- return function(chunk,err)
- if chunk~="" then
- local filtered=f(chunk)
- local done=chunk and ""
- while true do
- local ret,snkerr=snk(filtered,err)
- if not ret then
- return nil,snkerr
- end
- if filtered==done then
- return 1
- end
- filtered=f(done)
- end
- else
- return 1
- end
- end
-end
-function pump.step(src,snk)
- local chunk,src_err=src()
- local ret,snk_err=snk(chunk,src_err)
- if chunk and ret then
- return 1
- else
- return nil,src_err or snk_err
- end
-end
-function pump.all(src,snk,step)
- if not step then
- step=pump.step
- end
- while true do
- local ret,err=step(src,snk)
- if not ret then
- if err then
- return nil,err
- else
- return 1
- end
- end
- end
-end
-package.loaded["ltn12"]=ltn12
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-mime"] = package.loaded["util-soc-imp-mime"] or true
-
--- original size: 2373, stripped down to: 1931
-
-
-local type,tostring=type,tostring
-local mime=mime or package.loaded.mime or require("mime.core")
-local ltn12=ltn12 or package.loaded.ltn12 or require("ltn12")
-local filtercycle=ltn12.filter.cycle
-local function report(fmt,first,...)
- if logs then
- report=logs and logs.reporter("mime")
- report(fmt,first,...)
- elseif fmt then
- fmt="mime: "..fmt
- if first then
- print(format(fmt,first,...))
- else
- print(fmt)
- end
- end
-end
-mime.report=report
-local encodet={}
-local decodet={}
-local wrapt={}
-mime.encodet=encodet
-mime.decodet=decodet
-mime.wrapt=wrapt
-local mime_b64=mime.b64
-local mime_qp=mime.qp
-local mime_unb64=mime.unb64
-local mime_unqp=mime.unqp
-local mime_wrp=mime.wrp
-local mime_qpwrp=mime.qpwrp
-local mime_eol=mime_eol
-local mime_dot=mime_dot
-encodet['base64']=function()
- return filtercycle(mime_b64,"")
-end
-encodet['quoted-printable']=function(mode)
- return filtercycle(mime_qp,"",mode=="binary" and "=0D=0A" or "\r\n")
-end
-decodet['base64']=function()
- return filtercycle(mime_unb64,"")
-end
-decodet['quoted-printable']=function()
- return filtercycle(mime_unqp,"")
-end
-local wraptext=function(length)
- if not length then
- length=76
- end
- return filtercycle(mime_wrp,length,length)
-end
-local wrapquoted=function()
- return filtercycle(mime_qpwrp,76,76)
-end
-wrapt['text']=wraptext
-wrapt['base64']=wraptext
-wrapt['default']=wraptext
-wrapt['quoted-printable']=wrapquoted
-function mime.normalize(marker)
- return filtercycle(mime_eol,0,marker)
-end
-function mime.stuff()
- return filtercycle(mime_dot,2)
-end
-local function choose(list)
- return function(name,opt1,opt2)
- if type(name)~="string" then
- name,opt1,opt2="default",name,opt1
- end
- local filter=list[name or "nil"]
- if filter then
- return filter(opt1,opt2)
- else
- report("error: unknown key '%s'",tostring(name))
- end
- end
-end
-mime.encode=choose(encodet)
-mime.decode=choose(decodet)
-mime.wrap=choose(wrapt)
-package.loaded["mime"]=mime
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-url"] = package.loaded["util-soc-imp-url"] or true
-
--- original size: 6863, stripped down to: 5269
-
-
-local tonumber,tostring,type=tonumber,tostring,type
-local gsub,sub,match,find,format,byte,char=string.gsub,string.sub,string.match,string.find,string.format,string.byte,string.char
-local insert=table.insert
-local socket=socket or require("socket")
-local url={
- _VERSION="URL 1.0.3",
-}
-socket.url=url
-function url.escape(s)
- return (gsub(s,"([^A-Za-z0-9_])",function(c)
- return format("%%%02x",byte(c))
- end))
-end
-local function make_set(t)
- local s={}
- for i=1,#t do
- s[t[i]]=true
- end
- return s
-end
-local segment_set=make_set {
- "-","_",".","!","~","*","'","(",
- ")",":","@","&","=","+","$",",",
-}
-local function protect_segment(s)
- return gsub(s,"([^A-Za-z0-9_])",function(c)
- if segment_set[c] then
- return c
- else
- return format("%%%02X",byte(c))
- end
- end)
-end
-function url.unescape(s)
- return (gsub(s,"%%(%x%x)",function(hex)
- return char(tonumber(hex,16))
- end))
-end
-local function absolute_path(base_path,relative_path)
- if find(relative_path,"^/") then
- return relative_path
- end
- local path=gsub(base_path,"[^/]*$","")
- path=path..relative_path
- path=gsub(path,"([^/]*%./)",function (s)
- if s~="./" then
- return s
- else
- return ""
- end
- end)
- path=gsub(path,"/%.$","/")
- local reduced
- while reduced~=path do
- reduced=path
- path=gsub(reduced,"([^/]*/%.%./)",function (s)
- if s~="../../" then
- return ""
- else
- return s
- end
- end)
- end
- path=gsub(reduced,"([^/]*/%.%.)$",function (s)
- if s~="../.." then
- return ""
- else
- return s
- end
- end)
- return path
-end
-function url.parse(url,default)
- local parsed={}
- for k,v in next,default or parsed do
- parsed[k]=v
- end
- if not url or url=="" then
- return nil,"invalid url"
- end
- url=gsub(url,"#(.*)$",function(f)
- parsed.fragment=f
- return ""
- end)
- url=gsub(url,"^([%w][%w%+%-%.]*)%:",function(s)
- parsed.scheme=s
- return ""
- end)
- url=gsub(url,"^//([^/]*)",function(n)
- parsed.authority=n
- return ""
- end)
- url=gsub(url,"%?(.*)",function(q)
- parsed.query=q
- return ""
- end)
- url=gsub(url,"%;(.*)",function(p)
- parsed.params=p
- return ""
- end)
- if url~="" then
- parsed.path=url
- end
- local authority=parsed.authority
- if not authority then
- return parsed
- end
- authority=gsub(authority,"^([^@]*)@",function(u)
- parsed.userinfo=u
- return ""
- end)
- authority=gsub(authority,":([^:%]]*)$",function(p)
- parsed.port=p
- return ""
- end)
- if authority~="" then
- parsed.host=match(authority,"^%[(.+)%]$") or authority
- end
- local userinfo=parsed.userinfo
- if not userinfo then
- return parsed
- end
- userinfo=gsub(userinfo,":([^:]*)$",function(p)
- parsed.password=p
- return ""
- end)
- parsed.user=userinfo
- return parsed
-end
-function url.build(parsed)
- local url=parsed.path or ""
- if parsed.params then
- url=url..";"..parsed.params
- end
- if parsed.query then
- url=url.."?"..parsed.query
- end
- local authority=parsed.authority
- if parsed.host then
- authority=parsed.host
- if find(authority,":") then
- authority="["..authority.."]"
- end
- if parsed.port then
- authority=authority..":"..tostring(parsed.port)
- end
- local userinfo=parsed.userinfo
- if parsed.user then
- userinfo=parsed.user
- if parsed.password then
- userinfo=userinfo..":"..parsed.password
- end
- end
- if userinfo then authority=userinfo.."@"..authority end
- end
- if authority then
- url="//"..authority..url
- end
- if parsed.scheme then
- url=parsed.scheme..":"..url
- end
- if parsed.fragment then
- url=url.."#"..parsed.fragment
- end
- return url
-end
-function url.absolute(base_url,relative_url)
- local base_parsed
- if type(base_url)=="table" then
- base_parsed=base_url
- base_url=url.build(base_parsed)
- else
- base_parsed=url.parse(base_url)
- end
- local relative_parsed=url.parse(relative_url)
- if not base_parsed then
- return relative_url
- elseif not relative_parsed then
- return base_url
- elseif relative_parsed.scheme then
- return relative_url
- else
- relative_parsed.scheme=base_parsed.scheme
- if not relative_parsed.authority then
- relative_parsed.authority=base_parsed.authority
- if not relative_parsed.path then
- relative_parsed.path=base_parsed.path
- if not relative_parsed.params then
- relative_parsed.params=base_parsed.params
- if not relative_parsed.query then
- relative_parsed.query=base_parsed.query
- end
- end
- else
- relative_parsed.path=absolute_path(base_parsed.path or "",relative_parsed.path)
- end
- end
- return url.build(relative_parsed)
- end
-end
-function url.parse_path(path)
- local parsed={}
- path=path or ""
- gsub(path,"([^/]+)",function (s)
- insert(parsed,s)
- end)
- for i=1,#parsed do
- parsed[i]=url.unescape(parsed[i])
- end
- if sub(path,1,1)=="/" then
- parsed.is_absolute=1
- end
- if sub(path,-1,-1)=="/" then
- parsed.is_directory=1
- end
- return parsed
-end
-function url.build_path(parsed,unsafe)
- local path=""
- local n=#parsed
- if unsafe then
- for i=1,n-1 do
- path=path..parsed[i].."/"
- end
- if n>0 then
- path=path..parsed[n]
- if parsed.is_directory then
- path=path.."/"
- end
- end
- else
- for i=1,n-1 do
- path=path..protect_segment(parsed[i]).."/"
- end
- if n>0 then
- path=path..protect_segment(parsed[n])
- if parsed.is_directory then
- path=path.."/"
- end
- end
- end
- if parsed.is_absolute then
- path="/"..path
- end
- return path
-end
-package.loaded["socket.url"]=url
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-headers"] = package.loaded["util-soc-imp-headers"] or true
-
--- original size: 5721, stripped down to: 3754
-
-
-local next=next
-local lower=string.lower
-local concat=table.concat
-local socket=socket or require("socket")
-local headers={}
-socket.headers=headers
-local canonic={
- ["accept"]="Accept",
- ["accept-charset"]="Accept-Charset",
- ["accept-encoding"]="Accept-Encoding",
- ["accept-language"]="Accept-Language",
- ["accept-ranges"]="Accept-Ranges",
- ["action"]="Action",
- ["alternate-recipient"]="Alternate-Recipient",
- ["age"]="Age",
- ["allow"]="Allow",
- ["arrival-date"]="Arrival-Date",
- ["authorization"]="Authorization",
- ["bcc"]="Bcc",
- ["cache-control"]="Cache-Control",
- ["cc"]="Cc",
- ["comments"]="Comments",
- ["connection"]="Connection",
- ["content-description"]="Content-Description",
- ["content-disposition"]="Content-Disposition",
- ["content-encoding"]="Content-Encoding",
- ["content-id"]="Content-ID",
- ["content-language"]="Content-Language",
- ["content-length"]="Content-Length",
- ["content-location"]="Content-Location",
- ["content-md5"]="Content-MD5",
- ["content-range"]="Content-Range",
- ["content-transfer-encoding"]="Content-Transfer-Encoding",
- ["content-type"]="Content-Type",
- ["cookie"]="Cookie",
- ["date"]="Date",
- ["diagnostic-code"]="Diagnostic-Code",
- ["dsn-gateway"]="DSN-Gateway",
- ["etag"]="ETag",
- ["expect"]="Expect",
- ["expires"]="Expires",
- ["final-log-id"]="Final-Log-ID",
- ["final-recipient"]="Final-Recipient",
- ["from"]="From",
- ["host"]="Host",
- ["if-match"]="If-Match",
- ["if-modified-since"]="If-Modified-Since",
- ["if-none-match"]="If-None-Match",
- ["if-range"]="If-Range",
- ["if-unmodified-since"]="If-Unmodified-Since",
- ["in-reply-to"]="In-Reply-To",
- ["keywords"]="Keywords",
- ["last-attempt-date"]="Last-Attempt-Date",
- ["last-modified"]="Last-Modified",
- ["location"]="Location",
- ["max-forwards"]="Max-Forwards",
- ["message-id"]="Message-ID",
- ["mime-version"]="MIME-Version",
- ["original-envelope-id"]="Original-Envelope-ID",
- ["original-recipient"]="Original-Recipient",
- ["pragma"]="Pragma",
- ["proxy-authenticate"]="Proxy-Authenticate",
- ["proxy-authorization"]="Proxy-Authorization",
- ["range"]="Range",
- ["received"]="Received",
- ["received-from-mta"]="Received-From-MTA",
- ["references"]="References",
- ["referer"]="Referer",
- ["remote-mta"]="Remote-MTA",
- ["reply-to"]="Reply-To",
- ["reporting-mta"]="Reporting-MTA",
- ["resent-bcc"]="Resent-Bcc",
- ["resent-cc"]="Resent-Cc",
- ["resent-date"]="Resent-Date",
- ["resent-from"]="Resent-From",
- ["resent-message-id"]="Resent-Message-ID",
- ["resent-reply-to"]="Resent-Reply-To",
- ["resent-sender"]="Resent-Sender",
- ["resent-to"]="Resent-To",
- ["retry-after"]="Retry-After",
- ["return-path"]="Return-Path",
- ["sender"]="Sender",
- ["server"]="Server",
- ["smtp-remote-recipient"]="SMTP-Remote-Recipient",
- ["status"]="Status",
- ["subject"]="Subject",
- ["te"]="TE",
- ["to"]="To",
- ["trailer"]="Trailer",
- ["transfer-encoding"]="Transfer-Encoding",
- ["upgrade"]="Upgrade",
- ["user-agent"]="User-Agent",
- ["vary"]="Vary",
- ["via"]="Via",
- ["warning"]="Warning",
- ["will-retry-until"]="Will-Retry-Until",
- ["www-authenticate"]="WWW-Authenticate",
- ["x-mailer"]="X-Mailer",
-}
-headers.canonic=setmetatable(canonic,{
- __index=function(t,k)
- socket.report("invalid header: %s",k)
- t[k]=k
- return k
- end
-})
-function headers.normalize(headers)
- if not headers then
- return {}
- end
- local normalized={}
- for k,v in next,headers do
- normalized[#normalized+1]=canonic[k]..": "..v
- end
- normalized[#normalized+1]=""
- normalized[#normalized+1]=""
- return concat(normalized,"\r\n")
-end
-function headers.lower(lowered,headers)
- if not lowered then
- return {}
- end
- if not headers then
- lowered,headers={},lowered
- end
- for k,v in next,headers do
- lowered[lower(k)]=v
- end
- return lowered
-end
-socket.headers=headers
-package.loaded["socket.headers"]=headers
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-tp"] = package.loaded["util-soc-imp-tp"] or true
-
--- original size: 3116, stripped down to: 2533
-
-
-local setmetatable,next,type,tonumber=setmetatable,next,type,tonumber
-local find,upper=string.find,string.upper
-local socket=socket or require("socket")
-local ltn12=ltn12 or require("ltn12")
-local skipsocket=socket.skip
-local sinksocket=socket.sink
-local tcpsocket=socket.tcp
-local ltn12pump=ltn12.pump
-local pumpall=ltn12pump.all
-local pumpstep=ltn12pump.step
-local tp={
- TIMEOUT=60,
-}
-socket.tp=tp
-local function get_reply(c)
- local line,err=c:receive()
- local reply=line
- if err then return
- nil,err
- end
- local code,sep=skipsocket(2,find(line,"^(%d%d%d)(.?)"))
- if not code then
- return nil,"invalid server reply"
- end
- if sep=="-" then
- local current
- repeat
- line,err=c:receive()
- if err then
- return nil,err
- end
- current,sep=skipsocket(2,find(line,"^(%d%d%d)(.?)"))
- reply=reply.."\n"..line
- until code==current and sep==" "
- end
- return code,reply
-end
-local methods={}
-local mt={ __index=methods }
-function methods.getpeername(self)
- return self.c:getpeername()
-end
-function methods.getsockname(self)
- return self.c:getpeername()
-end
-function methods.check(self,ok)
- local code,reply=get_reply(self.c)
- if not code then
- return nil,reply
- end
- local c=tonumber(code)
- local t=type(ok)
- if t=="function" then
- return ok(c,reply)
- elseif t=="table" then
- for i=1,#ok do
- if find(code,ok[i]) then
- return c,reply
- end
- end
- return nil,reply
- elseif find(code,ok) then
- return c,reply
- else
- return nil,reply
- end
-end
-function methods.command(self,cmd,arg)
- cmd=upper(cmd)
- if arg then
- cmd=cmd.." "..arg.."\r\n"
- else
- cmd=cmd.."\r\n"
- end
- return self.c:send(cmd)
-end
-function methods.sink(self,snk,pat)
- local chunk,err=self.c:receive(pat)
- return snk(chunk,err)
-end
-function methods.send(self,data)
- return self.c:send(data)
-end
-function methods.receive(self,pat)
- return self.c:receive(pat)
-end
-function methods.getfd(self)
- return self.c:getfd()
-end
-function methods.dirty(self)
- return self.c:dirty()
-end
-function methods.getcontrol(self)
- return self.c
-end
-function methods.source(self,source,step)
- local sink=sinksocket("keep-open",self.c)
- local ret,err=pumpall(source,sink,step or pumpstep)
- return ret,err
-end
-function methods.close(self)
- self.c:close()
- return 1
-end
-function tp.connect(host,port,timeout,create)
- local c,e=(create or tcpsocket)()
- if not c then
- return nil,e
- end
- c:settimeout(timeout or tp.TIMEOUT)
- local r,e=c:connect(host,port)
- if not r then
- c:close()
- return nil,e
- end
- return setmetatable({ c=c },mt)
-end
-package.loaded["socket.tp"]=tp
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-http"] = package.loaded["util-soc-imp-http"] or true
-
--- original size: 12624, stripped down to: 9598
-
-
-local tostring,tonumber,setmetatable,next,type=tostring,tonumber,setmetatable,next,type
-local find,lower,format,gsub,match=string.find,string.lower,string.format,string.gsub,string.match
-local concat=table.concat
-local socket=socket or require("socket")
-local url=socket.url or require("socket.url")
-local ltn12=ltn12 or require("ltn12")
-local mime=mime or require("mime")
-local headers=socket.headers or require("socket.headers")
-local normalizeheaders=headers.normalize
-local parseurl=url.parse
-local buildurl=url.build
-local absoluteurl=url.absolute
-local unescapeurl=url.unescape
-local skipsocket=socket.skip
-local sinksocket=socket.sink
-local sourcesocket=socket.source
-local trysocket=socket.try
-local tcpsocket=socket.tcp
-local newtrysocket=socket.newtry
-local protectsocket=socket.protect
-local emptysource=ltn12.source.empty
-local stringsource=ltn12.source.string
-local rewindsource=ltn12.source.rewind
-local pumpstep=ltn12.pump.step
-local pumpall=ltn12.pump.all
-local sinknull=ltn12.sink.null
-local sinktable=ltn12.sink.table
-local lowerheaders=headers.lower
-local mimeb64=mime.b64
-local http={
- TIMEOUT=60,
- USERAGENT=socket._VERSION,
-}
-socket.http=http
-local PORT=80
-local SCHEMES={
- http=true,
-}
-local function receiveheaders(sock,headers)
- if not headers then
- headers={}
- end
- local line,err=sock:receive("*l")
- if err then
- return nil,err
- end
- while line~="" do
- local name,value=skipsocket(2,find(line,"^(.-):%s*(.*)"))
- if not (name and value) then
- return nil,"malformed reponse headers"
- end
- name=lower(name)
- line,err=sock:receive("*l")
- if err then
- return nil,err
- end
- while find(line,"^%s") do
- value=value..line
- line=sock:receive("*l")
- if err then
- return nil,err
- end
- end
- local found=headers[name]
- if found then
- value=found..", "..value
- end
- headers[name]=value
- end
- return headers
-end
-socket.sourcet["http-chunked"]=function(sock,headers)
- return setmetatable (
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },{
- __call=function()
- local line,err=sock:receive("*l")
- if err then
- return nil,err
- end
- local size=tonumber(gsub(line,";.*",""),16)
- if not size then
- return nil,"invalid chunk size"
- end
- if size>0 then
- local chunk,err,part=sock:receive(size)
- if chunk then
- sock:receive("*a")
- end
- return chunk,err
- else
- headers,err=receiveheaders(sock,headers)
- if not headers then
- return nil,err
- end
- end
- end
- }
- )
-end
-socket.sinkt["http-chunked"]=function(sock)
- return setmetatable(
- {
- getfd=function() return sock:getfd() end,
- dirty=function() return sock:dirty() end,
- },
- {
- __call=function(self,chunk,err)
- if not chunk then
- chunk=""
- end
- return sock:send(format("%X\r\n%s\r\n",#chunk,chunk))
- end
- })
-end
-local methods={}
-local mt={ __index=methods }
-local function openhttp(host,port,create)
- local c=trysocket((create or tcpsocket)())
- local h=setmetatable({ c=c },mt)
- local try=newtrysocket(function() h:close() end)
- h.try=try
- try(c:settimeout(http.TIMEOUT))
- try(c:connect(host,port or PORT))
- return h
-end
-http.open=openhttp
-function methods.sendrequestline(self,method,uri)
- local requestline=format("%s %s HTTP/1.1\r\n",method or "GET",uri)
- return self.try(self.c:send(requestline))
-end
-function methods.sendheaders(self,headers)
- self.try(self.c:send(normalizeheaders(headers)))
- return 1
-end
-function methods.sendbody(self,headers,source,step)
- if not source then
- source=emptysource()
- end
- if not step then
- step=pumpstep
- end
- local mode="http-chunked"
- if headers["content-length"] then
- mode="keep-open"
- end
- return self.try(pumpall(source,sinksocket(mode,self.c),step))
-end
-function methods.receivestatusline(self)
- local try=self.try
- local status=try(self.c:receive(5))
- if status~="HTTP/" then
- return nil,status
- end
- status=try(self.c:receive("*l",status))
- local code=skipsocket(2,find(status,"HTTP/%d*%.%d* (%d%d%d)"))
- return try(tonumber(code),status)
-end
-function methods.receiveheaders(self)
- return self.try(receiveheaders(self.c))
-end
-function methods.receivebody(self,headers,sink,step)
- if not sink then
- sink=sinknull()
- end
- if not step then
- step=pumpstep
- end
- local length=tonumber(headers["content-length"])
- local encoding=headers["transfer-encoding"]
- local mode="default"
- if encoding and encoding~="identity" then
- mode="http-chunked"
- elseif length then
- mode="by-length"
- end
- return self.try(pumpall(sourcesocket(mode,self.c,length),sink,step))
-end
-function methods.receive09body(self,status,sink,step)
- local source=rewindsource(sourcesocket("until-closed",self.c))
- source(status)
- return self.try(pumpall(source,sink,step))
-end
-function methods.close(self)
- return self.c:close()
-end
-local function adjusturi(request)
- if not request.proxy and not http.PROXY then
- request={
- path=trysocket(request.path,"invalid path 'nil'"),
- params=request.params,
- query=request.query,
- fragment=request.fragment,
- }
- end
- return buildurl(request)
-end
-local function adjustheaders(request)
- local headers={
- ["user-agent"]=http.USERAGENT,
- ["host"]=gsub(request.authority,"^.-@",""),
- ["connection"]="close, TE",
- ["te"]="trailers"
- }
- local username=request.user
- local password=request.password
- if username and password then
- headers["authorization"]="Basic "..(mimeb64(username..":"..unescapeurl(password)))
- end
- local proxy=request.proxy or http.PROXY
- if proxy then
- proxy=parseurl(proxy)
- local username=proxy.user
- local password=proxy.password
- if username and password then
- headers["proxy-authorization"]="Basic "..(mimeb64(username..":"..password))
- end
- end
- local requestheaders=request.headers
- if requestheaders then
- headers=lowerheaders(headers,requestheaders)
- end
- return headers
-end
-local default={
- host="",
- port=PORT,
- path="/",
- scheme="http"
-}
-local function adjustrequest(originalrequest)
- local url=originalrequest.url
- local request=url and parseurl(url,default) or {}
- for k,v in next,originalrequest do
- request[k]=v
- end
- local host=request.host
- local port=request.port
- local uri=request.uri
- if not host or host=="" then
- trysocket(nil,"invalid host '"..tostring(host).."'")
- end
- if port=="" then
- request.port=PORT
- end
- if not uri or uri=="" then
- request.uri=adjusturi(request)
- end
- request.headers=adjustheaders(request)
- local proxy=request.proxy or http.PROXY
- if proxy then
- proxy=parseurl(proxy)
- request.host=proxy.host
- request.port=proxy.port or 3128
- end
- return request
-end
-local maxredericts=4
-local validredirects={ [301]=true,[302]=true,[303]=true,[307]=true }
-local validmethods={ [false]=true,GET=true,HEAD=true }
-local function shouldredirect(request,code,headers)
- local location=headers.location
- if not location then
- return false
- end
- location=gsub(location,"%s","")
- if location=="" then
- return false
- end
- local scheme=match(location,"^([%w][%w%+%-%.]*)%:")
- if scheme and not SCHEMES[scheme] then
- return false
- end
- local method=request.method
- local redirect=request.redirect
- local redirects=request.nredirects or 0
- return redirect and validredirects[code] and validmethods[method] and redirects<=maxredericts
-end
-local function shouldreceivebody(request,code)
- if request.method=="HEAD" then
- return nil
- end
- if code==204 or code==304 then
- return nil
- end
- if code>=100 and code<200 then
- return nil
- end
- return 1
-end
-local tredirect,trequest,srequest
-tredirect=function(request,location)
- local result,code,headers,status=trequest {
- url=absoluteurl(request.url,location),
- source=request.source,
- sink=request.sink,
- headers=request.headers,
- proxy=request.proxy,
- nredirects=(request.nredirects or 0)+1,
- create=request.create,
- }
- if not headers then
- headers={}
- end
- if not headers.location then
- headers.location=location
- end
- return result,code,headers,status
-end
-trequest=function(originalrequest)
- local request=adjustrequest(originalrequest)
- local connection=openhttp(request.host,request.port,request.create)
- local headers=request.headers
- connection:sendrequestline(request.method,request.uri)
- connection:sendheaders(headers)
- if request.source then
- connection:sendbody(headers,request.source,request.step)
- end
- local code,status=connection:receivestatusline()
- if not code then
- connection:receive09body(status,request.sink,request.step)
- return 1,200
- end
- while code==100 do
- headers=connection:receiveheaders()
- code,status=connection:receivestatusline()
- end
- headers=connection:receiveheaders()
- if shouldredirect(request,code,headers) and not request.source then
- connection:close()
- return tredirect(originalrequest,headers.location)
- end
- if shouldreceivebody(request,code) then
- connection:receivebody(headers,request.sink,request.step)
- end
- connection:close()
- return 1,code,headers,status
-end
-local function genericform(url,body)
- local buffer={}
- local request={
- url=url,
- sink=sinktable(buffer),
- target=buffer,
- }
- if body then
- request.source=stringsource(body)
- request.method="POST"
- request.headers={
- ["content-length"]=#body,
- ["content-type"]="application/x-www-form-urlencoded"
- }
- end
- return request
-end
-http.genericform=genericform
-srequest=function(url,body)
- local request=genericform(url,body)
- local _,code,headers,status=trequest(request)
- return concat(request.target),code,headers,status
-end
-http.request=protectsocket(function(request,body)
- if type(request)=="string" then
- return srequest(request,body)
- else
- return trequest(request)
- end
-end)
-package.loaded["socket.http"]=http
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-ftp"] = package.loaded["util-soc-imp-ftp"] or true
-
--- original size: 10357, stripped down to: 8548
-
-
-local setmetatable,type,next=setmetatable,type,next
-local find,format,gsub,match=string.find,string.format,string.gsub,string.match
-local concat=table.concat
-local mod=math.mod
-local socket=socket or require("socket")
-local url=socket.url or require("socket.url")
-local tp=socket.tp or require("socket.tp")
-local ltn12=ltn12 or require("ltn12")
-local tcpsocket=socket.tcp
-local trysocket=socket.try
-local skipsocket=socket.skip
-local sinksocket=socket.sink
-local selectsocket=socket.select
-local bindsocket=socket.bind
-local newtrysocket=socket.newtry
-local sourcesocket=socket.source
-local protectsocket=socket.protect
-local parseurl=url.parse
-local unescapeurl=url.unescape
-local pumpall=ltn12.pump.all
-local pumpstep=ltn12.pump.step
-local sourcestring=ltn12.source.string
-local sinktable=ltn12.sink.table
-local ftp={
- TIMEOUT=60,
- USER="ftp",
- PASSWORD="anonymous@anonymous.org",
-}
-socket.ftp=ftp
-local PORT=21
-local methods={}
-local mt={ __index=methods }
-function ftp.open(server,port,create)
- local tp=trysocket(tp.connect(server,port or PORT,ftp.TIMEOUT,create))
- local f=setmetatable({ tp=tp },metat)
- f.try=newtrysocket(function() f:close() end)
- return f
-end
-function methods.portconnect(self)
- local try=self.try
- local server=self.server
- try(server:settimeout(ftp.TIMEOUT))
- self.data=try(server:accept())
- try(self.data:settimeout(ftp.TIMEOUT))
-end
-function methods.pasvconnect(self)
- local try=self.try
- self.data=try(tcpsocket())
- self(self.data:settimeout(ftp.TIMEOUT))
- self(self.data:connect(self.pasvt.address,self.pasvt.port))
-end
-function methods.login(self,user,password)
- local try=self.try
- local tp=self.tp
- try(tp:command("user",user or ftp.USER))
- local code,reply=try(tp:check{"2..",331})
- if code==331 then
- try(tp:command("pass",password or ftp.PASSWORD))
- try(tp:check("2.."))
- end
- return 1
-end
-function methods.pasv(self)
- local try=self.try
- local tp=self.tp
- try(tp:command("pasv"))
- local code,reply=try(self.tp:check("2.."))
- local pattern="(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)"
- local a,b,c,d,p1,p2=skipsocket(2,find(reply,pattern))
- try(a and b and c and d and p1 and p2,reply)
- local address=format("%d.%d.%d.%d",a,b,c,d)
- local port=p1*256+p2
- local server=self.server
- self.pasvt={
- address=address,
- port=port,
- }
- if server then
- server:close()
- self.server=nil
- end
- return address,port
-end
-function methods.epsv(self)
- local try=self.try
- local tp=self.tp
- try(tp:command("epsv"))
- local code,reply=try(tp:check("229"))
- local pattern="%((.)(.-)%1(.-)%1(.-)%1%)"
- local d,prt,address,port=match(reply,pattern)
- try(port,"invalid epsv response")
- local address=tp:getpeername()
- local server=self.server
- self.pasvt={
- address=address,
- port=port,
- }
- if self.server then
- server:close()
- self.server=nil
- end
- return address,port
-end
-function methods.port(self,address,port)
- local try=self.try
- local tp=self.tp
- self.pasvt=nil
- if not address then
- address,port=try(tp:getsockname())
- self.server=try(bindsocket(address,0))
- address,port=try(self.server:getsockname())
- try(self.server:settimeout(ftp.TIMEOUT))
- end
- local pl=mod(port,256)
- local ph=(port-pl)/256
- local arg=gsub(format("%s,%d,%d",address,ph,pl),"%.",",")
- try(tp:command("port",arg))
- try(tp:check("2.."))
- return 1
-end
-function methods.eprt(self,family,address,port)
- local try=self.try
- local tp=self.tp
- self.pasvt=nil
- if not address then
- address,port=try(tp:getsockname())
- self.server=try(bindsocket(address,0))
- address,port=try(self.server:getsockname())
- try(self.server:settimeout(ftp.TIMEOUT))
- end
- local arg=format("|%s|%s|%d|",family,address,port)
- try(tp:command("eprt",arg))
- try(tp:check("2.."))
- return 1
-end
-function methods.send(self,sendt)
- local try=self.try
- local tp=self.tp
- try(self.pasvt or self.server,"need port or pasv first")
- if self.pasvt then
- self:pasvconnect()
- end
- local argument=sendt.argument or unescapeurl(gsub(sendt.path or "","^[/\\]",""))
- if argument=="" then
- argument=nil
- end
- local command=sendt.command or "stor"
- try(tp:command(command,argument))
- local code,reply=try(tp:check{"2..","1.."})
- if not self.pasvt then
- self:portconnect()
- end
- local step=sendt.step or pumpstep
- local readt={ tp }
- local checkstep=function(src,snk)
- local readyt=selectsocket(readt,nil,0)
- if readyt[tp] then
- code=try(tp:check("2.."))
- end
- return step(src,snk)
- end
- local sink=sinksocket("close-when-done",self.data)
- try(pumpall(sendt.source,sink,checkstep))
- if find(code,"1..") then
- try(tp:check("2.."))
- end
- self.data:close()
- local sent=skipsocket(1,self.data:getstats())
- self.data=nil
- return sent
-end
-function methods.receive(self,recvt)
- local try=self.try
- local tp=self.tp
- try(self.pasvt or self.server,"need port or pasv first")
- if self.pasvt then self:pasvconnect() end
- local argument=recvt.argument or unescapeurl(gsub(recvt.path or "","^[/\\]",""))
- if argument=="" then
- argument=nil
- end
- local command=recvt.command or "retr"
- try(tp:command(command,argument))
- local code,reply=try(tp:check{"1..","2.."})
- if code>=200 and code<=299 then
- recvt.sink(reply)
- return 1
- end
- if not self.pasvt then
- self:portconnect()
- end
- local source=sourcesocket("until-closed",self.data)
- local step=recvt.step or pumpstep
- try(pumpall(source,recvt.sink,step))
- if find(code,"1..") then
- try(tp:check("2.."))
- end
- self.data:close()
- self.data=nil
- return 1
-end
-function methods.cwd(self,dir)
- local try=self.try
- local tp=self.tp
- try(tp:command("cwd",dir))
- try(tp:check(250))
- return 1
-end
-function methods.type(self,typ)
- local try=self.try
- local tp=self.tp
- try(tp:command("type",typ))
- try(tp:check(200))
- return 1
-end
-function methods.greet(self)
- local try=self.try
- local tp=self.tp
- local code=try(tp:check{"1..","2.."})
- if find(code,"1..") then
- try(tp:check("2.."))
- end
- return 1
-end
-function methods.quit(self)
- local try=self.try
- try(self.tp:command("quit"))
- try(self.tp:check("2.."))
- return 1
-end
-function methods.close(self)
- local data=self.data
- if data then
- data:close()
- end
- local server=self.server
- if server then
- server:close()
- end
- local tp=self.tp
- if tp then
- tp:close()
- end
-end
-local function override(t)
- if t.url then
- local u=parseurl(t.url)
- for k,v in next,t do
- u[k]=v
- end
- return u
- else
- return t
- end
-end
-local function tput(putt)
- putt=override(putt)
- local host=putt.host
- trysocket(host,"missing hostname")
- local f=ftp.open(host,putt.port,putt.create)
- f:greet()
- f:login(putt.user,putt.password)
- local typ=putt.type
- if typ then
- f:type(typ)
- end
- f:epsv()
- local sent=f:send(putt)
- f:quit()
- f:close()
- return sent
-end
-local default={
- path="/",
- scheme="ftp",
-}
-local function genericform(u)
- local t=trysocket(parseurl(u,default))
- trysocket(t.scheme=="ftp","wrong scheme '"..t.scheme.."'")
- trysocket(t.host,"missing hostname")
- local pat="^type=(.)$"
- if t.params then
- local typ=skipsocket(2,find(t.params,pat))
- t.type=typ
- trysocket(typ=="a" or typ=="i","invalid type '"..typ.."'")
- end
- return t
-end
-ftp.genericform=genericform
-local function sput(u,body)
- local putt=genericform(u)
- putt.source=sourcestring(body)
- return tput(putt)
-end
-ftp.put=protectsocket(function(putt,body)
- if type(putt)=="string" then
- return sput(putt,body)
- else
- return tput(putt)
- end
-end)
-local function tget(gett)
- gett=override(gett)
- local host=gett.host
- trysocket(host,"missing hostname")
- local f=ftp.open(host,gett.port,gett.create)
- f:greet()
- f:login(gett.user,gett.password)
- if gett.type then
- f:type(gett.type)
- end
- f:epsv()
- f:receive(gett)
- f:quit()
- return f:close()
-end
-local function sget(u)
- local gett=genericform(u)
- local t={}
- gett.sink=sinktable(t)
- tget(gett)
- return concat(t)
-end
-ftp.command=protectsocket(function(cmdt)
- cmdt=override(cmdt)
- local command=cmdt.command
- local argument=cmdt.argument
- local check=cmdt.check
- local host=cmdt.host
- trysocket(host,"missing hostname")
- trysocket(command,"missing command")
- local f=ftp.open(host,cmdt.port,cmdt.create)
- local try=f.try
- local tp=f.tp
- f:greet()
- f:login(cmdt.user,cmdt.password)
- if type(command)=="table" then
- local argument=argument or {}
- for i=1,#command do
- local cmd=command[i]
- try(tp:command(cmd,argument[i]))
- if check and check[i] then
- try(tp:check(check[i]))
- end
- end
- else
- try(tp:command(command,argument))
- if check then
- try(tp:check(check))
- end
- end
- f:quit()
- return f:close()
-end)
-ftp.get=protectsocket(function(gett)
- if type(gett)=="string" then
- return sget(gett)
- else
- return tget(gett)
- end
-end)
-package.loaded["socket.ftp"]=ftp
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-soc-imp-smtp"] = package.loaded["util-soc-imp-smtp"] or true
-
--- original size: 7018, stripped down to: 5883
-
-
-local type,setmetatable,next=type,setmetatable,next
-local find,lower,format=string.find,string.lower,string.format
-local osdate,osgetenv=os.date,os.getenv
-local random=math.random
-local socket=socket or require("socket")
-local headers=socket.headers or require("socket.headers")
-local ltn12=ltn12 or require("ltn12")
-local tp=socket.tp or require("socket.tp")
-local mime=mime or require("mime")
-local mimeb64=mime.b64
-local mimestuff=mime.stuff
-local skipsocket=socket.skip
-local trysocket=socket.try
-local newtrysocket=socket.newtry
-local protectsocket=socket.protect
-local normalizeheaders=headers.normalize
-local lowerheaders=headers.lower
-local createcoroutine=coroutine.create
-local resumecoroutine=coroutine.resume
-local yieldcoroutine=coroutine.resume
-local smtp={
- TIMEOUT=60,
- SERVER="localhost",
- PORT=25,
- DOMAIN=osgetenv("SERVER_NAME") or "localhost",
- ZONE="-0000",
-}
-socket.smtp=smtp
-local methods={}
-local mt={ __index=methods }
-function methods.greet(self,domain)
- local try=self.try
- local tp=self.tp
- try(tp:check("2.."))
- try(tp:command("EHLO",domain or _M.DOMAIN))
- return skipsocket(1,try(tp:check("2..")))
-end
-function methods.mail(self,from)
- local try=self.try
- local tp=self.tp
- try(tp:command("MAIL","FROM:"..from))
- return try(tp:check("2.."))
-end
-function methods.rcpt(self,to)
- local try=self.try
- local tp=self.tp
- try(tp:command("RCPT","TO:"..to))
- return try(tp:check("2.."))
-end
-function methods.data(self,src,step)
- local try=self.try
- local tp=self.tp
- try(tp:command("DATA"))
- try(tp:check("3.."))
- try(tp:source(src,step))
- try(tp:send("\r\n.\r\n"))
- return try(tp:check("2.."))
-end
-function methods.quit(self)
- local try=self.try
- local tp=self.tp
- try(tp:command("QUIT"))
- return try(tp:check("2.."))
-end
-function methods.close(self)
- return self.tp:close()
-end
-function methods.login(self,user,password)
- local try=self.try
- local tp=self.tp
- try(tp:command("AUTH","LOGIN"))
- try(tp:check("3.."))
- try(tp:send(mimeb64(user).."\r\n"))
- try(tp:check("3.."))
- try(tp:send(mimeb64(password).."\r\n"))
- return try(tp:check("2.."))
-end
-function methods.plain(self,user,password)
- local try=self.try
- local tp=self.tp
- local auth="PLAIN "..mimeb64("\0"..user.."\0"..password)
- try(tp:command("AUTH",auth))
- return try(tp:check("2.."))
-end
-function methods.auth(self,user,password,ext)
- if not user or not password then
- return 1
- end
- local try=self.try
- if find(ext,"AUTH[^\n]+LOGIN") then
- return self:login(user,password)
- elseif find(ext,"AUTH[^\n]+PLAIN") then
- return self:plain(user,password)
- else
- try(nil,"authentication not supported")
- end
-end
-function methods.send(self,mail)
- self:mail(mail.from)
- local receipt=mail.rcpt
- if type(receipt)=="table" then
- for i=1,#receipt do
- self:rcpt(receipt[i])
- end
- elseif receipt then
- self:rcpt(receipt)
- end
- self:data(ltn12.source.chain(mail.source,mimestuff()),mail.step)
-end
-local function opensmtp(self,server,port,create)
- if not server or server=="" then
- server=smtp.SERVER
- end
- if not port or port=="" then
- port=smtp.PORT
- end
- local s={
- tp=trysocket(tp.connect(server,port,smtp.TIMEOUT,create)),
- try=newtrysocket(function()
- s:close()
- end),
- }
- setmetatable(s,mt)
- return s
-end
-smtp.open=opensmtp
-local nofboundaries=0
-local function newboundary()
- nofboundaries=nofboundaries+1
- return format('%s%05d==%05u',osdate('%d%m%Y%H%M%S'),random(0,99999),nofboundaries)
-end
-local send_message
-local function send_headers(headers)
- yieldcoroutine(normalizeheaders(headers))
-end
-local function send_multipart(message)
- local boundary=newboundary()
- local headers=lowerheaders(message.headers)
- local body=message.body
- local preamble=body.preamble
- local epilogue=body.epilogue
- local content=headers['content-type'] or 'multipart/mixed'
- headers['content-type']=content..'; boundary="'..boundary..'"'
- send_headers(headers)
- if preamble then
- yieldcoroutine(preamble)
- yieldcoroutine("\r\n")
- end
- for i=1,#body do
- yieldcoroutine("\r\n--"..boundary.."\r\n")
- send_message(body[i])
- end
- yieldcoroutine("\r\n--"..boundary.."--\r\n\r\n")
- if epilogue then
- yieldcoroutine(epilogue)
- yieldcoroutine("\r\n")
- end
-end
-local default_content_type='text/plain; charset="UTF-8"'
-local function send_source(message)
- local headers=lowerheaders(message.headers)
- if not headers['content-type'] then
- headers['content-type']=default_content_type
- end
- send_headers(headers)
- local getchunk=message.body
- while true do
- local chunk,err=getchunk()
- if err then
- yieldcoroutine(nil,err)
- elseif chunk then
- yieldcoroutine(chunk)
- else
- break
- end
- end
-end
-local function send_string(message)
- local headers=lowerheaders(message.headers)
- if not headers['content-type'] then
- headers['content-type']=default_content_type
- end
- send_headers(headers)
- yieldcoroutine(message.body)
-end
-function send_message(message)
- local body=message.body
- if type(body)=="table" then
- send_multipart(message)
- elseif type(body)=="function" then
- send_source(message)
- else
- send_string(message)
- end
-end
-local function adjust_headers(message)
- local headers=lowerheaders(message.headers)
- if not headers["date"] then
- headers["date"]=osdate("!%a, %d %b %Y %H:%M:%S ")..(message.zone or smtp.ZONE)
- end
- if not headers["x-mailer"] then
- headers["x-mailer"]=socket._VERSION
- end
- headers["mime-version"]="1.0"
- return headers
-end
-function smtp.message(message)
- message.headers=adjust_headers(message)
- local action=createcoroutine(function()
- send_message(message)
- end)
- return function()
- local ret,a,b=resumecoroutine(action)
- if ret then
- return a,b
- else
- return nil,a
- end
- end
-end
-smtp.send=protectsocket(function(mail)
- local snd=opensmtp(smtp,mail.server,mail.port,mail.create)
- local ext=snd:greet(mail.domain)
- snd:auth(mail.user,mail.password,ext)
- snd:send(mail)
- snd:quit()
- return snd:close()
-end)
-package.loaded["socket.smtp"]=smtp
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-set"] = package.loaded["trac-set"] or true
-
--- original size: 13901, stripped down to: 9175
-
-if not modules then modules={} end modules ['trac-set']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,next,tostring,tonumber=type,next,tostring,tonumber
-local print=print
-local concat,sortedhash=table.concat,table.sortedhash
-local formatters,find,lower,gsub,topattern=string.formatters,string.find,string.lower,string.gsub,string.topattern
-local is_boolean=string.is_boolean
-local settings_to_hash=utilities.parsers.settings_to_hash
-local allocate=utilities.storage.allocate
-utilities=utilities or {}
-local utilities=utilities
-local setters=utilities.setters or {}
-utilities.setters=setters
-local data={}
-local trace_initialize=false
-local frozen=true
-local function initialize_setter(filename,name,values)
- local setter=data[name]
- if setter then
- local data=setter.data
- if data then
- for key,newvalue in sortedhash(values) do
- local newvalue=is_boolean(newvalue,newvalue,true)
- local functions=data[key]
- if functions then
- local oldvalue=functions.value
- if functions.frozen then
- if trace_initialize then
- setter.report("%s: %a is %s to %a",filename,key,"frozen",oldvalue)
- end
- elseif #functions>0 and not oldvalue then
- if trace_initialize then
- setter.report("%s: %a is %s to %a",filename,key,"set",newvalue)
- end
- for i=1,#functions do
- functions[i](newvalue)
- end
- functions.value=newvalue
- functions.frozen=functions.frozen or frozen
- else
- if trace_initialize then
- setter.report("%s: %a is %s as %a",filename,key,"kept",oldvalue)
- end
- end
- else
- functions={ default=newvalue,frozen=frozen }
- data[key]=functions
- if trace_initialize then
- setter.report("%s: %a is %s to %a",filename,key,"defaulted",newvalue)
- end
- end
- end
- return true
- end
- end
-end
-local function set(t,what,newvalue)
- local data=t.data
- if data and not data.frozen then
- local done=t.done
- if type(what)=="string" then
- what=settings_to_hash(what)
- end
- if type(what)~="table" then
- return
- end
- if not done then
- done={}
- t.done=done
- end
- for w,value in sortedhash(what) do
- if value=="" then
- value=newvalue
- elseif not value then
- value=false
- else
- value=is_boolean(value,value,true)
- end
- w=topattern(w,true,true)
- for name,functions in sortedhash(data) do
- if done[name] then
- elseif find(name,w) then
- done[name]=true
- for i=1,#functions do
- functions[i](value)
- end
- functions.value=value
- end
- end
- end
- end
-end
-local function reset(t)
- local data=t.data
- if data and not data.frozen then
- for name,functions in sortedthash(data) do
- for i=1,#functions do
- functions[i](false)
- end
- functions.value=false
- end
- end
-end
-local function enable(t,what)
- set(t,what,true)
-end
-local function disable(t,what)
- local data=t.data
- if not what or what=="" then
- t.done={}
- reset(t)
- else
- set(t,what,false)
- end
-end
-local function register_setter(t,what,...)
- local data=t.data
- what=lower(what)
- local functions=data[what]
- if not functions then
- functions={}
- data[what]=functions
- if trace_initialize then
- t.report("defining %a",what)
- end
- end
- local default=functions.default
- for i=1,select("#",...) do
- local fnc=select(i,...)
- local typ=type(fnc)
- if typ=="string" then
- if trace_initialize then
- t.report("coupling %a to %a",what,fnc)
- end
- local s=fnc
- fnc=function(value) set(t,s,value) end
- elseif typ~="function" then
- fnc=nil
- end
- if fnc then
- functions[#functions+1]=fnc
- local value=functions.value or default
- if value~=nil then
- fnc(value)
- functions.value=value
- end
- end
- end
- return false
-end
-local function enable_setter(t,what)
- local e=t.enable
- t.enable,t.done=enable,{}
- set(t,what,true)
- enable(t,what)
- t.enable,t.done=e,{}
-end
-local function disable_setter(t,what)
- local e=t.disable
- t.disable,t.done=disable,{}
- disable(t,what)
- t.disable,t.done=e,{}
-end
-local function reset_setter(t)
- t.done={}
- reset(t)
-end
-local function list_setter(t)
- local list=table.sortedkeys(t.data)
- local user,system={},{}
- for l=1,#list do
- local what=list[l]
- if find(what,"^%*") then
- system[#system+1]=what
- else
- user[#user+1]=what
- end
- end
- return user,system
-end
-local function show_setter(t)
- local list=list_setter(t)
- t.report()
- for k=1,#list do
- local name=list[k]
- local functions=t.data[name]
- if functions then
- local value=functions.value
- local default=functions.default
- local modules=#functions
- if default==nil then
- default="unset"
- elseif type(default)=="table" then
- default=concat(default,"|")
- else
- default=tostring(default)
- end
- if value==nil then
- value="unset"
- elseif type(value)=="table" then
- value=concat(value,"|")
- else
- value=tostring(value)
- end
- t.report(name)
- t.report(" modules : %i",modules)
- t.report(" default : %s",default)
- t.report(" value : %s",value)
- t.report()
- end
- end
-end
-function setters.report(setter,fmt,...)
- if fmt then
- print(formatters["%-15s : %s"](setter.name,formatters[fmt](...)))
- else
- print("")
- end
-end
-local function setter_default(setter,name)
- local d=setter.data[name]
- return d and d.default
-end
-local function setter_value(setter,name)
- local d=setter.data[name]
- return d and (d.value or d.default)
-end
-local function new_setter(name)
- local setter
- setter={
- data=allocate(),
- name=name,
- report=function(...) setters.report (setter,...) end,
- enable=function(...) enable_setter (setter,...) end,
- disable=function(...) disable_setter (setter,...) end,
- reset=function(...) reset_setter (setter,...) end,
- register=function(...) register_setter(setter,...) end,
- list=function(...) return list_setter (setter,...) end,
- show=function(...) show_setter (setter,...) end,
- default=function(...) return setter_default (setter,...) end,
- value=function(...) return setter_value (setter,...) end,
- }
- data[name]=setter
- return setter
-end
-setters.enable=enable_setter
-setters.disable=disable_setter
-setters.register=register_setter
-setters.list=list_setter
-setters.show=show_setter
-setters.reset=reset_setter
-setters.new=new_setter
-setters.initialize=initialize_setter
-trackers=new_setter("trackers")
-directives=new_setter("directives")
-experiments=new_setter("experiments")
-local t_enable,t_disable=trackers .enable,trackers .disable
-local d_enable,d_disable=directives .enable,directives .disable
-local e_enable,e_disable=experiments.enable,experiments.disable
-local trace_directives=false local trace_directives=false trackers.register("system.directives",function(v) trace_directives=v end)
-local trace_experiments=false local trace_experiments=false trackers.register("system.experiments",function(v) trace_experiments=v end)
-function directives.enable(...)
- if trace_directives then
- directives.report("enabling: % t",{...})
- end
- d_enable(...)
-end
-function directives.disable(...)
- if trace_directives then
- directives.report("disabling: % t",{...})
- end
- d_disable(...)
-end
-function experiments.enable(...)
- if trace_experiments then
- experiments.report("enabling: % t",{...})
- end
- e_enable(...)
-end
-function experiments.disable(...)
- if trace_experiments then
- experiments.report("disabling: % t",{...})
- end
- e_disable(...)
-end
-directives.register("system.nostatistics",function(v)
- if statistics then
- statistics.enable=not v
- else
- end
-end)
-directives.register("system.nolibraries",function(v)
- if libraries then
- libraries=nil
- else
- end
-end)
-if environment then
- local engineflags=environment.engineflags
- if engineflags then
- local list=engineflags["c:trackers"] or engineflags["trackers"]
- if type(list)=="string" then
- initialize_setter("commandline flags","trackers",settings_to_hash(list))
- end
- local list=engineflags["c:directives"] or engineflags["directives"]
- if type(list)=="string" then
- initialize_setter("commandline flags","directives",settings_to_hash(list))
- end
- end
-end
-if texconfig then
- local function set(k,v)
- v=tonumber(v)
- if v then
- texconfig[k]=v
- end
- end
- directives.register("luatex.expanddepth",function(v) set("expand_depth",v) end)
- directives.register("luatex.hashextra",function(v) set("hash_extra",v) end)
- directives.register("luatex.nestsize",function(v) set("nest_size",v) end)
- directives.register("luatex.maxinopen",function(v) set("max_in_open",v) end)
- directives.register("luatex.maxprintline",function(v) set("max_print_line",v) end)
- directives.register("luatex.maxstrings",function(v) set("max_strings",v) end)
- directives.register("luatex.paramsize",function(v) set("param_size",v) end)
- directives.register("luatex.savesize",function(v) set("save_size",v) end)
- directives.register("luatex.stacksize",function(v) set("stack_size",v) end)
-end
-local data=table.setmetatableindex("table")
-updaters={
- register=function(what,f)
- local d=data[what]
- d[#d+1]=f
- end,
- apply=function(what,...)
- local d=data[what]
- for i=1,#d do
- d[i](...)
- end
- end,
-}
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-log"] = package.loaded["trac-log"] or true
-
--- original size: 16017, stripped down to: 11045
-
-if not modules then modules={} end modules ['trac-log']={
- version=1.001,
- comment="companion to trac-log.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local next,type,select,print=next,type,select,print
-local format,gmatch,find=string.format,string.gmatch,string.find
-local concat,insert,remove=table.concat,table.insert,table.remove
-local topattern=string.topattern
-local utfchar=utf.char
-local datetime=os.date
-local openfile=io.open
-local write_nl=print
-local write=io.write
-local setmetatableindex=table.setmetatableindex
-local formatters=string.formatters
-local settings_to_hash=utilities.parsers.settings_to_hash
-local sortedkeys=table.sortedkeys
-local variant="default"
-logs=logs or {}
-local logs=logs
-local moreinfo=[[
-More information about ConTeXt and the tools that come with it can be found at:
-]].."\n"..[[
-maillist : ntg-context@ntg.nl / http://www.ntg.nl/mailman/listinfo/ntg-context
-webpage : http://www.pragma-ade.nl / http://tex.aanhet.net
-wiki : http://contextgarden.net
-]]
-formatters.add (
- formatters,"unichr",
- [["U+" .. format("%%05X",%s) .. " (" .. utfchar(%s) .. ")"]]
-)
-formatters.add (
- formatters,"chruni",
- [[utfchar(%s) .. " (U+" .. format("%%05X",%s) .. ")"]]
-)
-local function ignore() end
-setmetatableindex(logs,function(t,k) t[k]=ignore;return ignore end)
-local report,subreport,status,settarget,setformats,settranslations
-local direct,subdirect,writer,pushtarget,poptarget,setlogfile,settimedlog,setprocessor,setformatters,newline
-local function ansisupported(specification)
- if specification~="ansi" and specification~="ansilog" then
- return false
- elseif os and os.enableansi then
- return os.enableansi()
- else
- return false
- end
-end
-do
- local report_yes,subreport_yes,status_yes
- local report_nop,subreport_nop,status_nop
- local variants={
- default={
- formats={
- report_yes=formatters["%-15s | %s"],
- report_nop=formatters["%-15s |"],
- subreport_yes=formatters["%-15s | %s | %s"],
- subreport_nop=formatters["%-15s | %s |"],
- status_yes=formatters["%-15s : %s\n"],
- status_nop=formatters["%-15s :\n"],
- },
- },
- ansi={
- formats={
- report_yes=formatters["%-15s | %s"],
- report_nop=formatters["%-15s |"],
- subreport_yes=formatters["%-15s | %s | %s"],
- subreport_nop=formatters["%-15s | %s |"],
- status_yes=formatters["%-15s : %s\n"],
- status_nop=formatters["%-15s :\n"],
- },
- },
- }
- logs.flush=ignore
- writer=function(s)
- write_nl(s)
- end
- newline=function()
- write_nl("\n")
- end
- report=function(a,b,c,...)
- if c then
- write_nl(report_yes(a,formatters[b](c,...)))
- elseif b then
- write_nl(report_yes(a,b))
- elseif a then
- write_nl(report_nop(a))
- else
- write_nl("")
- end
- end
- subreport=function(a,sub,b,c,...)
- if c then
- write_nl(subreport_yes(a,sub,formatters[b](c,...)))
- elseif b then
- write_nl(subreport_yes(a,sub,b))
- elseif a then
- write_nl(subreport_nop(a,sub))
- else
- write_nl("")
- end
- end
- status=function(a,b,c,...)
- if c then
- write_nl(status_yes(a,formatters[b](c,...)))
- elseif b then
- write_nl(status_yes(a,b))
- elseif a then
- write_nl(status_nop(a))
- else
- write_nl("\n")
- end
- end
- direct=ignore
- subdirect=ignore
- settarget=ignore
- pushtarget=ignore
- poptarget=ignore
- setformats=ignore
- settranslations=ignore
- setprocessor=function(f)
- local writeline=write_nl
- write_nl=function(s)
- writeline(f(s))
- end
- end
- setformatters=function(specification)
- local f=nil
- local d=variants.default
- if specification then
- if type(specification)=="table" then
- f=specification.formats or specification
- else
- if not ansisupported(specification) then
- specification="default"
- end
- local v=variants[specification]
- if v then
- f=v.formats
- end
- end
- end
- if f then
- d=d.formats
- else
- f=d.formats
- d=f
- end
- setmetatableindex(f,d)
- report_yes=f.report_yes
- report_nop=f.report_nop
- subreport_yes=f.subreport_yes
- subreport_nop=f.subreport_nop
- status_yes=f.status_yes
- status_nop=f.status_nop
- end
- setformatters(variant)
- setlogfile=function(name,keepopen)
- if name and name~="" then
- local localtime=os.localtime
- local writeline=write_nl
- if keepopen then
- local f=io.open(name,"ab")
- write_nl=function(s)
- writeline(s)
- f:write(localtime()," | ",s,"\n")
- end
- else
- write_nl=function(s)
- writeline(s)
- local f=io.open(name,"ab")
- f:write(localtime()," | ",s,"\n")
- f:close()
- end
- end
- end
- setlogfile=ignore
- end
- settimedlog=function()
- local localtime=os.localtime
- local writeline=write_nl
- write_nl=function(s)
- writeline(localtime().." | "..s)
- end
- settimedlog=ignore
- end
-end
-logs.report=report
-logs.subreport=subreport
-logs.status=status
-logs.settarget=settarget
-logs.pushtarget=pushtarget
-logs.poptarget=poptarget
-logs.setformats=setformats
-logs.settranslations=settranslations
-logs.setlogfile=setlogfile
-logs.settimedlog=settimedlog
-logs.setprocessor=setprocessor
-logs.setformatters=setformatters
-logs.direct=direct
-logs.subdirect=subdirect
-logs.writer=writer
-logs.newline=newline
-local data={}
-local states=nil
-local force=false
-function logs.reporter(category,subcategory)
- local logger=data[category]
- if not logger then
- local state=states==true
- if not state and type(states)=="table" then
- for c,_ in next,states do
- if find(category,c) then
- state=true
- break
- end
- end
- end
- logger={
- reporters={},
- state=state,
- }
- data[category]=logger
- end
- local reporter=logger.reporters[subcategory or "default"]
- if not reporter then
- if subcategory then
- reporter=function(...)
- if force or not logger.state then
- subreport(category,subcategory,...)
- end
- end
- logger.reporters[subcategory]=reporter
- else
- local tag=category
- reporter=function(...)
- if force or not logger.state then
- report(category,...)
- end
- end
- logger.reporters.default=reporter
- end
- end
- return reporter
-end
-logs.new=logs.reporter
-local ctxreport=logs.writer
-function logs.setmessenger(m)
- ctxreport=m
-end
-function logs.messenger(category,subcategory)
- if subcategory then
- return function(...)
- ctxreport(subdirect(category,subcategory,...))
- end
- else
- return function(...)
- ctxreport(direct(category,...))
- end
- end
-end
-local function setblocked(category,value)
- if category==true or category=="all" then
- category,value="*",true
- elseif category==false then
- category,value="*",false
- elseif value==nil then
- value=true
- end
- if category=="*" then
- states=value
- for k,v in next,data do
- v.state=value
- end
- else
- alllocked=false
- states=settings_to_hash(category,type(states)=="table" and states or nil)
- for c in next,states do
- local v=data[c]
- if v then
- v.state=value
- else
- c=topattern(c,true,true)
- for k,v in next,data do
- if find(k,c) then
- v.state=value
- end
- end
- end
- end
- end
-end
-function logs.disable(category,value)
- setblocked(category,value==nil and true or value)
-end
-function logs.enable(category)
- setblocked(category,false)
-end
-function logs.categories()
- return sortedkeys(data)
-end
-function logs.show()
- local n,c,s,max=0,0,0,0
- for category,v in table.sortedpairs(data) do
- n=n+1
- local state=v.state
- local reporters=v.reporters
- local nc=#category
- if nc>c then
- c=nc
- end
- for subcategory,_ in next,reporters do
- local ns=#subcategory
- if ns>c then
- s=ns
- end
- local m=nc+ns
- if m>max then
- max=m
- end
- end
- local subcategories=concat(sortedkeys(reporters),", ")
- if state==true then
- state="disabled"
- elseif state==false then
- state="enabled"
- else
- state="unknown"
- end
- report("logging","category %a, subcategories %a, state %a",category,subcategories,state)
- end
- report("logging","categories: %s, max category: %s, max subcategory: %s, max combined: %s",n,c,s,max)
-end
-local delayed_reporters={}
-setmetatableindex(delayed_reporters,function(t,k)
- local v=logs.reporter(k.name)
- t[k]=v
- return v
-end)
-function utilities.setters.report(setter,...)
- delayed_reporters[setter](...)
-end
-directives.register("logs.blocked",function(v)
- setblocked(v,true)
-end)
-directives.register("logs.target",function(v)
- settarget(v)
-end)
-local nesting=0
-local verbose=false
-local hasscheme=url.hasscheme
-local simple=logs.reporter("comment")
-logs.simple=simple
-logs.simpleline=simple
-logs.setprogram=ignore
-logs.extendbanner=ignore
-logs.reportlines=ignore
-logs.reportbanner=ignore
-logs.reportline=ignore
-logs.simplelines=ignore
-logs.help=ignore
-local Carg,C,lpegmatch=lpeg.Carg,lpeg.C,lpeg.match
-local p_newline=lpeg.patterns.newline
-local linewise=(
- Carg(1)*C((1-p_newline)^1)/function(t,s) t.report(s) end+Carg(1)*p_newline^2/function(t) t.report() end+p_newline
-)^1
-local function reportlines(t,str)
- if str then
- lpegmatch(linewise,str,1,t)
- end
-end
-local function reportbanner(t)
- local banner=t.banner
- if banner then
- t.report(banner)
- t.report()
- end
-end
-local function reportversion(t)
- local banner=t.banner
- if banner then
- t.report(banner)
- end
-end
-local function reporthelp(t,...)
- local helpinfo=t.helpinfo
- if type(helpinfo)=="string" then
- reportlines(t,helpinfo)
- elseif type(helpinfo)=="table" then
- for i=1,select("#",...) do
- reportlines(t,t.helpinfo[select(i,...)])
- if i<n then
- t.report()
- end
- end
- end
-end
-local function reportinfo(t)
- t.report()
- reportlines(t,t.moreinfo)
-end
-local function reportexport(t,method)
- report(t.helpinfo)
-end
-local reporters={
- lines=reportlines,
- banner=reportbanner,
- version=reportversion,
- help=reporthelp,
- info=reportinfo,
- export=reportexport,
-}
-local exporters={
-}
-logs.reporters=reporters
-logs.exporters=exporters
-function logs.application(t)
- local arguments=environment and environment.arguments
- if arguments then
- local ansi=arguments.ansi or arguments.ansilog
- if ansi then
- logs.setformatters(arguments.ansi and "ansi" or "ansilog")
- end
- end
- t.name=t.name or "unknown"
- t.banner=t.banner
- t.moreinfo=moreinfo
- t.report=logs.reporter(t.name)
- t.help=function(...)
- reporters.banner(t)
- reporters.help(t,...)
- reporters.info(t)
- end
- t.export=function(...)
- reporters.export(t,...)
- end
- t.identify=function()
- reporters.banner(t)
- end
- t.version=function()
- reporters.version(t)
- end
- return t
-end
-local f_syslog=formatters["%s %s => %s => %s => %s\r"]
-function logs.system(whereto,process,jobname,category,fmt,arg,...)
- local message=f_syslog(datetime("%d/%m/%y %H:%m:%S"),process,jobname,category,arg==nil and fmt or format(fmt,arg,...))
- for i=1,10 do
- local f=openfile(whereto,"a")
- if f then
- f:write(message)
- f:close()
- break
- else
- sleep(0.1)
- end
- end
-end
-local report_system=logs.reporter("system","logs")
-if utilities then
- utilities.report=report_system
-end
-if package.helpers.report then
- package.helpers.report=logs.reporter("package loader")
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-inf"] = package.loaded["trac-inf"] or true
-
--- original size: 9740, stripped down to: 7296
-
-if not modules then modules={} end modules ['trac-inf']={
- version=1.001,
- comment="companion to trac-inf.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,tonumber,select=type,tonumber,select
-local format,lower,find=string.format,string.lower,string.find
-local concat=table.concat
-local clock=os.gettimeofday or os.clock
-local setmetatableindex=table.setmetatableindex
-local serialize=table.serialize
-local formatters=string.formatters
-statistics=statistics or {}
-local statistics=statistics
-statistics.enable=true
-statistics.threshold=0.01
-local statusinfo,n,registered,timers={},0,{},{}
-setmetatableindex(timers,function(t,k)
- local v={ timing=0,loadtime=0,offset=0 }
- t[k]=v
- return v
-end)
-local function hastiming(instance)
- return instance and timers[instance]
-end
-local function resettiming(instance)
- timers[instance or "notimer"]={ timing=0,loadtime=0,offset=0 }
-end
-local ticks=clock
-local seconds=function(n) return n or 0 end
-if os.type~="windows" then
-elseif lua.getpreciseticks then
- ticks=lua.getpreciseticks
- seconds=lua.getpreciseseconds
-elseif FFISUPPORTED then
- local okay,kernel=pcall(ffi.load,"kernel32")
- if kernel then
- local tonumber=ffi.number or tonumber
- ffi.cdef[[
- int QueryPerformanceFrequency(int64_t *lpFrequency);
- int QueryPerformanceCounter(int64_t *lpPerformanceCount);
- ]]
- local target=ffi.new("__int64[1]")
- ticks=function()
- if kernel.QueryPerformanceCounter(target)==1 then
- return tonumber(target[0])
- else
- return 0
- end
- end
- local target=ffi.new("__int64[1]")
- seconds=function(ticks)
- if kernel.QueryPerformanceFrequency(target)==1 then
- return ticks/tonumber(target[0])
- else
- return 0
- end
- end
- end
-else
-end
-local function starttiming(instance,reset)
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if reset then
- it=0
- timer.loadtime=0
- end
- if it==0 then
- timer.starttime=ticks()
- if not timer.loadtime then
- timer.loadtime=0
- end
- end
- timer.timing=it+1
-end
-local function stoptiming(instance)
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if it>1 then
- timer.timing=it-1
- else
- local starttime=timer.starttime
- if starttime and starttime>0 then
- local stoptime=ticks()
- local loadtime=stoptime-starttime
- timer.stoptime=stoptime
- timer.loadtime=timer.loadtime+loadtime
- timer.timing=0
- timer.starttime=0
- end
- end
-end
-local function benchmarktimer(instance)
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if it>1 then
- timer.timing=it-1
- else
- local starttime=timer.starttime
- if starttime and starttime>0 then
- timer.offset=ticks()-starttime
- else
- timer.offset=0
- end
- end
-end
-local function elapsed(instance)
- if type(instance)=="number" then
- return instance
- else
- local timer=timers[instance or "notimer"]
- return timer and seconds(timer.loadtime-2*(timer.offset or 0)) or 0
- end
-end
-local function currenttime(instance)
- if type(instance)=="number" then
- return instance
- else
- local timer=timers[instance or "notimer"]
- local it=timer.timing
- if it>1 then
- else
- local starttime=timer.starttime
- if starttime and starttime>0 then
- return seconds(timer.loadtime+ticks()-starttime-2*(timer.offset or 0))
- end
- end
- return 0
- end
-end
-local function elapsedtime(instance)
- return format("%0.3f",elapsed(instance))
-end
-local function elapsedindeed(instance)
- return elapsed(instance)>statistics.threshold
-end
-local function elapsedseconds(instance,rest)
- if elapsedindeed(instance) then
- return format("%0.3f seconds %s",elapsed(instance),rest or "")
- end
-end
-statistics.hastiming=hastiming
-statistics.resettiming=resettiming
-statistics.starttiming=starttiming
-statistics.stoptiming=stoptiming
-statistics.currenttime=currenttime
-statistics.elapsed=elapsed
-statistics.elapsedtime=elapsedtime
-statistics.elapsedindeed=elapsedindeed
-statistics.elapsedseconds=elapsedseconds
-statistics.benchmarktimer=benchmarktimer
-function statistics.register(tag,fnc)
- if statistics.enable and type(fnc)=="function" then
- local rt=registered[tag] or (#statusinfo+1)
- statusinfo[rt]={ tag,fnc }
- registered[tag]=rt
- if #tag>n then n=#tag end
- end
-end
-local report=logs.reporter("mkiv lua stats")
-function statistics.show()
- if statistics.enable then
- local register=statistics.register
- register("used platform",function()
- return format("%s, type: %s, binary subtree: %s",
- os.platform or "unknown",os.type or "unknown",environment.texos or "unknown")
- end)
- register("used engine",function()
- return format("%s version: %s, functionality level: %s, banner: %s",
- LUATEXENGINE,LUATEXVERSION,LUATEXFUNCTIONALITY,lower(status.banner))
- end)
- register("used hash slots",function()
- return format("%s of %s + %s",status.cs_count,status.hash_size,status.hash_extra)
- end)
- register("callbacks",statistics.callbacks)
- if JITSUPPORTED then
- local jitstatus=jit.status
- if jitstatus then
- local jitstatus={ jitstatus() }
- if jitstatus[1] then
- register("luajit options",concat(jitstatus," ",2))
- end
- end
- end
- register("lua properties",function()
- local hash=2^status.luatex_hashchars
- local mask=load([[τεχ = 1]]) and "utf" or "ascii"
- return format("engine: %s %s, used memory: %s, hash chars: min(%i,40), symbol mask: %s (%s)",
- jit and "luajit" or "lua",LUAVERSION,statistics.memused(),hash,mask,mask=="utf" and "τεχ" or "tex")
- end)
- register("runtime",statistics.runtime)
- logs.newline()
- for i=1,#statusinfo do
- local s=statusinfo[i]
- local r=s[2]()
- if r then
- report("%s: %s",s[1],r)
- end
- end
- statistics.enable=false
- end
-end
-function statistics.memused()
- local round=math.round or math.floor
- return format("%s MB, ctx: %s MB, max: %s MB",
- round(collectgarbage("count")/1000),
- round(status.luastate_bytes/1000000),
- status.luastate_bytes_max and round(status.luastate_bytes_max/1000000) or "unknown"
- )
-end
-starttiming(statistics)
-function statistics.formatruntime(runtime)
- return format("%s seconds",runtime)
-end
-function statistics.runtime()
- stoptiming(statistics)
- local runtime=lua.getruntime and lua.getruntime() or elapsedtime(statistics)
- return statistics.formatruntime(runtime)
-end
-local report=logs.reporter("system")
-function statistics.timed(action,all)
- starttiming("run")
- action()
- stoptiming("run")
- local runtime=tonumber(elapsedtime("run"))
- if all then
- local alltime=tonumber(lua.getruntime and lua.getruntime() or elapsedtime(statistics))
- if alltime and alltime>0 then
- report("total runtime: %0.3f seconds of %0.3f seconds",runtime,alltime)
- return
- end
- end
- report("total runtime: %0.3f seconds",runtime)
-end
-function statistics.tracefunction(base,tag,...)
- for i=1,select("#",...) do
- local name=select(i,...)
- local stat={}
- local func=base[name]
- setmetatableindex(stat,function(t,k) t[k]=0 return 0 end)
- base[name]=function(n,k,v) stat[k]=stat[k]+1 return func(n,k,v) end
- statistics.register(formatters["%s.%s"](tag,name),function() return serialize(stat,"calls") end)
- end
-end
-function status.getreadstate()
- return {
- filename=status.filename or "?",
- linenumber=status.linenumber or 0,
- iocode=status.inputid or 0,
- }
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-pro"] = package.loaded["trac-pro"] or true
-
--- original size: 5841, stripped down to: 3352
-
-if not modules then modules={} end modules ['trac-pro']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local getmetatable,setmetatable,rawset,type,next=getmetatable,setmetatable,rawset,type,next
-local trace_namespaces=false trackers.register("system.namespaces",function(v) trace_namespaces=v end)
-local report_system=logs.reporter("system","protection")
-namespaces=namespaces or {}
-local namespaces=namespaces
-local registered={}
-local function report_index(k,name)
- if trace_namespaces then
- report_system("reference to %a in protected namespace %a: %s",k,name)
- debugger.showtraceback(report_system)
- else
- report_system("reference to %a in protected namespace %a",k,name)
- end
-end
-local function report_newindex(k,name)
- if trace_namespaces then
- report_system("assignment to %a in protected namespace %a: %s",k,name)
- debugger.showtraceback(report_system)
- else
- report_system("assignment to %a in protected namespace %a",k,name)
- end
-end
-local function register(name)
- local data=name=="global" and _G or _G[name]
- if not data then
- return
- end
- registered[name]=data
- local m=getmetatable(data)
- if not m then
- m={}
- setmetatable(data,m)
- end
- local index,newindex={},{}
- m.__saved__index=m.__index
- m.__no__index=function(t,k)
- if not index[k] then
- index[k]=true
- report_index(k,name)
- end
- return nil
- end
- m.__saved__newindex=m.__newindex
- m.__no__newindex=function(t,k,v)
- if not newindex[k] then
- newindex[k]=true
- report_newindex(k,name)
- end
- rawset(t,k,v)
- end
- m.__protection__depth=0
-end
-local function private(name)
- local data=registered[name]
- if not data then
- data=_G[name]
- if not data then
- data={}
- _G[name]=data
- end
- register(name)
- end
- return data
-end
-local function protect(name)
- local data=registered[name]
- if not data then
- return
- end
- local m=getmetatable(data)
- local pd=m.__protection__depth
- if pd>0 then
- m.__protection__depth=pd+1
- else
- m.__save_d_index,m.__saved__newindex=m.__index,m.__newindex
- m.__index,m.__newindex=m.__no__index,m.__no__newindex
- m.__protection__depth=1
- end
-end
-local function unprotect(name)
- local data=registered[name]
- if not data then
- return
- end
- local m=getmetatable(data)
- local pd=m.__protection__depth
- if pd>1 then
- m.__protection__depth=pd-1
- else
- m.__index,m.__newindex=m.__saved__index,m.__saved__newindex
- m.__protection__depth=0
- end
-end
-local function protectall()
- for name,_ in next,registered do
- if name~="global" then
- protect(name)
- end
- end
-end
-local function unprotectall()
- for name,_ in next,registered do
- if name~="global" then
- unprotect(name)
- end
- end
-end
-namespaces.register=register
-namespaces.private=private
-namespaces.protect=protect
-namespaces.unprotect=unprotect
-namespaces.protectall=protectall
-namespaces.unprotectall=unprotectall
-namespaces.private("namespaces") registered={} register("global")
-directives.register("system.protect",function(v)
- if v then
- protectall()
- else
- unprotectall()
- end
-end)
-directives.register("system.checkglobals",function(v)
- if v then
- report_system("enabling global namespace guard")
- protect("global")
- else
- report_system("disabling global namespace guard")
- unprotect("global")
- end
-end)
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-lua"] = package.loaded["util-lua"] or true
-
--- original size: 7149, stripped down to: 4997
-
-if not modules then modules={} end modules ['util-lua']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- comment="the strip code is written by Peter Cawley",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local rep,sub,byte,dump,format=string.rep,string.sub,string.byte,string.dump,string.format
-local load,loadfile,type,collectgarbage=load,loadfile,type,collectgarbage
-utilities=utilities or {}
-utilities.lua=utilities.lua or {}
-local luautilities=utilities.lua
-local report_lua=logs.reporter("system","lua")
-local report_mem=logs.reporter("system","lua memory")
-local tracestripping=false
-local tracememory=false
-luautilities.stripcode=true
-luautilities.alwaysstripcode=false
-luautilities.nofstrippedchunks=0
-luautilities.nofstrippedbytes=0
-local strippedchunks={}
-luautilities.strippedchunks=strippedchunks
-if not LUATEXENGINE then
- LUATEXENGINE=status.luatex_engine and string.lower(status.luatex_engine)
- JITSUPPORTED=LUATEXENGINE=="luajittex" or jit
- CONTEXTLMTXMODE=CONTEXTLMTXMODE or (LUATEXENGINE=="luametatex" and 1) or 0
-end
-luautilities.suffixes={
- tma="tma",
- tmc=(CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and "tmd") or (jit and "tmb") or "tmc",
- lua="lua",
- luc=(CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and "lud") or (jit and "lub") or "luc",
- lui="lui",
- luv="luv",
- luj="luj",
- tua="tua",
- tuc=(CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and "tud") or (jit and "tub") or "tuc",
-}
-local function register(name)
- if tracestripping then
- report_lua("stripped bytecode from %a",name or "unknown")
- end
- strippedchunks[#strippedchunks+1]=name
- luautilities.nofstrippedchunks=luautilities.nofstrippedchunks+1
-end
-local function stupidcompile(luafile,lucfile,strip)
- local code=io.loaddata(luafile)
- if code and code~="" then
- code=load(code)
- if code then
- code=dump(code,strip and luautilities.stripcode or luautilities.alwaysstripcode)
- if code and code~="" then
- register(name)
- io.savedata(lucfile,code)
- return true,0
- end
- else
- report_lua("fatal error %a in file %a",1,luafile)
- end
- else
- report_lua("fatal error %a in file %a",2,luafile)
- end
- return false,0
-end
-function luautilities.loadedluacode(fullname,forcestrip,name,macros)
- name=name or fullname
- if macros then
- macros=lua.macros
- end
- local code,message
- if macros then
- code,message=macros.loaded(fullname,true,false)
- else
- code,message=loadfile(fullname)
- end
- if code then
- code()
- else
- report_lua("loading of file %a failed:\n\t%s",fullname,message or "no message")
- code,message=loadfile(fullname)
- end
- if forcestrip and luautilities.stripcode then
- if type(forcestrip)=="function" then
- forcestrip=forcestrip(fullname)
- end
- if forcestrip or luautilities.alwaysstripcode then
- register(name)
- return load(dump(code,true)),0
- else
- return code,0
- end
- elseif luautilities.alwaysstripcode then
- register(name)
- return load(dump(code,true)),0
- else
- return code,0
- end
-end
-function luautilities.strippedloadstring(code,name,forcestrip)
- local code,message=load(code)
- if not code then
- report_lua("loading of file %a failed:\n\t%s",name,message or "no message")
- end
- if forcestrip and luautilities.stripcode or luautilities.alwaysstripcode then
- register(name)
- return load(dump(code,true)),0
- else
- return code,0
- end
-end
-function luautilities.loadstring(code,name)
- local code,message=load(code)
- if not code then
- report_lua("loading of file %a failed:\n\t%s",name,message or "no message")
- end
- return code,0
-end
-function luautilities.compile(luafile,lucfile,cleanup,strip,fallback)
- report_lua("compiling %a into %a",luafile,lucfile)
- os.remove(lucfile)
- local done=stupidcompile(luafile,lucfile,strip~=false)
- if done then
- report_lua("dumping %a into %a stripped",luafile,lucfile)
- if cleanup==true and lfs.isfile(lucfile) and lfs.isfile(luafile) then
- report_lua("removing %a",luafile)
- os.remove(luafile)
- end
- end
- return done
-end
-function luautilities.loadstripped(...)
- local l=load(...)
- if l then
- return load(dump(l,true))
- end
-end
-local finalizers={}
-setmetatable(finalizers,{
- __gc=function(t)
- for i=1,#t do
- pcall(t[i])
- end
- end
-} )
-function luautilities.registerfinalizer(f)
- finalizers[#finalizers+1]=f
-end
-function luautilities.checkmemory(previous,threshold,trace)
- local current=collectgarbage("count")
- if previous then
- local checked=(threshold or 64)*1024
- local delta=current-previous
- if current-previous>checked then
- collectgarbage("collect")
- local afterwards=collectgarbage("count")
- if trace or tracememory then
- report_mem("previous %r MB, current %r MB, delta %r MB, threshold %r MB, afterwards %r MB",
- previous/1024,current/1024,delta/1024,threshold,afterwards)
- end
- return afterwards
- elseif trace or tracememory then
- report_mem("previous %r MB, current %r MB, delta %r MB, threshold %r MB",
- previous/1024,current/1024,delta/1024,threshold)
- end
- end
- return current
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-deb"] = package.loaded["util-deb"] or true
-
--- original size: 10136, stripped down to: 6832
-
-if not modules then modules={} end modules ['util-deb']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,next,tostring,tonumber=type,next,tostring,tonumber
-local format,find,sub,gsub=string.format,string.find,string.sub,string.gsub
-local insert,remove,sort=table.insert,table.remove,table.sort
-local setmetatableindex=table.setmetatableindex
-utilities=utilities or {}
-local debugger=utilities.debugger or {}
-utilities.debugger=debugger
-local report=logs.reporter("debugger")
-local ticks=os.gettimeofday or os.clock
-local seconds=function(n) return n or 0 end
-local overhead=0
-local dummycalls=10*1000
-local nesting=0
-local names={}
-local initialize=false
-if lua.getpreciseticks then
- initialize=function()
- ticks=lua.getpreciseticks
- seconds=lua.getpreciseseconds
- initialize=false
- end
-elseif not (FFISUPPORTED and ffi) then
-elseif os.type=="windows" then
- initialize=function()
- local kernel=ffilib("kernel32","system")
- if kernel then
- local tonumber=ffi.number or tonumber
- ffi.cdef[[
- int QueryPerformanceFrequency(int64_t *lpFrequency);
- int QueryPerformanceCounter(int64_t *lpPerformanceCount);
- ]]
- local target=ffi.new("__int64[1]")
- ticks=function()
- if kernel.QueryPerformanceCounter(target)==1 then
- return tonumber(target[0])
- else
- return 0
- end
- end
- local target=ffi.new("__int64[1]")
- seconds=function(ticks)
- if kernel.QueryPerformanceFrequency(target)==1 then
- return ticks/tonumber(target[0])
- else
- return 0
- end
- end
- end
- initialize=false
- end
-elseif os.type=="unix" then
- initialize=function()
- local C=ffi.C
- local tonumber=ffi.number or tonumber
- ffi.cdef [[
- /* what a mess */
- typedef int clk_id_t;
- typedef enum { CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID } clk_id;
- typedef struct timespec { long sec; long nsec; } ctx_timespec;
- int clock_gettime(clk_id_t timerid, struct timespec *t);
- ]]
- local target=ffi.new("ctx_timespec[?]",1)
- local clock=C.CLOCK_PROCESS_CPUTIME_ID
- ticks=function ()
- C.clock_gettime(clock,target)
- return tonumber(target[0].sec*1000000000+target[0].nsec)
- end
- seconds=function(ticks)
- return ticks/1000000000
- end
- initialize=false
- end
-end
-setmetatableindex(names,function(t,name)
- local v=setmetatableindex(function(t,source)
- local v=setmetatableindex(function(t,line)
- local v={ total=0,count=0,nesting=0 }
- t[line]=v
- return v
- end)
- t[source]=v
- return v
- end)
- t[name]=v
- return v
-end)
-local getinfo=nil
-local sethook=nil
-local function hook(where)
- local f=getinfo(2,"nSl")
- if f then
- local source=f.short_src
- if not source then
- return
- end
- local line=f.linedefined or 0
- local name=f.name
- if not name then
- local what=f.what
- if what=="C" then
- name="<anonymous>"
- else
- name=f.namewhat or what or "<unknown>"
- end
- end
- local data=names[name][source][line]
- if where=="call" then
- local nesting=data.nesting
- if nesting==0 then
- data.count=data.count+1
- insert(data,ticks())
- data.nesting=1
- else
- data.nesting=nesting+1
- end
- elseif where=="return" then
- local nesting=data.nesting
- if nesting==1 then
- local t=remove(data)
- if t then
- data.total=data.total+ticks()-t
- end
- data.nesting=0
- else
- data.nesting=nesting-1
- end
- end
- end
-end
-function debugger.showstats(printer,threshold)
- local printer=printer or report
- local calls=0
- local functions=0
- local dataset={}
- local length=0
- local realtime=0
- local totaltime=0
- local threshold=threshold or 0
- for name,sources in next,names do
- for source,lines in next,sources do
- for line,data in next,lines do
- local count=data.count
- if count>threshold then
- if #name>length then
- length=#name
- end
- local total=data.total
- local real=total
- if real>0 then
- real=total-(count*overhead/dummycalls)
- if real<0 then
- real=0
- end
- realtime=realtime+real
- end
- totaltime=totaltime+total
- if line<0 then
- line=0
- end
- dataset[#dataset+1]={ real,total,count,name,source,line }
- end
- end
- end
- end
- sort(dataset,function(a,b)
- if a[1]==b[1] then
- if a[2]==b[2] then
- if a[3]==b[3] then
- if a[4]==b[4] then
- if a[5]==b[5] then
- return a[6]<b[6]
- else
- return a[5]<b[5]
- end
- else
- return a[4]<b[4]
- end
- else
- return b[3]<a[3]
- end
- else
- return b[2]<a[2]
- end
- else
- return b[1]<a[1]
- end
- end)
- if length>50 then
- length=50
- end
- local fmt=string.formatters["%4.9k s %3.3k %% %4.9k s %3.3k %% %8i # %-"..length.."s %4i %s"]
- for i=1,#dataset do
- local data=dataset[i]
- local real=data[1]
- local total=data[2]
- local count=data[3]
- local name=data[4]
- local source=data[5]
- local line=data[6]
- calls=calls+count
- functions=functions+1
- name=gsub(name,"%s+"," ")
- if #name>length then
- name=sub(name,1,length)
- end
- printer(fmt(seconds(total),100*total/totaltime,seconds(real),100*real/realtime,count,name,line,source))
- end
- printer("")
- printer(format("functions : %i",functions))
- printer(format("calls : %i",calls))
- printer(format("overhead : %f",seconds(overhead/1000)))
-end
-local function getdebug()
- if sethook and getinfo then
- return
- end
- if not debug then
- local okay
- okay,debug=pcall(require,"debug")
- end
- if type(debug)~="table" then
- return
- end
- getinfo=debug.getinfo
- sethook=debug.sethook
- if type(getinfo)~="function" then
- getinfo=nil
- end
- if type(sethook)~="function" then
- sethook=nil
- end
-end
-function debugger.savestats(filename,threshold)
- local f=io.open(filename,'w')
- if f then
- debugger.showstats(function(str) f:write(str,"\n") end,threshold)
- f:close()
- end
-end
-function debugger.enable()
- getdebug()
- if sethook and getinfo and nesting==0 then
- running=true
- if initialize then
- initialize()
- end
- sethook(hook,"cr")
- local function dummy() end
- local t=ticks()
- for i=1,dummycalls do
- dummy()
- end
- overhead=ticks()-t
- end
- if nesting>0 then
- nesting=nesting+1
- end
-end
-function debugger.disable()
- if nesting>0 then
- nesting=nesting-1
- end
- if sethook and getinfo and nesting==0 then
- sethook()
- end
-end
-local function showtraceback(rep)
- getdebug()
- if getinfo then
- local level=2
- local reporter=rep or report
- while true do
- local info=getinfo(level,"Sl")
- if not info then
- break
- elseif info.what=="C" then
- reporter("%2i : %s",level-1,"C function")
- else
- reporter("%2i : %s : %s",level-1,info.short_src,info.currentline)
- end
- level=level+1
- end
- end
-end
-debugger.showtraceback=showtraceback
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-tpl"] = package.loaded["util-tpl"] or true
-
--- original size: 7722, stripped down to: 4212
-
-if not modules then modules={} end modules ['util-tpl']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-utilities.templates=utilities.templates or {}
-local templates=utilities.templates
-local trace_template=false trackers.register("templates.trace",function(v) trace_template=v end)
-local report_template=logs.reporter("template")
-local tostring,next=tostring,next
-local format,sub,byte=string.format,string.sub,string.byte
-local P,C,R,Cs,Cc,Carg,lpegmatch,lpegpatterns=lpeg.P,lpeg.C,lpeg.R,lpeg.Cs,lpeg.Cc,lpeg.Carg,lpeg.match,lpeg.patterns
-local formatters=string.formatters
-local replacer
-local function replacekey(k,t,how,recursive)
- local v=t[k]
- if not v then
- if trace_template then
- report_template("unknown key %a",k)
- end
- return ""
- else
- v=tostring(v)
- if trace_template then
- report_template("setting key %a to value %a",k,v)
- end
- if recursive then
- return lpegmatch(replacer,v,1,t,how,recursive)
- else
- return v
- end
- end
-end
-local sqlescape=lpeg.replacer {
- { "'","''" },
- { "\\","\\\\" },
- { "\r\n","\\n" },
- { "\r","\\n" },
-}
-local sqlquoted=Cs(Cc("'")*sqlescape*Cc("'"))
-lpegpatterns.sqlescape=sqlescape
-lpegpatterns.sqlquoted=sqlquoted
-local luaescape=lpegpatterns.luaescape
-local escapers={
- lua=function(s)
- return lpegmatch(luaescape,s)
- end,
- sql=function(s)
- return lpegmatch(sqlescape,s)
- end,
-}
-local quotedescapers={
- lua=function(s)
- return format("%q",s)
- end,
- sql=function(s)
- return lpegmatch(sqlquoted,s)
- end,
-}
-local luaescaper=escapers.lua
-local quotedluaescaper=quotedescapers.lua
-local function replacekeyunquoted(s,t,how,recurse)
- if how==false then
- return replacekey(s,t,how,recurse)
- else
- local escaper=how and escapers[how] or luaescaper
- return escaper(replacekey(s,t,how,recurse))
- end
-end
-local function replacekeyquoted(s,t,how,recurse)
- if how==false then
- return replacekey(s,t,how,recurse)
- else
- local escaper=how and quotedescapers[how] or quotedluaescaper
- return escaper(replacekey(s,t,how,recurse))
- end
-end
-local function replaceoptional(l,m,r,t,how,recurse)
- local v=t[l]
- return v and v~="" and lpegmatch(replacer,r,1,t,how or "lua",recurse or false) or ""
-end
-local function replaceformatted(l,m,r,t,how,recurse)
- local v=t[r]
- return v and formatters[l](v)
-end
-local single=P("%")
-local double=P("%%")
-local lquoted=P("%[")
-local rquoted=P("]%")
-local lquotedq=P("%(")
-local rquotedq=P(")%")
-local escape=double/'%%'
-local nosingle=single/''
-local nodouble=double/''
-local nolquoted=lquoted/''
-local norquoted=rquoted/''
-local nolquotedq=lquotedq/''
-local norquotedq=rquotedq/''
-local nolformatted=P(":")/"%%"
-local norformatted=P(":")/""
-local noloptional=P("%?")/''
-local noroptional=P("?%")/''
-local nomoptional=P(":")/''
-local args=Carg(1)*Carg(2)*Carg(3)
-local key=nosingle*((C((1-nosingle)^1)*args)/replacekey)*nosingle
-local quoted=nolquotedq*((C((1-norquotedq)^1)*args)/replacekeyquoted)*norquotedq
-local unquoted=nolquoted*((C((1-norquoted)^1)*args)/replacekeyunquoted)*norquoted
-local optional=noloptional*((C((1-nomoptional)^1)*nomoptional*C((1-noroptional)^1)*args)/replaceoptional)*noroptional
-local formatted=nosingle*((Cs(nolformatted*(1-norformatted )^1)*norformatted*C((1-nosingle)^1)*args)/replaceformatted)*nosingle
-local any=P(1)
- replacer=Cs((unquoted+quoted+formatted+escape+optional+key+any)^0)
-local function replace(str,mapping,how,recurse)
- if mapping and str then
- return lpegmatch(replacer,str,1,mapping,how or "lua",recurse or false) or str
- else
- return str
- end
-end
-templates.replace=replace
-function templates.replacer(str,how,recurse)
- return function(mapping)
- return lpegmatch(replacer,str,1,mapping,how or "lua",recurse or false) or str
- end
-end
-function templates.load(filename,mapping,how,recurse)
- local data=io.loaddata(filename) or ""
- if mapping and next(mapping) then
- return replace(data,mapping,how,recurse)
- else
- return data
- end
-end
-function templates.resolve(t,mapping,how,recurse)
- if not mapping then
- mapping=t
- end
- for k,v in next,t do
- t[k]=replace(v,mapping,how,recurse)
- end
- return t
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-sbx"] = package.loaded["util-sbx"] or true
-
--- original size: 21084, stripped down to: 13214
-
-if not modules then modules={} end modules ['util-sbx']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-if not sandbox then require("l-sandbox") end
-local next,type=next,type
-local replace=utilities.templates.replace
-local collapsepath=file.collapsepath
-local expandname=dir.expandname
-local sortedhash=table.sortedhash
-local lpegmatch=lpeg.match
-local platform=os.type
-local P,S,C=lpeg.P,lpeg.S,lpeg.C
-local gsub=string.gsub
-local lower=string.lower
-local find=string.find
-local concat=string.concat
-local unquoted=string.unquoted
-local optionalquoted=string.optionalquoted
-local basename=file.basename
-local nameonly=file.nameonly
-local sandbox=sandbox
-local validroots={}
-local validrunners={}
-local validbinaries=true
-local validlibraries=true
-local validators={}
-local finalized=nil
-local trace=false
-local p_validroot=nil
-local p_split=lpeg.firstofsplit(" ")
-local report=logs.reporter("sandbox")
-trackers.register("sandbox",function(v) trace=v end)
-sandbox.setreporter(report)
-sandbox.finalizer {
- category="files",
- action=function()
- finalized=true
- end
-}
-local function registerroot(root,what)
- if finalized then
- report("roots are already finalized")
- else
- if type(root)=="table" then
- root,what=root[1],root[2]
- end
- if type(root)=="string" and root~="" then
- root=collapsepath(expandname(root))
- if what=="r" or what=="ro" or what=="readable" then
- what="read"
- elseif what=="w" or what=="wo" or what=="writable" then
- what="write"
- end
- validroots[root]=what=="write" or false
- end
- end
-end
-sandbox.finalizer {
- category="files",
- action=function()
- if p_validroot then
- report("roots are already initialized")
- else
- sandbox.registerroot(".","write")
- for name in sortedhash(validroots) do
- if p_validroot then
- p_validroot=P(name)+p_validroot
- else
- p_validroot=P(name)
- end
- end
- p_validroot=p_validroot/validroots
- end
- end
-}
-local function registerbinary(name)
- if finalized then
- report("binaries are already finalized")
- elseif type(name)=="string" and name~="" then
- if not validbinaries then
- return
- end
- if validbinaries==true then
- validbinaries={ [name]=true }
- else
- validbinaries[name]=true
- end
- elseif name==true then
- validbinaries={}
- end
-end
-local function registerlibrary(name)
- if finalized then
- report("libraries are already finalized")
- elseif type(name)=="string" and name~="" then
- if not validlibraries then
- return
- end
- if validlibraries==true then
- validlibraries={ [nameonly(name)]=true }
- else
- validlibraries[nameonly(name)]=true
- end
- elseif name==true then
- validlibraries={}
- end
-end
-local p_write=S("wa") p_write=(1-p_write)^0*p_write
-local p_path=S("\\/~$%:") p_path=(1-p_path )^0*p_path
-local function normalized(name)
- if platform=="windows" then
- name=gsub(name,"/","\\")
- end
- return name
-end
-function sandbox.possiblepath(name)
- return lpegmatch(p_path,name) and true or false
-end
-local filenamelogger=false
-function sandbox.setfilenamelogger(l)
- filenamelogger=type(l)=="function" and l or false
-end
-local function validfilename(name,what)
- if p_validroot and type(name)=="string" and lpegmatch(p_path,name) then
- local asked=collapsepath(expandname(name))
- local okay=lpegmatch(p_validroot,asked)
- if okay==true then
- if filenamelogger then
- filenamelogger(name,"w",asked,true)
- end
- return name
- elseif okay==false then
- if not what then
- if filenamelogger then
- filenamelogger(name,"r",asked,true)
- end
- return name
- elseif lpegmatch(p_write,what) then
- if filenamelogger then
- filenamelogger(name,"w",asked,false)
- end
- return
- else
- if filenamelogger then
- filenamelogger(name,"r",asked,true)
- end
- return name
- end
- elseif filenamelogger then
- filenamelogger(name,"*",name,false)
- end
- else
- return name
- end
-end
-local function readable(name,finalized)
- return validfilename(name,"r")
-end
-local function normalizedreadable(name,finalized)
- local valid=validfilename(name,"r")
- if valid then
- return normalized(valid)
- end
-end
-local function writeable(name,finalized)
- return validfilename(name,"w")
-end
-local function normalizedwriteable(name,finalized)
- local valid=validfilename(name,"w")
- if valid then
- return normalized(valid)
- end
-end
-validators.readable=readable
-validators.writeable=normalizedwriteable
-validators.normalizedreadable=normalizedreadable
-validators.normalizedwriteable=writeable
-validators.filename=readable
-table.setmetatableindex(validators,function(t,k)
- if k then
- t[k]=readable
- end
- return readable
-end)
-function validators.string(s,finalized)
- if finalized and suspicious(s) then
- return ""
- else
- return s
- end
-end
-function validators.cache(s)
- if finalized then
- return basename(s)
- else
- return s
- end
-end
-function validators.url(s)
- if finalized and find("^file:") then
- return ""
- else
- return s
- end
-end
-local function filehandlerone(action,one,...)
- local checkedone=validfilename(one)
- if checkedone then
- return action(one,...)
- else
- end
-end
-local function filehandlertwo(action,one,two,...)
- local checkedone=validfilename(one)
- if checkedone then
- local checkedtwo=validfilename(two)
- if checkedtwo then
- return action(one,two,...)
- else
- end
- else
- end
-end
-local function iohandler(action,one,...)
- if type(one)=="string" then
- local checkedone=validfilename(one)
- if checkedone then
- return action(one,...)
- end
- elseif one then
- return action(one,...)
- else
- return action()
- end
-end
-local osexecute=sandbox.original(os.execute)
-local iopopen=sandbox.original(io.popen)
-local reported={}
-local function validcommand(name,program,template,checkers,defaults,variables,reporter,strict)
- if validbinaries~=false and (validbinaries==true or validbinaries[program]) then
- local binpath=nil
- if variables then
- for variable,value in next,variables do
- local chktype=checkers[variable]
- if chktype=="verbose" then
- else
- local checker=validators[chktype]
- if checker then
- value=checker(unquoted(value),strict)
- if value then
- variables[variable]=optionalquoted(value)
- else
- report("variable %a with value %a fails the check",variable,value)
- return
- end
- else
- report("variable %a has no checker",variable)
- return
- end
- end
- end
- for variable,default in next,defaults do
- local value=variables[variable]
- if not value or value=="" then
- local chktype=checkers[variable]
- if chktype=="verbose" then
- else
- local checker=validators[chktype]
- if checker then
- default=checker(unquoted(default),strict)
- if default then
- variables[variable]=optionalquoted(default)
- else
- report("variable %a with default %a fails the check",variable,default)
- return
- end
- end
- end
- end
- end
- binpath=variables.binarypath
- end
- if type(binpath)=="string" and binpath~="" then
- program=binpath.."/"..program
- end
- local command=program.." "..replace(template,variables)
- if reporter then
- reporter("executing runner %a: %s",name,command)
- elseif trace then
- report("executing runner %a: %s",name,command)
- end
- return command
- elseif not reported[name] then
- report("executing program %a of runner %a is not permitted",program,name)
- reported[name]=true
- end
-end
-local runners={
- resultof=function(...)
- local command=validcommand(...)
- if command then
- if trace then
- report("resultof: %s",command)
- end
- local handle=iopopen(command,"r")
- if handle then
- local result=handle:read("*all") or ""
- handle:close()
- return result
- end
- end
- end,
- execute=function(...)
- local command=validcommand(...)
- if command then
- if trace then
- report("execute: %s",command)
- end
- local okay=osexecute(command)
- return okay
- end
- end,
- pipeto=function(...)
- local command=validcommand(...)
- if command then
- if trace then
- report("pipeto: %s",command)
- end
- return iopopen(command,"w")
- end
- end,
-}
-function sandbox.registerrunner(specification)
- if type(specification)=="string" then
- local wrapped=validrunners[specification]
- inspect(table.sortedkeys(validrunners))
- if wrapped then
- return wrapped
- else
- report("unknown predefined runner %a",specification)
- return
- end
- end
- if type(specification)~="table" then
- report("specification should be a table (or string)")
- return
- end
- local name=specification.name
- if type(name)~="string" then
- report("invalid name, string expected",name)
- return
- end
- if validrunners[name] then
- report("invalid name, runner %a already defined",name)
- return
- end
- local program=specification.program
- if type(program)=="string" then
- elseif type(program)=="table" then
- program=program[platform] or program.default or program.unix
- end
- if type(program)~="string" or program=="" then
- report("invalid runner %a specified for platform %a",name,platform)
- return
- end
- local template=specification.template
- if not template then
- report("missing template for runner %a",name)
- return
- end
- local method=specification.method or "execute"
- local checkers=specification.checkers or {}
- local defaults=specification.defaults or {}
- local runner=runners[method]
- if runner then
- local finalized=finalized
- local wrapped=function(variables)
- return runner(name,program,template,checkers,defaults,variables,specification.reporter,finalized)
- end
- validrunners[name]=wrapped
- return wrapped
- else
- validrunners[name]=nil
- report("invalid method for runner %a",name)
- end
-end
-function sandbox.getrunner(name)
- return name and validrunners[name]
-end
-local function suspicious(str)
- return (find(str,"[/\\]") or find(command,"..",1,true)) and true or false
-end
-local function binaryrunner(action,command,...)
- if validbinaries==false then
- report("no binaries permitted, ignoring command: %s",command)
- return
- end
- if type(command)~="string" then
- report("command should be a string")
- return
- end
- local program=lpegmatch(p_split,command)
- if not program or program=="" then
- report("unable to filter binary from command: %s",command)
- return
- end
- if validbinaries==true then
- elseif not validbinaries[program] then
- report("binary not permitted, ignoring command: %s",command)
- return
- elseif suspicious(command) then
- report("/ \\ or .. found, ignoring command (use sandbox.registerrunner): %s",command)
- return
- end
- return action(command,...)
-end
-local function dummyrunner(action,command,...)
- if type(command)=="table" then
- command=concat(command," ",command[0] and 0 or 1)
- end
- report("ignoring command: %s",command)
-end
-sandbox.filehandlerone=filehandlerone
-sandbox.filehandlertwo=filehandlertwo
-sandbox.iohandler=iohandler
-function sandbox.disablerunners()
- validbinaries=false
-end
-function sandbox.disablelibraries()
- validlibraries=false
-end
-if FFISUPPORTED and ffi then
- function sandbox.disablelibraries()
- validlibraries=false
- for k,v in next,ffi do
- if k~="gc" then
- ffi[k]=nil
- end
- end
- end
- local fiiload=ffi.load
- if fiiload then
- local reported={}
- function ffi.load(name,...)
- if validlibraries==false then
- elseif validlibraries==true then
- return fiiload(name,...)
- elseif validlibraries[nameonly(name)] then
- return fiiload(name,...)
- else
- end
- if not reported[name] then
- report("using library %a is not permitted",name)
- reported[name]=true
- end
- return nil
- end
- end
-end
-local overload=sandbox.overload
-local register=sandbox.register
- overload(loadfile,filehandlerone,"loadfile")
-if io then
- overload(io.open,filehandlerone,"io.open")
- overload(io.popen,binaryrunner,"io.popen")
- overload(io.input,iohandler,"io.input")
- overload(io.output,iohandler,"io.output")
- overload(io.lines,filehandlerone,"io.lines")
-end
-if os then
- overload(os.execute,binaryrunner,"os.execute")
- overload(os.spawn,dummyrunner,"os.spawn")
- overload(os.exec,dummyrunner,"os.exec")
- overload(os.resultof,binaryrunner,"os.resultof")
- overload(os.pipeto,binaryrunner,"os.pipeto")
- overload(os.rename,filehandlertwo,"os.rename")
- overload(os.remove,filehandlerone,"os.remove")
-end
-if lfs then
- overload(lfs.chdir,filehandlerone,"lfs.chdir")
- overload(lfs.mkdir,filehandlerone,"lfs.mkdir")
- overload(lfs.rmdir,filehandlerone,"lfs.rmdir")
- overload(lfs.isfile,filehandlerone,"lfs.isfile")
- overload(lfs.isdir,filehandlerone,"lfs.isdir")
- overload(lfs.attributes,filehandlerone,"lfs.attributes")
- overload(lfs.dir,filehandlerone,"lfs.dir")
- overload(lfs.lock_dir,filehandlerone,"lfs.lock_dir")
- overload(lfs.touch,filehandlerone,"lfs.touch")
- overload(lfs.link,filehandlertwo,"lfs.link")
- overload(lfs.setmode,filehandlerone,"lfs.setmode")
- overload(lfs.readlink,filehandlerone,"lfs.readlink")
- overload(lfs.shortname,filehandlerone,"lfs.shortname")
- overload(lfs.symlinkattributes,filehandlerone,"lfs.symlinkattributes")
-end
-if zip then
- zip.open=register(zip.open,filehandlerone,"zip.open")
-end
-sandbox.registerroot=registerroot
-sandbox.registerbinary=registerbinary
-sandbox.registerlibrary=registerlibrary
-sandbox.validfilename=validfilename
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-mrg"] = package.loaded["util-mrg"] or true
-
--- original size: 7819, stripped down to: 5881
-
-if not modules then modules={} end modules ['util-mrg']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local gsub,format=string.gsub,string.format
-local concat=table.concat
-local type,next=type,next
-local P,R,S,V,Ct,C,Cs,Cc,Cp,Cmt,Cb,Cg=lpeg.P,lpeg.R,lpeg.S,lpeg.V,lpeg.Ct,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Cp,lpeg.Cmt,lpeg.Cb,lpeg.Cg
-local lpegmatch,patterns=lpeg.match,lpeg.patterns
-utilities=utilities or {}
-local merger=utilities.merger or {}
-utilities.merger=merger
-merger.strip_comment=true
-local report=logs.reporter("system","merge")
-utilities.report=report
-local m_begin_merge="begin library merge"
-local m_end_merge="end library merge"
-local m_begin_closure="do -- create closure to overcome 200 locals limit"
-local m_end_closure="end -- of closure"
-local m_pattern="%c+".."%-%-%s+"..m_begin_merge.."%c+(.-)%c+".."%-%-%s+"..m_end_merge.."%c+"
-local m_format="\n\n-- "..m_begin_merge.."\n%s\n".."-- "..m_end_merge.."\n\n"
-local m_faked="-- ".."created merged file".."\n\n".."-- "..m_begin_merge.."\n\n".."-- "..m_end_merge.."\n\n"
-local m_report=[[
--- used libraries : %s
--- skipped libraries : %s
--- original bytes : %s
--- stripped bytes : %s
-]]
-local m_preloaded=[[package.loaded[%q] = package.loaded[%q] or true]]
-local function self_fake()
- return m_faked
-end
-local function self_nothing()
- return ""
-end
-local function self_load(name)
- local data=io.loaddata(name) or ""
- if data=="" then
- report("unknown file %a",name)
- else
- report("inserting file %a",name)
- end
- return data or ""
-end
-local space=patterns.space
-local eol=patterns.newline
-local equals=P("=")^0
-local open=P("[")*Cg(equals,"init")*P("[")*P("\n")^-1
-local close=P("]")*C(equals)*P("]")
-local closeeq=Cmt(close*Cb("init"),function(s,i,a,b) return a==b end)
-local longstring=open*(1-closeeq)^0*close
-local quoted=patterns.quoted
-local digit=patterns.digit
-local emptyline=space^0*eol
-local operator1=P("<=")+P(">=")+P("~=")+P("..")+S("/^<>=*+%%")
-local operator2=S("*+/")
-local operator3=S("-")
-local operator4=P("..")
-local separator=S(",;")
-local ignore=(P("]")*space^1*P("=")*space^1*P("]"))/"]=["+(P("=")*space^1*P("{"))/"={"+(P("(")*space^1)/"("+(P("{")*(space+eol)^1*P("}"))/"{}"
-local strings=quoted
-local longcmt=(emptyline^0*P("--")*longstring*emptyline^0)/""
-local longstr=longstring
-local comment=emptyline^0*P("--")*P("-")^0*(1-eol)^0*emptyline^1/"\n"
-local optionalspaces=space^0/""
-local mandatespaces=space^1/""
-local optionalspacing=(eol+space)^0/""
-local mandatespacing=(eol+space)^1/""
-local pack=digit*space^1*operator4*optionalspacing+optionalspacing*operator1*optionalspacing+optionalspacing*operator2*optionalspaces+mandatespacing*operator3*mandatespaces+optionalspaces*separator*optionalspaces
-local lines=emptyline^2/"\n"
-local spaces=(space*space)/" "
-local spaces=(space*space*space*space)/" "
-local compact=Cs ((
- ignore+strings+longcmt+longstr+comment+pack+lines+spaces+1
-)^1 )
-local strip=Cs((emptyline^2/"\n"+1)^0)
-local stripreturn=Cs((1-P("return")*space^1*P(1-space-eol)^1*(space+eol)^0*P(-1))^1)
-function merger.compact(data)
- return lpegmatch(strip,lpegmatch(compact,data))
-end
-local function self_compact(data)
- local delta=0
- if merger.strip_comment then
- local before=#data
- data=lpegmatch(compact,data)
- data=lpegmatch(strip,data)
- local after=#data
- delta=before-after
- report("original size %s, compacted to %s, stripped %s",before,after,delta)
- data=format("-- original size: %s, stripped down to: %s\n\n%s",before,after,data)
- end
- return lpegmatch(stripreturn,data) or data,delta
-end
-local function self_save(name,data)
- if data~="" then
- io.savedata(name,data)
- report("saving %s with size %s",name,#data)
- end
-end
-local function self_swap(data,code)
- return data~="" and (gsub(data,m_pattern,function() return format(m_format,code) end,1)) or ""
-end
-local function self_libs(libs,list)
- local result,f,frozen,foundpath={},nil,false,nil
- result[#result+1]="\n"
- if type(libs)=='string' then libs={ libs } end
- if type(list)=='string' then list={ list } end
- for i=1,#libs do
- local lib=libs[i]
- for j=1,#list do
- local pth=gsub(list[j],"\\","/")
- report("checking library path %a",pth)
- local name=pth.."/"..lib
- if lfs.isfile(name) then
- foundpath=pth
- end
- end
- if foundpath then break end
- end
- if foundpath then
- report("using library path %a",foundpath)
- local right,wrong,original,stripped={},{},0,0
- for i=1,#libs do
- local lib=libs[i]
- local fullname=foundpath.."/"..lib
- if lfs.isfile(fullname) then
- report("using library %a",fullname)
- local preloaded=file.nameonly(lib)
- local data=io.loaddata(fullname,true)
- original=original+#data
- local data,delta=self_compact(data)
- right[#right+1]=lib
- result[#result+1]=m_begin_closure
- result[#result+1]=format(m_preloaded,preloaded,preloaded)
- result[#result+1]=data
- result[#result+1]=m_end_closure
- stripped=stripped+delta
- else
- report("skipping library %a",fullname)
- wrong[#wrong+1]=lib
- end
- end
- right=#right>0 and concat(right," ") or "-"
- wrong=#wrong>0 and concat(wrong," ") or "-"
- report("used libraries: %a",right)
- report("skipped libraries: %a",wrong)
- report("original bytes: %a",original)
- report("stripped bytes: %a",stripped)
- result[#result+1]=format(m_report,right,wrong,original,stripped)
- else
- report("no valid library path found")
- end
- return concat(result,"\n\n")
-end
-function merger.selfcreate(libs,list,target)
- if target then
- self_save(target,self_swap(self_fake(),self_libs(libs,list)))
- end
-end
-function merger.selfmerge(name,libs,list,target)
- self_save(target or name,self_swap(self_load(name),self_libs(libs,list)))
-end
-function merger.selfclean(name)
- self_save(name,self_swap(self_load(name),self_nothing()))
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-env"] = package.loaded["util-env"] or true
-
--- original size: 9738, stripped down to: 5531
-
-if not modules then modules={} end modules ['util-env']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local allocate,mark=utilities.storage.allocate,utilities.storage.mark
-local format,sub,match,gsub,find=string.format,string.sub,string.match,string.gsub,string.find
-local unquoted,quoted,optionalquoted=string.unquoted,string.quoted,string.optionalquoted
-local concat,insert,remove=table.concat,table.insert,table.remove
-environment=environment or {}
-local environment=environment
-local setlocale=os.setlocale
-setlocale(nil,nil)
-local report=logs.reporter("system")
-function os.setlocale(a,b)
- if a or b then
- if report then
- report()
- report("You're messing with os.locale in a supposedly locale neutral enviroment. From")
- report("now on are on your own and without support. Crashes or unexpected side effects")
- report("can happen but don't bother the luatex and context developer team with it.")
- report()
- report=nil
- end
- setlocale(a,b)
- end
-end
-local validengines=allocate {
- ["luatex"]=true,
- ["luajittex"]=true,
-}
-local basicengines=allocate {
- ["luatex"]="luatex",
- ["texlua"]="luatex",
- ["texluac"]="luatex",
- ["luajittex"]="luajittex",
- ["texluajit"]="luajittex",
-}
-local luaengines=allocate {
- ["lua"]=true,
- ["luajit"]=true,
-}
-environment.validengines=validengines
-environment.basicengines=basicengines
-if not arg then
- environment.used_as_library=true
-elseif luaengines[file.removesuffix(arg[-1])] then
-elseif validengines[file.removesuffix(arg[0])] then
- if arg[1]=="--luaonly" then
- arg[-1]=arg[0]
- arg[ 0]=arg[2]
- for k=3,#arg do
- arg[k-2]=arg[k]
- end
- remove(arg)
- remove(arg)
- else
- end
- local originalzero=file.basename(arg[0])
- local specialmapping={ luatools=="base" }
- if originalzero~="mtxrun" and originalzero~="mtxrun.lua" then
- arg[0]=specialmapping[originalzero] or originalzero
- insert(arg,0,"--script")
- insert(arg,0,"mtxrun")
- end
-end
-environment.arguments=allocate()
-environment.files=allocate()
-environment.sortedflags=nil
-function environment.initializearguments(arg)
- local arguments={}
- local files={}
- environment.arguments=arguments
- environment.files=files
- environment.sortedflags=nil
- for index=1,#arg do
- local argument=arg[index]
- if index>0 then
- local flag,value=match(argument,"^%-+(.-)=(.-)$")
- if flag then
- flag=gsub(flag,"^c:","")
- arguments[flag]=unquoted(value or "")
- else
- flag=match(argument,"^%-+(.+)")
- if flag then
- flag=gsub(flag,"^c:","")
- arguments[flag]=true
- else
- files[#files+1]=argument
- end
- end
- end
- end
- if not environment.ownname then
- if os.selfpath and os.selfname then
- environment.ownname=file.addsuffix(file.join(os.selfpath,os.selfname),"lua")
- end
- end
- environment.ownname=file.reslash(environment.ownname or arg[0] or 'unknown.lua')
-end
-function environment.setargument(name,value)
- environment.arguments[name]=value
-end
-function environment.getargument(name,partial)
- local arguments,sortedflags=environment.arguments,environment.sortedflags
- if arguments[name] then
- return arguments[name]
- elseif partial then
- if not sortedflags then
- sortedflags=allocate(table.sortedkeys(arguments))
- for k=1,#sortedflags do
- sortedflags[k]="^"..sortedflags[k]
- end
- environment.sortedflags=sortedflags
- end
- for k=1,#sortedflags do
- local v=sortedflags[k]
- if find(name,v) then
- return arguments[sub(v,2,#v)]
- end
- end
- end
- return nil
-end
-environment.argument=environment.getargument
-function environment.splitarguments(separator)
- local done,before,after=false,{},{}
- local originalarguments=environment.originalarguments
- for k=1,#originalarguments do
- local v=originalarguments[k]
- if not done and v==separator then
- done=true
- elseif done then
- after[#after+1]=v
- else
- before[#before+1]=v
- end
- end
- return before,after
-end
-function environment.reconstructcommandline(arg,noquote)
- local resolveprefix=resolvers.resolve
- arg=arg or environment.originalarguments
- if noquote and #arg==1 then
- return unquoted(resolveprefix and resolveprefix(arg[1]) or arg[1])
- elseif #arg>0 then
- local result={}
- for i=1,#arg do
- result[i]=optionalquoted(resolveprefix and resolveprefix(arg[i]) or resolveprefix)
- end
- return concat(result," ")
- else
- return ""
- end
-end
-function environment.relativepath(path,root)
- if not path then
- path=""
- end
- if not file.is_rootbased_path(path) then
- if not root then
- root=file.pathpart(environment.ownscript or environment.ownname or ".")
- end
- if root=="" then
- root="."
- end
- path=root.."/"..path
- end
- return file.collapsepath(path,true)
-end
-if arg then
- local newarg,instring={},false
- for index=1,#arg do
- local argument=arg[index]
- if find(argument,"^\"") then
- if find(argument,"\"$") then
- newarg[#newarg+1]=gsub(argument,"^\"(.-)\"$","%1")
- instring=false
- else
- newarg[#newarg+1]=gsub(argument,"^\"","")
- instring=true
- end
- elseif find(argument,"\"$") then
- if instring then
- newarg[#newarg]=newarg[#newarg].." "..gsub(argument,"\"$","")
- instring=false
- else
- newarg[#newarg+1]=argument
- end
- elseif instring then
- newarg[#newarg]=newarg[#newarg].." "..argument
- else
- newarg[#newarg+1]=argument
- end
- end
- for i=1,-5,-1 do
- newarg[i]=arg[i]
- end
- environment.initializearguments(newarg)
- environment.originalarguments=mark(newarg)
- environment.rawarguments=mark(arg)
- arg={}
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["luat-env"] = package.loaded["luat-env"] or true
-
--- original size: 6267, stripped down to: 4115
-
- if not modules then modules={} end modules ['luat-env']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local rawset,loadfile=rawset,loadfile
-local gsub=string.gsub
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_lua=logs.reporter("resolvers","lua")
-local luautilities=utilities.lua
-local luasuffixes=luautilities.suffixes
-local texgettoks=tex and tex.gettoks
-environment=environment or {}
-local environment=environment
-local mt={
- __index=function(_,k)
- if k=="version" then
- local version=texgettoks and texgettoks("contextversiontoks")
- if version and version~="" then
- rawset(environment,"version",version)
- return version
- else
- return "unknown"
- end
- elseif k=="jobname" or k=="formatname" then
- local name=tex and tex[k]
- if name or name=="" then
- rawset(environment,k,name)
- return name
- else
- return "unknown"
- end
- elseif k=="outputfilename" then
- local name=environment.jobname
- rawset(environment,k,name)
- return name
- end
- end
-}
-setmetatable(environment,mt)
-function environment.texfile(filename)
- return resolvers.findfile(filename,'tex')
-end
-function environment.luafile(filename)
- if CONTEXTLMTXMODE and CONTEXTLMTXMODE>0 and file.suffix(filename)=="lua" then
- local resolved=resolvers.findfile(file.replacesuffix(filename,"lmt")) or ""
- if resolved~="" then
- return resolved
- end
- end
- local resolved=resolvers.findfile(filename,'tex') or ""
- if resolved~="" then
- return resolved
- end
- resolved=resolvers.findfile(filename,'texmfscripts') or ""
- if resolved~="" then
- return resolved
- end
- return resolvers.findfile(filename,'luatexlibs') or ""
-end
-local stripindeed=false directives.register("system.compile.strip",function(v) stripindeed=v end)
-local function strippable(filename)
- if stripindeed then
- local modu=modules[file.nameonly(filename)]
- return modu and modu.dataonly
- else
- return false
- end
-end
-function environment.luafilechunk(filename,silent,macros)
- filename=file.replacesuffix(filename,"lua")
- local fullname=environment.luafile(filename)
- if fullname and fullname~="" then
- local data=luautilities.loadedluacode(fullname,strippable,filename,macros)
- if not silent then
- report_lua("loading file %a %s",fullname,not data and "failed" or "succeeded")
- end
- return data
- else
- if not silent then
- report_lua("unknown file %a",filename)
- end
- return nil
- end
-end
-function environment.loadluafile(filename,version)
- local lucname,luaname,chunk
- local basename=file.removesuffix(filename)
- if basename==filename then
- luaname=file.addsuffix(basename,luasuffixes.lua)
- lucname=file.addsuffix(basename,luasuffixes.luc)
- else
- luaname=filename
- lucname=nil
- end
- local fullname=(lucname and environment.luafile(lucname)) or ""
- if fullname~="" then
- if trace_locating then
- report_lua("loading %a",fullname)
- end
- chunk=loadfile(fullname)
- end
- if chunk then
- chunk()
- if version then
- local v=version
- if modules and modules[filename] then
- v=modules[filename].version
- elseif versions and versions[filename] then
- v=versions[filename]
- end
- if v==version then
- return true
- else
- if trace_locating then
- report_lua("version mismatch for %a, lua version %a, luc version %a",filename,v,version)
- end
- environment.loadluafile(filename)
- end
- else
- return true
- end
- end
- fullname=(luaname and environment.luafile(luaname)) or ""
- if fullname~="" then
- if trace_locating then
- report_lua("loading %a",fullname)
- end
- chunk=loadfile(fullname)
- if not chunk then
- if trace_locating then
- report_lua("unknown file %a",filename)
- end
- else
- chunk()
- return true
- end
- end
- return false
-end
-environment.filenames=setmetatable({},{
- __index=function(t,k)
- local v=environment.files[k]
- if v then
- return (gsub(v,"%.+$",""))
- end
- end,
- __newindex=function(t,k)
- end,
- __len=function(t)
- return #environment.files
- end,
-} )
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["util-zip"] = package.loaded["util-zip"] or true
-
--- original size: 19496, stripped down to: 10858
-
-if not modules then modules={} end modules ['util-zip']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,tostring,tonumber=type,tostring,tonumber
-local sort=table.sort
-local find,format,sub,gsub=string.find,string.format,string.sub,string.gsub
-local osdate,ostime,osclock=os.date,os.time,os.clock
-local ioopen=io.open
-local loaddata,savedata=io.loaddata,io.savedata
-local filejoin,isdir,dirname,mkdirs=file.join,lfs.isdir,file.dirname,dir.mkdirs
-local files=utilities.files
-local openfile=files.open
-local closefile=files.close
-local readstring=files.readstring
-local readcardinal2=files.readcardinal2le
-local readcardinal4=files.readcardinal4le
-local setposition=files.setposition
-local getposition=files.getposition
-local band=bit32.band
-local rshift=bit32.rshift
-local lshift=bit32.lshift
-local decompress,expandsize,calculatecrc
- local zlibdecompress=zlib.decompress
- local zlibexpandsize=zlib.expandsize
- local zlibchecksum=zlib.crc32
- decompress=function(source)
- return zlibdecompress(source,-15)
- end
- expandsize=zlibexpandsize and function(source,targetsize)
- return zlibexpandsize(source,targetsize,-15)
- end or decompress
- calculatecrc=function(buffer,initial)
- return zlibchecksum(initial or 0,buffer)
- end
-local zipfiles={}
-utilities.zipfiles=zipfiles
-local openzipfile,closezipfile,unzipfile,foundzipfile,getziphash,getziplist do
- function openzipfile(name)
- return {
- name=name,
- handle=openfile(name,0),
- }
- end
- local function collect(z)
- if not z.list then
- local list={}
- local hash={}
- local position=0
- local index=0
- local handle=z.handle
- while true do
- setposition(handle,position)
- local signature=readstring(handle,4)
- if signature=="PK\3\4" then
- local version=readcardinal2(handle)
- local flag=readcardinal2(handle)
- local method=readcardinal2(handle)
- local filetime=readcardinal2(handle)
- local filedate=readcardinal2(handle)
- local crc32=readcardinal4(handle)
- local compressed=readcardinal4(handle)
- local uncompressed=readcardinal4(handle)
- local namelength=readcardinal2(handle)
- local extralength=readcardinal2(handle)
- local filename=readstring(handle,namelength)
- local descriptor=band(flag,8)~=0
- local encrypted=band(flag,1)~=0
- local acceptable=method==0 or method==8
- local skipped=0
- local size=0
- if encrypted then
- size=readcardinal2(handle)
- skipbytes(size)
- skipped=skipped+size+2
- skipbytes(8)
- skipped=skipped+8
- size=readcardinal2(handle)
- skipbytes(size)
- skipped=skipped+size+2
- size=readcardinal4(handle)
- skipbytes(size)
- skipped=skipped+size+4
- size=readcardinal2(handle)
- skipbytes(size)
- skipped=skipped+size+2
- end
- position=position+30+namelength+extralength+skipped
- if descriptor then
- setposition(handle,position+compressed)
- crc32=readcardinal4(handle)
- compressed=readcardinal4(handle)
- uncompressed=readcardinal4(handle)
- end
- if acceptable then
- index=index+1
- local data={
- filename=filename,
- index=index,
- position=position,
- method=method,
- compressed=compressed,
- uncompressed=uncompressed,
- crc32=crc32,
- encrypted=encrypted,
- }
- hash[filename]=data
- list[index]=data
- else
- end
- position=position+compressed
- else
- break
- end
- z.list=list
- z.hash=hash
- end
- end
- end
- function getziplist(z)
- local list=z.list
- if not list then
- collect(z)
- end
- return z.list
- end
- function getziphash(z)
- local hash=z.hash
- if not hash then
- collect(z)
- end
- return z.hash
- end
- function foundzipfile(z,name)
- return getziphash(z)[name]
- end
- function closezipfile(z)
- local f=z.handle
- if f then
- closefile(f)
- z.handle=nil
- end
- end
- function unzipfile(z,filename,check)
- local hash=z.hash
- if not hash then
- hash=zipfiles.hash(z)
- end
- local data=hash[filename]
- if not data then
- end
- if data then
- local handle=z.handle
- local position=data.position
- local compressed=data.compressed
- if compressed>0 then
- setposition(handle,position)
- local result=readstring(handle,compressed)
- if data.method==8 then
- if expandsize then
- result=expandsize(result,data.uncompressed)
- else
- result=decompress(result)
- end
- end
- if check and data.crc32~=calculatecrc(result) then
- print("checksum mismatch")
- return ""
- end
- return result
- else
- return ""
- end
- end
- end
- zipfiles.open=openzipfile
- zipfiles.close=closezipfile
- zipfiles.unzip=unzipfile
- zipfiles.hash=getziphash
- zipfiles.list=getziplist
- zipfiles.found=foundzipfile
-end
-if xzip then
- local writecardinal1=files.writebyte
- local writecardinal2=files.writecardinal2le
- local writecardinal4=files.writecardinal4le
- local logwriter=logs.writer
- local globpattern=dir.globpattern
- local compress=xzip.compress
- local checksum=xzip.crc32
- local function fromdostime(dostime,dosdate)
- return ostime {
- year=rshift(dosdate,9)+1980,
- month=band(rshift(dosdate,5),0x0F),
- day=band((dosdate ),0x1F),
- hour=band(rshift(dostime,11) ),
- min=band(rshift(dostime,5),0x3F),
- sec=band((dostime ),0x1F),
- }
- end
- local function todostime(time)
- local t=osdate("*t",time)
- return
- lshift(t.year-1980,9)+lshift(t.month,5)+t.day,
- lshift(t.hour,11)+lshift(t.min,5)+rshift(t.sec,1)
- end
- local function openzip(filename,level,comment,verbose)
- local f=ioopen(filename,"wb")
- if f then
- return {
- filename=filename,
- handle=f,
- list={},
- level=tonumber(level) or 3,
- comment=tostring(comment),
- verbose=verbose,
- uncompressed=0,
- compressed=0,
- }
- end
- end
- local function writezip(z,name,data,level,time)
- local f=z.handle
- local list=z.list
- local level=tonumber(level) or z.level or 3
- local method=8
- local zipped=compress(data,level)
- local checksum=checksum(data)
- local verbose=z.verbose
- if not zipped then
- method=0
- zipped=data
- end
- local start=f:seek()
- local compressed=#zipped
- local uncompressed=#data
- z.compressed=z.compressed+compressed
- z.uncompressed=z.uncompressed+uncompressed
- if verbose then
- local pct=100*compressed/uncompressed
- if pct>=100 then
- logwriter(format("%10i %s",uncompressed,name))
- else
- logwriter(format("%10i %02.1f %s",uncompressed,pct,name))
- end
- end
- f:write("\x50\x4b\x03\x04")
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,method)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal4(f,checksum)
- writecardinal4(f,compressed)
- writecardinal4(f,uncompressed)
- writecardinal2(f,#name)
- writecardinal2(f,0)
- f:write(name)
- f:write(zipped)
- list[#list+1]={ #zipped,#data,name,checksum,start,time or 0 }
- end
- local function closezip(z)
- local f=z.handle
- local list=z.list
- local comment=z.comment
- local verbose=z.verbose
- local count=#list
- local start=f:seek()
- for i=1,count do
- local l=list[i]
- local compressed=l[1]
- local uncompressed=l[2]
- local name=l[3]
- local checksum=l[4]
- local start=l[5]
- local time=l[6]
- local date,time=todostime(time)
- f:write('\x50\x4b\x01\x02')
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,8)
- writecardinal2(f,time)
- writecardinal2(f,date)
- writecardinal4(f,checksum)
- writecardinal4(f,compressed)
- writecardinal4(f,uncompressed)
- writecardinal2(f,#name)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal4(f,0)
- writecardinal4(f,start)
- f:write(name)
- end
- local stop=f:seek()
- local size=stop-start
- f:write('\x50\x4b\x05\x06')
- writecardinal2(f,0)
- writecardinal2(f,0)
- writecardinal2(f,count)
- writecardinal2(f,count)
- writecardinal4(f,size)
- writecardinal4(f,start)
- if type(comment)=="string" and comment~="" then
- writecardinal2(f,#comment)
- f:write(comment)
- else
- writecardinal2(f,0)
- end
- if verbose then
- local compressed=z.compressed
- local uncompressed=z.uncompressed
- local filename=z.filename
- local pct=100*compressed/uncompressed
- logwriter("")
- if pct>=100 then
- logwriter(format("%10i %s",uncompressed,filename))
- else
- logwriter(format("%10i %02.1f %s",uncompressed,pct,filename))
- end
- end
- f:close()
- end
- local function zipdir(zipname,path,level,verbose)
- if type(zipname)=="table" then
- verbose=zipname.verbose
- level=zipname.level
- path=zipname.path
- zipname=zipname.zipname
- end
- if not zipname or zipname=="" then
- return
- end
- if not path or path=="" then
- path="."
- end
- if not isdir(path) then
- return
- end
- path=gsub(path,"\\+","/")
- path=gsub(path,"/+","/")
- local list={}
- local count=0
- globpattern(path,"",true,function(name,size,time)
- count=count+1
- list[count]={ name,time }
- end)
- sort(list,function(a,b)
- return a[1]<b[1]
- end)
- local zipf=openzip(zipname,level,comment,verbose)
- if zipf then
- local p=#path+2
- for i=1,count do
- local li=list[i]
- local name=li[1]
- local time=li[2]
- local data=loaddata(name)
- local name=sub(name,p,#name)
- writezip(zipf,name,data,level,time,verbose)
- end
- closezip(zipf)
- end
- end
- local function unzipdir(zipname,path,verbose)
- if type(zipname)=="table" then
- verbose=zipname.verbose
- path=zipname.path
- zipname=zipname.zipname
- end
- if not zipname or zipname=="" then
- return
- end
- if not path or path=="" then
- path="."
- end
- local z=openzipfile(zipname)
- if z then
- local list=getziplist(z)
- if list then
- local total=0
- local count=#list
- local step=number.idiv(count,10)
- local done=0
- local steps=verbose=="steps"
- local time=steps and osclock()
- for i=1,count do
- local l=list[i]
- local n=l.filename
- local d=unzipfile(z,n)
- if d then
- local p=filejoin(path,n)
- if mkdirs(dirname(p)) then
- if steps then
- total=total+#d
- done=done+1
- if done>=step then
- done=0
- logwriter(format("%4i files of %4i done, %10i bytes, %0.3f seconds",i,count,total,osclock()-time))
- end
- elseif verbose then
- logwriter(n)
- end
- savedata(p,d)
- end
- else
- logwriter(format("problem with file %s",n))
- end
- end
- if steps then
- logwriter(format("%4i files of %4i done, %10i bytes, %0.3f seconds",count,count,total,osclock()-time))
- end
- closezipfile(z)
- return true
- else
- closezipfile(z)
- end
- end
- end
- zipfiles.zipdir=zipdir
- zipfiles.unzipdir=unzipdir
-end
-zipfiles.gunzipfile=gzip.load
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-tab"] = package.loaded["lxml-tab"] or true
-
--- original size: 61808, stripped down to: 36227
-
-if not modules then modules={} end modules ['lxml-tab']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local trace_entities=false trackers.register("xml.entities",function(v) trace_entities=v end)
-local report_xml=logs and logs.reporter("xml","core") or function(...) print(string.format(...)) end
-if lpeg.setmaxstack then lpeg.setmaxstack(1000) end
-xml=xml or {}
-local xml=xml
-local concat,remove,insert=table.concat,table.remove,table.insert
-local type,next,setmetatable,getmetatable,tonumber,rawset,select=type,next,setmetatable,getmetatable,tonumber,rawset,select
-local lower,find,match,gsub=string.lower,string.find,string.match,string.gsub
-local sort=table.sort
-local utfchar=utf.char
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local P,S,R,C,V,C,Cs=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.V,lpeg.C,lpeg.Cs
-local formatters=string.formatters
-do
-xml.xmlns=xml.xmlns or {}
-local check=P(false)
-local parse=check
-function xml.registerns(namespace,pattern)
- check=check+C(P(lower(pattern)))/namespace
- parse=P { P(check)+1*V(1) }
-end
-function xml.checkns(namespace,url)
- local ns=lpegmatch(parse,lower(url))
- if ns and namespace~=ns then
- xml.xmlns[namespace]=ns
- end
-end
-function xml.resolvens(url)
- return lpegmatch(parse,lower(url)) or ""
-end
-end
-local nsremap,resolvens=xml.xmlns,xml.resolvens
-local stack,level,top,at,xmlnms,errorstr
-local entities,parameters
-local strip,utfize,resolve,cleanup,resolve_predefined,unify_predefined
-local dcache,hcache,acache
-local mt,dt,nt
-local currentfilename,currentline,linenumbers
-local grammar_parsed_text_one
-local grammar_parsed_text_two
-local grammar_unparsed_text
-local handle_hex_entity
-local handle_dec_entity
-local handle_any_entity_dtd
-local handle_any_entity_text
-local function preparexmlstate(settings)
- if settings then
- linenumbers=settings.linenumbers
- stack={}
- level=0
- top={}
- at={}
- mt={}
- dt={}
- nt=0
- xmlns={}
- errorstr=nil
- strip=settings.strip_cm_and_dt
- utfize=settings.utfize_entities
- resolve=settings.resolve_entities
- resolve_predefined=settings.resolve_predefined_entities
- unify_predefined=settings.unify_predefined_entities
- cleanup=settings.text_cleanup
- entities=settings.entities or {}
- currentfilename=settings.currentresource
- currentline=1
- parameters={}
- reported_at_errors={}
- dcache={}
- hcache={}
- acache={}
- if utfize==nil then
- settings.utfize_entities=true
- utfize=true
- end
- if resolve_predefined==nil then
- settings.resolve_predefined_entities=true
- resolve_predefined=true
- end
- else
- linenumbers=false
- stack=nil
- level=nil
- top=nil
- at=nil
- mt=nil
- dt=nil
- nt=nil
- xmlns=nil
- errorstr=nil
- strip=nil
- utfize=nil
- resolve=nil
- resolve_predefined=nil
- unify_predefined=nil
- cleanup=nil
- entities=nil
- parameters=nil
- reported_at_errors=nil
- dcache=nil
- hcache=nil
- acache=nil
- currentfilename=nil
- currentline=1
- end
-end
-local function initialize_mt(root)
- mt={ __index=root }
-end
-function xml.setproperty(root,k,v)
- getmetatable(root).__index[k]=v
-end
-function xml.checkerror(top,toclose)
- return ""
-end
-local checkns=xml.checkns
-local function add_attribute(namespace,tag,value)
- if cleanup and value~="" then
- value=cleanup(value)
- end
- if tag=="xmlns" then
- xmlns[#xmlns+1]=resolvens(value)
- at[tag]=value
- elseif namespace=="" then
- at[tag]=value
- elseif namespace=="xmlns" then
- checkns(tag,value)
- at["xmlns:"..tag]=value
- else
- at[namespace..":"..tag]=value
- end
-end
-local function add_empty(spacing,namespace,tag)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- local resolved=namespace=="" and xmlns[#xmlns] or nsremap[namespace] or namespace
- top=stack[level]
- dt=top.dt
- nt=#dt+1
- local t=linenumbers and {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt={},
- ni=nt,
- cf=currentfilename,
- cl=currentline,
- __p__=top,
- } or {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt={},
- ni=nt,
- __p__=top,
- }
- dt[nt]=t
- setmetatable(t,mt)
- if at.xmlns then
- remove(xmlns)
- end
- at={}
-end
-local function add_begin(spacing,namespace,tag)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- local resolved=namespace=="" and xmlns[#xmlns] or nsremap[namespace] or namespace
- dt={}
- top=linenumbers and {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt=dt,
- ni=nil,
- cf=currentfilename,
- cl=currentline,
- __p__=stack[level],
- } or {
- ns=namespace or "",
- rn=resolved,
- tg=tag,
- at=at,
- dt=dt,
- ni=nil,
- __p__=stack[level],
- }
- setmetatable(top,mt)
- nt=0
- level=level+1
- stack[level]=top
- at={}
-end
-local function add_end(spacing,namespace,tag)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- local toclose=stack[level]
- level=level-1
- top=stack[level]
- if level<1 then
- errorstr=formatters["unable to close %s %s"](tag,xml.checkerror(top,toclose) or "")
- report_xml(errorstr)
- elseif toclose.tg~=tag then
- errorstr=formatters["unable to close %s with %s %s"](toclose.tg,tag,xml.checkerror(top,toclose) or "")
- report_xml(errorstr)
- end
- dt=top.dt
- nt=#dt+1
- dt[nt]=toclose
- toclose.ni=nt
- if toclose.at.xmlns then
- remove(xmlns)
- end
-end
-local function add_text(text)
- if text=="" then
- return
- end
- if cleanup then
- if nt>0 then
- local s=dt[nt]
- if type(s)=="string" then
- dt[nt]=s..cleanup(text)
- else
- nt=nt+1
- dt[nt]=cleanup(text)
- end
- else
- nt=1
- dt[1]=cleanup(text)
- end
- else
- if nt>0 then
- local s=dt[nt]
- if type(s)=="string" then
- dt[nt]=s..text
- else
- nt=nt+1
- dt[nt]=text
- end
- else
- nt=1
- dt[1]=text
- end
- end
-end
-local function add_special(what,spacing,text)
- if spacing~="" then
- nt=nt+1
- dt[nt]=spacing
- end
- if strip and (what=="@cm@" or what=="@dt@") then
- else
- nt=nt+1
- dt[nt]=linenumbers and {
- special=true,
- ns="",
- tg=what,
- ni=nil,
- dt={ text },
- cf=currentfilename,
- cl=currentline,
- } or {
- special=true,
- ns="",
- tg=what,
- ni=nil,
- dt={ text },
- }
- end
-end
-local function set_message(txt)
- errorstr="garbage at the end of the file: "..gsub(txt,"([ \n\r\t]*)","")
-end
-local function attribute_value_error(str)
- if not reported_at_errors[str] then
- report_xml("invalid attribute value %a",str)
- reported_at_errors[str]=true
- at._error_=str
- end
- return str
-end
-local function attribute_specification_error(str)
- if not reported_at_errors[str] then
- report_xml("invalid attribute specification %a",str)
- reported_at_errors[str]=true
- at._error_=str
- end
- return str
-end
-do
- local badentity="&"
- xml.placeholders={
- unknown_dec_entity=function(str) return str=="" and badentity or formatters["&%s;"](str) end,
- unknown_hex_entity=function(str) return formatters["&#x%s;"](str) end,
- unknown_any_entity=function(str) return formatters["&#x%s;"](str) end,
- }
- local function fromhex(s)
- local n=tonumber(s,16)
- if n then
- return utfchar(n)
- else
- return formatters["h:%s"](s),true
- end
- end
- local function fromdec(s)
- local n=tonumber(s)
- if n then
- return utfchar(n)
- else
- return formatters["d:%s"](s),true
- end
- end
- local p_rest=(1-P(";"))^0
- local p_many=P(1)^0
- local parsedentity=P("&#")*(P("x")*(p_rest/fromhex)+(p_rest/fromdec))*P(";")*P(-1)+P ("#")*(P("x")*(p_many/fromhex)+(p_many/fromdec))
- xml.parsedentitylpeg=parsedentity
- local predefined_unified={
- [38]="&amp;",
- [42]="&quot;",
- [47]="&apos;",
- [74]="&lt;",
- [76]="&gt;",
- }
- local predefined_simplified={
- [38]="&",amp="&",
- [42]='"',quot='"',
- [47]="'",apos="'",
- [74]="<",lt="<",
- [76]=">",gt=">",
- }
- local nofprivates=0xF0000
- local privates_u={
- [ [[&]] ]="&amp;",
- [ [["]] ]="&quot;",
- [ [[']] ]="&apos;",
- [ [[<]] ]="&lt;",
- [ [[>]] ]="&gt;",
- }
- local privates_p={
- }
- local privates_s={
- [ [["]] ]="&U+22;",
- [ [[#]] ]="&U+23;",
- [ [[$]] ]="&U+24;",
- [ [[%]] ]="&U+25;",
- [ [[&]] ]="&U+26;",
- [ [[']] ]="&U+27;",
- [ [[<]] ]="&U+3C;",
- [ [[>]] ]="&U+3E;",
- [ [[\]] ]="&U+5C;",
- [ [[{]] ]="&U+7B;",
- [ [[|]] ]="&U+7C;",
- [ [[}]] ]="&U+7D;",
- [ [[~]] ]="&U+7E;",
- }
- local privates_x={
- [ [["]] ]="&U+22;",
- [ [[#]] ]="&U+23;",
- [ [[$]] ]="&U+24;",
- [ [[%]] ]="&U+25;",
- [ [[']] ]="&U+27;",
- [ [[\]] ]="&U+5C;",
- [ [[{]] ]="&U+7B;",
- [ [[|]] ]="&U+7C;",
- [ [[}]] ]="&U+7D;",
- [ [[~]] ]="&U+7E;",
- }
- local privates_n={
- }
- local escaped=utf.remapper(privates_u,"dynamic")
- local unprivatized=utf.remapper(privates_p,"dynamic")
- local unspecialized=utf.remapper(privates_s,"dynamic")
- local despecialized=utf.remapper(privates_x,"dynamic")
- xml.unprivatized=unprivatized
- xml.unspecialized=unspecialized
- xml.despecialized=despecialized
- xml.escaped=escaped
- local function unescaped(s)
- local p=privates_n[s]
- if not p then
- nofprivates=nofprivates+1
- p=utfchar(nofprivates)
- privates_n[s]=p
- s="&"..s..";"
- privates_u[p]=s
- privates_p[p]=s
- privates_s[p]=s
- end
- return p
- end
- xml.privatetoken=unescaped
- xml.privatecodes=privates_n
- xml.specialcodes=privates_s
- function xml.addspecialcode(key,value)
- privates_s[key]=value or "&"..s..";"
- end
- handle_hex_entity=function(str)
- local h=hcache[str]
- if not h then
- local n=tonumber(str,16)
- h=unify_predefined and predefined_unified[n]
- if h then
- if trace_entities then
- report_xml("utfize, converting hex entity &#x%s; into %a",str,h)
- end
- elseif utfize then
- h=(n and utfchar(n)) or xml.unknown_hex_entity(str) or ""
- if not n then
- report_xml("utfize, ignoring hex entity &#x%s;",str)
- elseif trace_entities then
- report_xml("utfize, converting hex entity &#x%s; into %a",str,h)
- end
- else
- if trace_entities then
- report_xml("found entity &#x%s;",str)
- end
- h="&#x"..str..";"
- end
- hcache[str]=h
- end
- return h
- end
- handle_dec_entity=function(str)
- local d=dcache[str]
- if not d then
- local n=tonumber(str)
- d=unify_predefined and predefined_unified[n]
- if d then
- if trace_entities then
- report_xml("utfize, converting dec entity &#%s; into %a",str,d)
- end
- elseif utfize then
- d=(n and utfchar(n)) or placeholders.unknown_dec_entity(str) or ""
- if not n then
- report_xml("utfize, ignoring dec entity &#%s;",str)
- elseif trace_entities then
- report_xml("utfize, converting dec entity &#%s; into %a",str,d)
- end
- else
- if trace_entities then
- report_xml("found entity &#%s;",str)
- end
- d="&#"..str..";"
- end
- dcache[str]=d
- end
- return d
- end
- handle_any_entity_dtd=function(str)
- if resolve then
- local a=resolve_predefined and predefined_simplified[str]
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to predefined %a",str,a)
- end
- else
- if type(resolve)=="function" then
- a=resolve(str,entities) or entities[str]
- else
- a=entities[str]
- end
- if a then
- if type(a)=="function" then
- if trace_entities then
- report_xml("expanding entity &%s; to function call",str)
- end
- a=a(str) or ""
- end
- a=lpegmatch(parsedentity,a) or a
- if trace_entities then
- report_xml("resolving entity &%s; to internal %a",str,a)
- end
- else
- local unknown_any_entity=placeholders.unknown_any_entity
- if unknown_any_entity then
- a=unknown_any_entity(str) or ""
- end
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to external %s",str,a)
- end
- else
- if trace_entities then
- report_xml("keeping entity &%s;",str)
- end
- if str=="" then
- a=badentity
- else
- a="&"..str..";"
- end
- end
- end
- end
- return a
- else
- local a=acache[str]
- if not a then
- a=resolve_predefined and predefined_simplified[str]
- if a then
- acache[str]=a
- if trace_entities then
- report_xml("entity &%s; becomes %a",str,a)
- end
- elseif str=="" then
- if trace_entities then
- report_xml("invalid entity &%s;",str)
- end
- a=badentity
- acache[str]=a
- else
- if trace_entities then
- report_xml("entity &%s; is made private",str)
- end
- a=unescaped(str)
- acache[str]=a
- end
- end
- return a
- end
- end
- handle_any_entity_text=function(str)
- if resolve then
- local a=resolve_predefined and predefined_simplified[str]
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to predefined %a",str,a)
- end
- else
- if type(resolve)=="function" then
- a=resolve(str,entities) or entities[str]
- else
- a=entities[str]
- end
- if a then
- if type(a)=="function" then
- if trace_entities then
- report_xml("expanding entity &%s; to function call",str)
- end
- a=a(str) or ""
- end
- a=lpegmatch(grammar_parsed_text_two,a) or a
- if type(a)=="number" then
- return ""
- else
- a=lpegmatch(parsedentity,a) or a
- if trace_entities then
- report_xml("resolving entity &%s; to internal %a",str,a)
- end
- end
- if trace_entities then
- report_xml("resolving entity &%s; to internal %a",str,a)
- end
- else
- local unknown_any_entity=placeholders.unknown_any_entity
- if unknown_any_entity then
- a=unknown_any_entity(str) or ""
- end
- if a then
- if trace_entities then
- report_xml("resolving entity &%s; to external %s",str,a)
- end
- else
- if trace_entities then
- report_xml("keeping entity &%s;",str)
- end
- if str=="" then
- a=badentity
- else
- a="&"..str..";"
- end
- end
- end
- end
- return a
- else
- local a=acache[str]
- if not a then
- a=resolve_predefined and predefined_simplified[str]
- if a then
- acache[str]=a
- if trace_entities then
- report_xml("entity &%s; becomes %a",str,a)
- end
- elseif str=="" then
- if trace_entities then
- report_xml("invalid entity &%s;",str)
- end
- a=badentity
- acache[str]=a
- else
- if trace_entities then
- report_xml("entity &%s; is made private",str)
- end
- a=unescaped(str)
- acache[str]=a
- end
- end
- return a
- end
- end
- local p_rest=(1-P(";"))^1
- local spec={
- [0x23]="\\Ux{23}",
- [0x24]="\\Ux{24}",
- [0x25]="\\Ux{25}",
- [0x5C]="\\Ux{5C}",
- [0x7B]="\\Ux{7B}",
- [0x7C]="\\Ux{7C}",
- [0x7D]="\\Ux{7D}",
- [0x7E]="\\Ux{7E}",
- }
- local hash=table.setmetatableindex(spec,function(t,k)
- local v=utfchar(k)
- t[k]=v
- return v
- end)
- local function fromuni(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["u:%s"](s),true
- end
- end
- local function fromhex(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["h:%s"](s),true
- end
- end
- local function fromdec(s)
- local n=tonumber(s)
- if n then
- return hash[n]
- else
- return formatters["d:%s"](s),true
- end
- end
- local reparsedentity=P("U+")*(p_rest/fromuni)+P("#")*(
- P("x")*(p_rest/fromhex)+p_rest/fromdec
- )
- local hash=table.setmetatableindex(function(t,k)
- local v=utfchar(k)
- t[k]=v
- return v
- end)
- local function fromuni(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["u:%s"](s),true
- end
- end
- local function fromhex(s)
- local n=tonumber(s,16)
- if n then
- return hash[n]
- else
- return formatters["h:%s"](s),true
- end
- end
- local function fromdec(s)
- local n=tonumber(s)
- if n then
- return hash[n]
- else
- return formatters["d:%s"](s),true
- end
- end
- local unescapedentity=P("U+")*(p_rest/fromuni)+P("#")*(
- P("x")*(p_rest/fromhex)+p_rest/fromdec
- )
- xml.reparsedentitylpeg=reparsedentity
- xml.unescapedentitylpeg=unescapedentity
-end
-local escaped=xml.escaped
-local unescaped=xml.unescaped
-local placeholders=xml.placeholders
-local function handle_end_entity(str)
- report_xml("error in entity, %a found without ending %a",str,";")
- return str
-end
-local function handle_crap_error(chr)
- report_xml("error in parsing, unexpected %a found ",chr)
- add_text(chr)
- return chr
-end
-local function handlenewline()
- currentline=currentline+1
-end
-local spacetab=S(' \t')
-local space=S(' \r\n\t')
-local newline=lpegpatterns.newline/handlenewline
-local anything=P(1)
-local open=P('<')
-local close=P('>')
-local squote=S("'")
-local dquote=S('"')
-local equal=P('=')
-local slash=P('/')
-local colon=P(':')
-local semicolon=P(';')
-local ampersand=P('&')
-local valid_0=R("\128\255")
-local valid_1=R('az','AZ')+S('_')+valid_0
-local valid_2=valid_1+R('09')+S('-.')
-local valid=valid_1*valid_2^0
-local name_yes=C(valid^1)*colon*C(valid^1)
-local name_nop=C(P(true))*C(valid^1)
-local name=name_yes+name_nop
-local utfbom=lpegpatterns.utfbom
-local spacing=C(space^0)
-local space_nl=spacetab+newline
-local spacing_nl=Cs((space_nl)^0)
-local anything_nl=newline+P(1)
-local function weirdentity(k,v)
- if trace_entities then
- report_xml("registering %s entity %a as %a","weird",k,v)
- end
- parameters[k]=v
-end
-local function normalentity(k,v)
- if trace_entities then
- report_xml("registering %s entity %a as %a","normal",k,v)
- end
- entities[k]=v
-end
-local function systementity(k,v,n)
- if trace_entities then
- report_xml("registering %s entity %a as %a","system",k,v)
- end
- entities[k]=v
-end
-local function publicentity(k,v,n)
- if trace_entities then
- report_xml("registering %s entity %a as %a","public",k,v)
- end
- entities[k]=v
-end
-local function entityfile(pattern,k,v,n)
- if n then
- local okay,data
- local loadbinfile=resolvers and resolvers.loadbinfile
- if loadbinfile then
- okay,data=loadbinfile(n)
- else
- data=io.loaddata(n)
- okay=data and data~=""
- end
- if okay then
- if trace_entities then
- report_xml("loading public entities %a as %a from %a",k,v,n)
- end
- lpegmatch(pattern,data)
- return
- end
- end
- report_xml("ignoring public entities %a as %a from %a",k,v,n)
-end
-local function install(spacenewline,spacing,anything)
- local anyentitycontent=(1-open-semicolon-space-close-ampersand)^0
- local hexentitycontent=R("AF","af","09")^1
- local decentitycontent=R("09")^1
- local parsedentity=P("#")/""*(
- P("x")/""*(hexentitycontent/handle_hex_entity)+(decentitycontent/handle_dec_entity)
- )+(anyentitycontent/handle_any_entity_dtd)
- local parsedentity_text=P("#")/""*(
- P("x")/""*(hexentitycontent/handle_hex_entity)+(decentitycontent/handle_dec_entity)
- )+(anyentitycontent/handle_any_entity_text)
- local entity=(ampersand/"")*parsedentity*(semicolon/"")+ampersand*(anyentitycontent/handle_end_entity)
- local entity_text=(ampersand/"")*parsedentity_text*(semicolon/"")+ampersand*(anyentitycontent/handle_end_entity)
- local text_unparsed=Cs((anything-open)^1)
- local text_parsed=(Cs((anything-open-ampersand)^1)/add_text+Cs(entity_text)/add_text)^1
- local somespace=(spacenewline)^1
- local optionalspace=(spacenewline)^0
- local value=(squote*Cs((entity+(anything-squote))^0)*squote)+(dquote*Cs((entity+(anything-dquote))^0)*dquote)
- local endofattributes=slash*close+close
- local whatever=space*name*optionalspace*equal
- local wrongvalue=Cs(P(entity+(1-space-endofattributes))^1)/attribute_value_error
- local attributevalue=value+wrongvalue
- local attribute=(somespace*name*optionalspace*equal*optionalspace*attributevalue)/add_attribute
- local attributes=(attribute+somespace^-1*(((anything-endofattributes)^1)/attribute_specification_error))^0
- local parsedtext=text_parsed
- local unparsedtext=text_unparsed/add_text
- local balanced=P { "["*((anything-S"[]")+V(1))^0*"]" }
- local emptyelement=(spacing*open*name*attributes*optionalspace*slash*close)/add_empty
- local beginelement=(spacing*open*name*attributes*optionalspace*close)/add_begin
- local endelement=(spacing*open*slash*name*optionalspace*close)/add_end
- local begincomment=open*P("!--")
- local endcomment=P("--")*close
- local begininstruction=open*P("?")
- local endinstruction=P("?")*close
- local begincdata=open*P("![CDATA[")
- local endcdata=P("]]")*close
- local someinstruction=C((anything-endinstruction)^0)
- local somecomment=C((anything-endcomment )^0)
- local somecdata=C((anything-endcdata )^0)
- local begindoctype=open*P("!DOCTYPE")
- local enddoctype=close
- local beginset=P("[")
- local endset=P("]")
- local wrdtypename=C((anything-somespace-P(";"))^1)
- local doctypename=C((anything-somespace-close)^0)
- local elementdoctype=optionalspace*P("<!ELEMENT")*(anything-close)^0*close
- local basiccomment=begincomment*((anything-endcomment)^0)*endcomment
- local weirdentitytype=P("%")*(somespace*doctypename*somespace*value)/weirdentity
- local normalentitytype=(doctypename*somespace*value)/normalentity
- local publicentitytype=(doctypename*somespace*P("PUBLIC")*somespace*value)/publicentity
- local systementitytype=(doctypename*somespace*P("SYSTEM")*somespace*value*somespace*P("NDATA")*somespace*doctypename)/systementity
- local entitydoctype=optionalspace*P("<!ENTITY")*somespace*(systementitytype+publicentitytype+normalentitytype+weirdentitytype)*optionalspace*close
- local publicentityfile=(doctypename*somespace*P("PUBLIC")*somespace*value*(somespace*value)^0)/function(...)
- entityfile(entitydoctype,...)
- end
- local function weirdresolve(s)
- lpegmatch(entitydoctype,parameters[s])
- end
- local function normalresolve(s)
- lpegmatch(entitydoctype,entities[s])
- end
- local entityresolve=P("%")*(wrdtypename/weirdresolve )*P(";")+P("&")*(wrdtypename/normalresolve)*P(";")
- entitydoctype=entitydoctype+entityresolve
- local doctypeset=beginset*optionalspace*P(elementdoctype+entitydoctype+entityresolve+basiccomment+space)^0*optionalspace*endset
- local definitiondoctype=doctypename*somespace*doctypeset
- local publicdoctype=doctypename*somespace*P("PUBLIC")*somespace*value*somespace*value*somespace*doctypeset
- local systemdoctype=doctypename*somespace*P("SYSTEM")*somespace*value*somespace*doctypeset
- local simpledoctype=(anything-close)^1
- local somedoctype=C((somespace*(
-publicentityfile+publicdoctype+systemdoctype+definitiondoctype+simpledoctype)*optionalspace)^0)
- local instruction=(spacing*begininstruction*someinstruction*endinstruction)/function(...) add_special("@pi@",...) end
- local comment=(spacing*begincomment*somecomment*endcomment )/function(...) add_special("@cm@",...) end
- local cdata=(spacing*begincdata*somecdata*endcdata )/function(...) add_special("@cd@",...) end
- local doctype=(spacing*begindoctype*somedoctype*enddoctype )/function(...) add_special("@dt@",...) end
- local crap_parsed=anything-beginelement-endelement-emptyelement-begininstruction-begincomment-begincdata-ampersand
- local crap_unparsed=anything-beginelement-endelement-emptyelement-begininstruction-begincomment-begincdata
- local parsedcrap=Cs((crap_parsed^1+entity_text)^1)/handle_crap_error
- local parsedcrap=Cs((crap_parsed^1+entity_text)^1)/handle_crap_error
- local unparsedcrap=Cs((crap_unparsed )^1)/handle_crap_error
- local trailer=space^0*(text_unparsed/set_message)^0
- local grammar_parsed_text_one=P { "preamble",
- preamble=utfbom^0*instruction^0*(doctype+comment+instruction)^0,
- }
- local grammar_parsed_text_two=P { "followup",
- followup=V("parent")*trailer,
- parent=beginelement*V("children")^0*endelement,
- children=parsedtext+V("parent")+emptyelement+comment+cdata+instruction+parsedcrap,
- }
- local grammar_unparsed_text=P { "preamble",
- preamble=utfbom^0*instruction^0*(doctype+comment+instruction)^0*V("parent")*trailer,
- parent=beginelement*V("children")^0*endelement,
- children=unparsedtext+V("parent")+emptyelement+comment+cdata+instruction+unparsedcrap,
- }
- return grammar_parsed_text_one,grammar_parsed_text_two,grammar_unparsed_text
-end
-local
- grammar_parsed_text_one_nop,
- grammar_parsed_text_two_nop,
- grammar_unparsed_text_nop=install(space,spacing,anything)
-local
- grammar_parsed_text_one_yes,
- grammar_parsed_text_two_yes,
- grammar_unparsed_text_yes=install(space_nl,spacing_nl,anything_nl)
-local function _xmlconvert_(data,settings,detail)
- settings=settings or {}
- preparexmlstate(settings)
- if settings.linenumbers then
- grammar_parsed_text_one=grammar_parsed_text_one_yes
- grammar_parsed_text_two=grammar_parsed_text_two_yes
- grammar_unparsed_text=grammar_unparsed_text_yes
- else
- grammar_parsed_text_one=grammar_parsed_text_one_nop
- grammar_parsed_text_two=grammar_parsed_text_two_nop
- grammar_unparsed_text=grammar_unparsed_text_nop
- end
- local preprocessor=settings.preprocessor
- if data and data~="" and type(preprocessor)=="function" then
- data=preprocessor(data,settings) or data
- end
- if settings.parent_root then
- mt=getmetatable(settings.parent_root)
- else
- initialize_mt(top)
- end
- level=level+1
- stack[level]=top
- top.dt={}
- dt=top.dt
- nt=0
- if not data or data=="" then
- errorstr="empty xml file"
- elseif data==true then
- errorstr=detail or "problematic xml file"
- elseif utfize or resolve then
- local m=lpegmatch(grammar_parsed_text_one,data)
- if m then
- m=lpegmatch(grammar_parsed_text_two,data,m)
- end
- if m then
- else
- errorstr="invalid xml file - parsed text"
- end
- elseif type(data)=="string" then
- if lpegmatch(grammar_unparsed_text,data) then
- errorstr=""
- else
- errorstr="invalid xml file - unparsed text"
- end
- else
- errorstr="invalid xml file - no text at all"
- end
- local result
- if errorstr and errorstr~="" then
- result={ dt={ { ns="",tg="error",dt={ errorstr },at={},er=true } } }
- setmetatable(result,mt)
- setmetatable(result.dt[1],mt)
- setmetatable(stack,mt)
- local errorhandler=settings.error_handler
- if errorhandler==false then
- else
- errorhandler=errorhandler or xml.errorhandler
- if errorhandler then
- local currentresource=settings.currentresource
- if currentresource and currentresource~="" then
- xml.errorhandler(formatters["load error in [%s]: %s"](currentresource,errorstr),currentresource)
- else
- xml.errorhandler(formatters["load error: %s"](errorstr))
- end
- end
- end
- else
- result=stack[1]
- end
- if not settings.no_root then
- result={ special=true,ns="",tg='@rt@',dt=result.dt,at={},entities=entities,settings=settings }
- setmetatable(result,mt)
- local rdt=result.dt
- for k=1,#rdt do
- local v=rdt[k]
- if type(v)=="table" and not v.special then
- result.ri=k
- v.__p__=result
- break
- end
- end
- end
- if errorstr and errorstr~="" then
- result.error=true
- else
- errorstr=nil
- end
- result.statistics={
- errormessage=errorstr,
- entities={
- decimals=dcache,
- hexadecimals=hcache,
- names=acache,
- intermediates=parameters,
- }
- }
- preparexmlstate()
- return result
-end
-local function xmlconvert(data,settings)
- local ok,result=pcall(function() return _xmlconvert_(data,settings) end)
- if ok then
- return result
- elseif type(result)=="string" then
- return _xmlconvert_(true,settings,result)
- else
- return _xmlconvert_(true,settings)
- end
-end
-xml.convert=xmlconvert
-function xml.inheritedconvert(data,xmldata,cleanup)
- local settings=xmldata.settings
- if settings then
- settings.parent_root=xmldata
- end
- local xc=xmlconvert(data,settings)
- if cleanup then
- local x=xc.dt
- if x then
- x=x[1]
- if x and x.tg=="@pi@" then
- local dt=x.dt
- local pi=dt and dt[1]
- if type(pi)=="string" and find(pi,"^xml") then
- remove(dt,1)
- end
- end
- end
- end
- return xc
-end
-function xml.is_valid(root)
- return root and root.dt and root.dt[1] and type(root.dt[1])=="table" and not root.dt[1].er
-end
-function xml.package(tag,attributes,data)
- local ns,tg=match(tag,"^(.-):?([^:]+)$")
- local t={ ns=ns,tg=tg,dt=data or "",at=attributes or {} }
- setmetatable(t,mt)
- return t
-end
-function xml.is_valid(root)
- return root and not root.error
-end
-xml.errorhandler=report_xml
-function xml.load(filename,settings)
- local data=""
- if type(filename)=="string" then
- local f=io.open(filename,'r')
- if f then
- data=f:read("*all")
- f:close()
- end
- elseif filename then
- data=filename:read("*all")
- end
- if settings then
- settings.currentresource=filename
- local result=xmlconvert(data,settings)
- settings.currentresource=nil
- return result
- else
- return xmlconvert(data,{ currentresource=filename })
- end
-end
-local no_root={ no_root=true }
-function xml.toxml(data)
- if type(data)=="string" then
- local root={ xmlconvert(data,no_root) }
- return (#root>1 and root) or root[1]
- else
- return data
- end
-end
-local function copy(old,p)
- if old then
- local new={}
- for k,v in next,old do
- local t=type(v)=="table"
- if k=="at" then
- local t={}
- for k,v in next,v do
- t[k]=v
- end
- new[k]=t
- elseif k=="dt" then
- v.__p__=nil
- local t={}
- for i=1,#v do
- local vi=v[i]
- if type(vi)=="table" then
- t[i]=copy(vi,new)
- else
- t[i]=vi
- end
- end
- new[k]=t
- t.__p__=p
- else
- new[k]=v
- end
- end
- local mt=getmetatable(old)
- if mt then
- setmetatable(new,mt)
- end
- return new
- else
- return {}
- end
-end
-xml.copy=copy
-function xml.checkbom(root)
- if root.ri then
- local dt=root.dt
- for k=1,#dt do
- local v=dt[k]
- if type(v)=="table" and v.special and v.tg=="@pi@" and find(v.dt[1],"xml.*version=") then
- return
- end
- end
- insert(dt,1,{ special=true,ns="",tg="@pi@",dt={ "xml version='1.0' standalone='yes'" } } )
- insert(dt,2,"\n" )
- end
-end
-local f_attribute=formatters['%s=%q']
-local function verbose_element(e,handlers,escape)
- local handle=handlers.handle
- local serialize=handlers.serialize
- local ens,etg,eat,edt,ern=e.ns,e.tg,e.at,e.dt,e.rn
- local ats=eat and next(eat) and {}
- if ats then
- local n=0
- for k in next,eat do
- n=n+1
- ats[n]=k
- end
- if n==1 then
- local k=ats[1]
- ats=f_attribute(k,escaped(eat[k]))
- else
- sort(ats)
- for i=1,n do
- local k=ats[i]
- ats[i]=f_attribute(k,escaped(eat[k]))
- end
- ats=concat(ats," ")
- end
- end
- if ern and trace_entities and ern~=ens then
- ens=ern
- end
- local n=edt and #edt
- if ens~="" then
- if n and n>0 then
- if ats then
- handle("<",ens,":",etg," ",ats,">")
- else
- handle("<",ens,":",etg,">")
- end
- for i=1,n do
- local e=edt[i]
- if type(e)=="string" then
- handle(escaped(e))
- else
- serialize(e,handlers)
- end
- end
- handle("</",ens,":",etg,">")
- else
- if ats then
- handle("<",ens,":",etg," ",ats,"/>")
- else
- handle("<",ens,":",etg,"/>")
- end
- end
- else
- if n and n>0 then
- if ats then
- handle("<",etg," ",ats,">")
- else
- handle("<",etg,">")
- end
- for i=1,n do
- local e=edt[i]
- if type(e)=="string" then
- handle(escaped(e))
- else
- serialize(e,handlers)
- end
- end
- handle("</",etg,">")
- else
- if ats then
- handle("<",etg," ",ats,"/>")
- else
- handle("<",etg,"/>")
- end
- end
- end
-end
-local function verbose_pi(e,handlers)
- handlers.handle("<?",e.dt[1],"?>")
-end
-local function verbose_comment(e,handlers)
- handlers.handle("<!--",e.dt[1],"-->")
-end
-local function verbose_cdata(e,handlers)
- handlers.handle("<![CDATA[",e.dt[1],"]]>")
-end
-local function verbose_doctype(e,handlers)
- handlers.handle("<!DOCTYPE",e.dt[1],">")
-end
-local function verbose_root(e,handlers)
- handlers.serialize(e.dt,handlers)
-end
-local function verbose_text(e,handlers)
- handlers.handle(escaped(e))
-end
-local function verbose_document(e,handlers)
- local serialize=handlers.serialize
- local functions=handlers.functions
- for i=1,#e do
- local ei=e[i]
- if type(ei)=="string" then
- functions["@tx@"](ei,handlers)
- else
- serialize(ei,handlers)
- end
- end
-end
-local function serialize(e,handlers,...)
- if e then
- local initialize=handlers.initialize
- local finalize=handlers.finalize
- local functions=handlers.functions
- if initialize then
- local state=initialize(...)
- if not state==true then
- return state
- end
- end
- local etg=e.tg
- if etg then
- (functions[etg] or functions["@el@"])(e,handlers)
- else
- functions["@dc@"](e,handlers)
- end
- if finalize then
- return finalize()
- end
- end
-end
-local function xserialize(e,handlers)
- if e then
- local functions=handlers.functions
- local etg=e.tg
- if etg then
- (functions[etg] or functions["@el@"])(e,handlers)
- else
- functions["@dc@"](e,handlers)
- end
- end
-end
-local handlers={}
-local function newhandlers(settings)
- local t=table.copy(handlers[settings and settings.parent or "verbose"] or {})
- if settings then
- for k,v in next,settings do
- if type(v)=="table" then
- local tk=t[k] if not tk then tk={} t[k]=tk end
- for kk,vv in next,v do
- tk[kk]=vv
- end
- else
- t[k]=v
- end
- end
- if settings.name then
- handlers[settings.name]=t
- end
- end
- utilities.storage.mark(t)
- return t
-end
-local nofunction=function() end
-function xml.sethandlersfunction(handler,name,fnc)
- handler.functions[name]=fnc or nofunction
-end
-function xml.gethandlersfunction(handler,name)
- return handler.functions[name]
-end
-function xml.gethandlers(name)
- return handlers[name]
-end
-newhandlers {
- name="verbose",
- initialize=false,
- finalize=false,
- serialize=xserialize,
- handle=print,
- functions={
- ["@dc@"]=verbose_document,
- ["@dt@"]=verbose_doctype,
- ["@rt@"]=verbose_root,
- ["@el@"]=verbose_element,
- ["@pi@"]=verbose_pi,
- ["@cm@"]=verbose_comment,
- ["@cd@"]=verbose_cdata,
- ["@tx@"]=verbose_text,
- }
-}
-local result
-local xmlfilehandler=newhandlers {
- name="file",
- initialize=function(name)
- result=io.open(name,"wb")
- return result
- end,
- finalize=function()
- result:close()
- return true
- end,
- handle=function(...)
- result:write(...)
- end,
-}
-function xml.save(root,name)
- serialize(root,xmlfilehandler,name)
-end
-local result,r,threshold={},0,512
-local xmlstringhandler=newhandlers {
- name="string",
- initialize=function()
- r=0
- return result
- end,
- finalize=function()
- local done=concat(result,"",1,r)
- r=0
- if r>threshold then
- result={}
- end
- return done
- end,
- handle=function(...)
- for i=1,select("#",...) do
- r=r+1
- result[r]=select(i,...)
- end
- end,
-}
-local function xmltostring(root)
- if not root then
- return ""
- elseif type(root)=="string" then
- return root
- else
- return serialize(root,xmlstringhandler) or ""
- end
-end
-local function __tostring(root)
- return (root and xmltostring(root)) or ""
-end
-initialize_mt=function(root)
- mt={ __tostring=__tostring,__index=root }
-end
-xml.defaulthandlers=handlers
-xml.newhandlers=newhandlers
-xml.serialize=serialize
-xml.tostring=xmltostring
-local function xmlstring(e,handle)
- if not handle or (e.special and e.tg~="@rt@") then
- elseif e.tg then
- local edt=e.dt
- if edt then
- for i=1,#edt do
- xmlstring(edt[i],handle)
- end
- end
- else
- handle(e)
- end
-end
-xml.string=xmlstring
-function xml.settings(e)
- while e do
- local s=e.settings
- if s then
- return s
- else
- e=e.__p__
- end
- end
- return nil
-end
-function xml.root(e)
- local r=e
- while e do
- e=e.__p__
- if e then
- r=e
- end
- end
- return r
-end
-function xml.parent(root)
- return root.__p__
-end
-function xml.body(root)
- return root.ri and root.dt[root.ri] or root
-end
-function xml.name(root)
- if not root then
- return ""
- end
- local ns=root.ns
- local tg=root.tg
- if ns=="" then
- return tg
- else
- return ns..":"..tg
- end
-end
-function xml.erase(dt,k)
- if dt then
- if k then
- dt[k]=""
- else for k=1,#dt do
- dt[1]={ "" }
- end end
- end
-end
-function xml.assign(dt,k,root)
- if dt and k then
- dt[k]=type(root)=="table" and xml.body(root) or root
- return dt[k]
- else
- return xml.body(root)
- end
-end
-function xml.tocdata(e,wrapper)
- local whatever=type(e)=="table" and xmltostring(e.dt) or e or ""
- if wrapper then
- whatever=formatters["<%s>%s</%s>"](wrapper,whatever,wrapper)
- end
- local t={ special=true,ns="",tg="@cd@",at={},rn="",dt={ whatever },__p__=e }
- setmetatable(t,getmetatable(e))
- e.dt={ t }
-end
-function xml.makestandalone(root)
- if root.ri then
- local dt=root.dt
- for k=1,#dt do
- local v=dt[k]
- if type(v)=="table" and v.special and v.tg=="@pi@" then
- local txt=v.dt[1]
- if find(txt,"xml.*version=") then
- v.dt[1]=txt.." standalone='yes'"
- break
- end
- end
- end
- end
- return root
-end
-function xml.kind(e)
- local dt=e and e.dt
- if dt then
- local n=#dt
- if n==1 then
- local d=dt[1]
- if d.special then
- local tg=d.tg
- if tg=="@cd@" then
- return "cdata"
- elseif tg=="@cm" then
- return "comment"
- elseif tg=="@pi@" then
- return "instruction"
- elseif tg=="@dt@" then
- return "declaration"
- end
- elseif type(d)=="string" then
- return "text"
- end
- return "element"
- elseif n>0 then
- return "mixed"
- end
- end
- return "empty"
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-lpt"] = package.loaded["lxml-lpt"] or true
-
--- original size: 54667, stripped down to: 31258
-
-if not modules then modules={} end modules ['lxml-lpt']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local concat,remove,insert=table.concat,table.remove,table.insert
-local type,next,tonumber,tostring,setmetatable,load,select=type,next,tonumber,tostring,setmetatable,load,select
-local format,upper,lower,gmatch,gsub,find,rep=string.format,string.upper,string.lower,string.gmatch,string.gsub,string.find,string.rep
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local setmetatableindex=table.setmetatableindex
-local formatters=string.formatters
-local trace_lpath=false
-local trace_lparse=false
-local trace_lprofile=false
-local report_lpath=logs.reporter("xml","lpath")
-if trackers then
- trackers.register("xml.path",function(v)
- trace_lpath=v
- end)
- trackers.register("xml.parse",function(v)
- trace_lparse=v
- end)
- trackers.register("xml.profile",function(v)
- trace_lpath=v
- trace_lparse=v
- trace_lprofile=v
- end)
-end
-local xml=xml
-local lpathcalls=0 function xml.lpathcalls () return lpathcalls end
-local lpathcached=0 function xml.lpathcached() return lpathcached end
-xml.functions=xml.functions or {}
-local functions=xml.functions
-xml.expressions=xml.expressions or {}
-local expressions=xml.expressions
-xml.finalizers=xml.finalizers or {}
-local finalizers=xml.finalizers
-xml.specialhandler=xml.specialhandler or {}
-local specialhandler=xml.specialhandler
-lpegpatterns.xml=lpegpatterns.xml or {}
-local xmlpatterns=lpegpatterns.xml
-finalizers.xml=finalizers.xml or {}
-finalizers.tex=finalizers.tex or {}
-local function fallback (t,name)
- local fn=finalizers[name]
- if fn then
- t[name]=fn
- else
- report_lpath("unknown sub finalizer %a",name)
- fn=function() end
- end
- return fn
-end
-setmetatableindex(finalizers.xml,fallback)
-setmetatableindex(finalizers.tex,fallback)
-xml.defaultprotocol="xml"
-local apply_axis={}
-apply_axis['root']=function(list)
- local collected={}
- for l=1,#list do
- local ll=list[l]
- local rt=ll
- while ll do
- ll=ll.__p__
- if ll then
- rt=ll
- end
- end
- collected[l]=rt
- end
- return collected
-end
-apply_axis['self']=function(list)
- return list
-end
-apply_axis['child']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local dt=ll.dt
- if dt then
- local n=#dt
- if n==0 then
- ll.en=0
- elseif n==1 then
- local dk=dt[1]
- if dk.tg then
- c=c+1
- collected[c]=dk
- dk.ni=1
- dk.ei=1
- ll.en=1
- end
- else
- local en=0
- for k=1,#dt do
- local dk=dt[k]
- if dk.tg then
- c=c+1
- en=en+1
- collected[c]=dk
- dk.ni=k
- dk.ei=en
- end
- end
- ll.en=en
- end
- end
- end
- return collected
-end
-local function collect(list,collected,c)
- local dt=list.dt
- if dt then
- local n=#dt
- if n==0 then
- list.en=0
- elseif n==1 then
- local dk=dt[1]
- if dk.tg then
- c=c+1
- collected[c]=dk
- dk.ni=1
- dk.ei=1
- c=collect(dk,collected,c)
- list.en=1
- else
- list.en=0
- end
- else
- local en=0
- for k=1,n do
- local dk=dt[k]
- if dk.tg then
- c=c+1
- en=en+1
- collected[c]=dk
- dk.ni=k
- dk.ei=en
- c=collect(dk,collected,c)
- end
- end
- list.en=en
- end
- end
- return c
-end
-apply_axis['descendant']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- c=collect(list[l],collected,c)
- end
- return collected
-end
-local function collect(list,collected,c)
- local dt=list.dt
- if dt then
- local n=#dt
- if n==0 then
- list.en=0
- elseif n==1 then
- local dk=dt[1]
- if dk.tg then
- c=c+1
- collected[c]=dk
- dk.ni=1
- dk.ei=1
- c=collect(dk,collected,c)
- list.en=1
- end
- else
- local en=0
- for k=1,#dt do
- local dk=dt[k]
- if dk.tg then
- c=c+1
- en=en+1
- collected[c]=dk
- dk.ni=k
- dk.ei=en
- c=collect(dk,collected,c)
- end
- end
- list.en=en
- end
- end
- return c
-end
-apply_axis['descendant-or-self']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- if ll.special~=true then
- c=c+1
- collected[c]=ll
- end
- c=collect(ll,collected,c)
- end
- return collected
-end
-apply_axis['ancestor']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- while ll do
- ll=ll.__p__
- if ll then
- c=c+1
- collected[c]=ll
- end
- end
- end
- return collected
-end
-apply_axis['ancestor-or-self']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- c=c+1
- collected[c]=ll
- while ll do
- ll=ll.__p__
- if ll then
- c=c+1
- collected[c]=ll
- end
- end
- end
- return collected
-end
-apply_axis['parent']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local pl=list[l].__p__
- if pl then
- c=c+1
- collected[c]=pl
- end
- end
- return collected
-end
-apply_axis['attribute']=function(list)
- return {}
-end
-apply_axis['namespace']=function(list)
- return {}
-end
-apply_axis['following']=function(list)
- return {}
-end
-apply_axis['preceding']=function(list)
- return {}
-end
-apply_axis['following-sibling']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local p=ll.__p__
- local d=p.dt
- for i=ll.ni+1,#d do
- local di=d[i]
- if type(di)=="table" then
- c=c+1
- collected[c]=di
- end
- end
- end
- return collected
-end
-apply_axis['preceding-sibling']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local p=ll.__p__
- local d=p.dt
- for i=1,ll.ni-1 do
- local di=d[i]
- if type(di)=="table" then
- c=c+1
- collected[c]=di
- end
- end
- end
- return collected
-end
-apply_axis['reverse-sibling']=function(list)
- local collected={}
- local c=0
- for l=1,#list do
- local ll=list[l]
- local p=ll.__p__
- local d=p.dt
- for i=ll.ni-1,1,-1 do
- local di=d[i]
- if type(di)=="table" then
- c=c+1
- collected[c]=di
- end
- end
- end
- return collected
-end
-apply_axis['auto-descendant-or-self']=apply_axis['descendant-or-self']
-apply_axis['auto-descendant']=apply_axis['descendant']
-apply_axis['auto-child']=apply_axis['child']
-apply_axis['auto-self']=apply_axis['self']
-apply_axis['initial-child']=apply_axis['child']
-local function apply_nodes(list,directive,nodes)
- local maxn=#nodes
- if maxn==3 then
- local nns=nodes[2]
- local ntg=nodes[3]
- if not nns and not ntg then
- if directive then
- return list
- else
- return {}
- end
- else
- local collected={}
- local c=0
- local m=0
- local p=nil
- if not nns then
- for l=1,#list do
- local ll=list[l]
- local ltg=ll.tg
- if ltg then
- if directive then
- if ntg==ltg then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif ntg~=ltg then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- elseif not ntg then
- for l=1,#list do
- local ll=list[l]
- local lns=ll.rn or ll.ns
- if lns then
- if directive then
- if lns==nns then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif lns~=nns then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- else
- for l=1,#list do
- local ll=list[l]
- local ltg=ll.tg
- if ltg then
- local lns=ll.rn or ll.ns
- local ok=ltg==ntg and lns==nns
- if directive then
- if ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif not ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- end
- return collected
- end
- else
- local collected={}
- local c=0
- local m=0
- local p=nil
- for l=1,#list do
- local ll=list[l]
- local ltg=ll.tg
- if ltg then
- local lns=ll.rn or ll.ns
- local ok=false
- for n=1,maxn,3 do
- local nns=nodes[n+1]
- local ntg=nodes[n+2]
- ok=(not ntg or ltg==ntg) and (not nns or lns==nns)
- if ok then
- break
- end
- end
- if directive then
- if ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- elseif not ok then
- local llp=ll.__p__;if llp~=p then p=llp;m=1 else m=m+1 end
- c=c+1
- collected[c]=ll
- ll.mi=m
- end
- end
- end
- return collected
- end
-end
-local quit_expression=false
-local function apply_expression(list,expression,order)
- local collected={}
- local c=0
- quit_expression=false
- for l=1,#list do
- local ll=list[l]
- if expression(list,ll,l,order) then
- c=c+1
- collected[c]=ll
- end
- if quit_expression then
- break
- end
- end
- return collected
-end
-local function apply_selector(list,specification)
- if xml.applyselector then
- apply_selector=xml.applyselector
- return apply_selector(list,specification)
- else
- return list
- end
-end
-local P,V,C,Cs,Cc,Ct,R,S,Cg,Cb=lpeg.P,lpeg.V,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.Ct,lpeg.R,lpeg.S,lpeg.Cg,lpeg.Cb
-local spaces=S(" \n\r\t\f")^0
-local lp_space=S(" \n\r\t\f")
-local lp_any=P(1)
-local lp_noequal=P("!=")/"~="+P("<=")+P(">=")+P("==")
-local lp_doequal=P("=")/"=="
-local lp_or=P("|")/" or "
-local lp_and=P("&")/" and "
-local builtin={
- text="(ll.dt[1] or '')",
- content="ll.dt",
- name="((ll.ns~='' and ll.ns..':'..ll.tg) or ll.tg)",
- tag="ll.tg",
- position="l",
- firstindex="1",
- firstelement="1",
- first="1",
- lastindex="(#ll.__p__.dt or 1)",
- lastelement="(ll.__p__.en or 1)",
- last="#list",
- list="list",
- self="ll",
- rootposition="order",
- order="order",
- element="(ll.ei or 1)",
- index="(ll.ni or 1)",
- match="(ll.mi or 1)",
- namespace="ll.ns",
- ns="ll.ns",
-}
-local lp_builtin=lpeg.utfchartabletopattern(builtin)/builtin*((spaces*P("(")*spaces*P(")"))/"")
-local lp_attribute=(P("@")+P("attribute::"))/""*Cc("(ll.at and ll.at['")*((R("az","AZ")+S("-_:"))^1)*Cc("'])")
-local lp_fastpos_p=P("+")^0*R("09")^1*P(-1)/"l==%0"
-local lp_fastpos_n=P("-")*R("09")^1*P(-1)/"(%0<0 and (#list+%0+1==l))"
-local lp_fastpos=lp_fastpos_n+lp_fastpos_p
-local lp_reserved=C("and")+C("or")+C("not")+C("div")+C("mod")+C("true")+C("false")
-local lp_lua_function=Cs((R("az","AZ","__")^1*(P(".")*R("az","AZ","__")^1)^1)*("("))/"%0"
-local lp_function=C(R("az","AZ","__")^1)*P("(")/function(t)
- if expressions[t] then
- return "expr."..t.."("
- else
- return "expr.error("
- end
-end
-local lparent=P("(")
-local rparent=P(")")
-local noparent=1-(lparent+rparent)
-local nested=P{lparent*(noparent+V(1))^0*rparent}
-local value=P(lparent*C((noparent+nested)^0)*rparent)
-local lp_child=Cc("expr.child(ll,'")*R("az","AZ")*R("az","AZ","--","__")^0*Cc("')")
-local lp_number=S("+-")*R("09")^1
-local lp_string=Cc("'")*R("az","AZ","--","__")^1*Cc("'")
-local lp_content=(P("'")*(1-P("'"))^0*P("'")+P('"')*(1-P('"'))^0*P('"'))
-local cleaner
-local lp_special=(C(P("name")+P("text")+P("tag")+P("count")+P("child")))*value/function(t,s)
- if expressions[t] then
- s=s and s~="" and lpegmatch(cleaner,s)
- if s and s~="" then
- return "expr."..t.."(ll,"..s..")"
- else
- return "expr."..t.."(ll)"
- end
- else
- return "expr.error("..t..")"
- end
-end
-local content=lp_builtin+lp_attribute+lp_special+lp_noequal+lp_doequal+lp_or+lp_and+lp_reserved+lp_lua_function+lp_function+lp_content+
- lp_child+lp_any
-local converter=Cs (
- lp_fastpos+(P { lparent*(V(1))^0*rparent+content } )^0
-)
-cleaner=Cs ((
- lp_reserved+lp_number+lp_string+1 )^1 )
-local template_e=[[
- local expr = xml.expressions
- return function(list,ll,l,order)
- return %s
- end
-]]
-local template_f_y=[[
- local finalizer = xml.finalizers['%s']['%s']
- return function(collection)
- return finalizer(collection,%s)
- end
-]]
-local template_f_n=[[
- return xml.finalizers['%s']['%s']
-]]
-local register_last_match={ kind="axis",axis="last-match" }
-local register_self={ kind="axis",axis="self" }
-local register_parent={ kind="axis",axis="parent" }
-local register_descendant={ kind="axis",axis="descendant" }
-local register_child={ kind="axis",axis="child" }
-local register_descendant_or_self={ kind="axis",axis="descendant-or-self" }
-local register_root={ kind="axis",axis="root" }
-local register_ancestor={ kind="axis",axis="ancestor" }
-local register_ancestor_or_self={ kind="axis",axis="ancestor-or-self" }
-local register_attribute={ kind="axis",axis="attribute" }
-local register_namespace={ kind="axis",axis="namespace" }
-local register_following={ kind="axis",axis="following" }
-local register_following_sibling={ kind="axis",axis="following-sibling" }
-local register_preceding={ kind="axis",axis="preceding" }
-local register_preceding_sibling={ kind="axis",axis="preceding-sibling" }
-local register_reverse_sibling={ kind="axis",axis="reverse-sibling" }
-local register_auto_descendant_or_self={ kind="axis",axis="auto-descendant-or-self" }
-local register_auto_descendant={ kind="axis",axis="auto-descendant" }
-local register_auto_self={ kind="axis",axis="auto-self" }
-local register_auto_child={ kind="axis",axis="auto-child" }
-local register_initial_child={ kind="axis",axis="initial-child" }
-local register_all_nodes={ kind="nodes",nodetest=true,nodes={ true,false,false } }
-local skip={}
-local function errorrunner_e(str,cnv)
- if not skip[str] then
- report_lpath("error in expression: %s => %s",str,cnv)
- skip[str]=cnv or str
- end
- return false
-end
-local function errorrunner_f(str,arg)
- report_lpath("error in finalizer: %s(%s)",str,arg or "")
- return false
-end
-local function register_nodes(nodetest,nodes)
- return { kind="nodes",nodetest=nodetest,nodes=nodes }
-end
-local function register_selector(specification)
- return { kind="selector",specification=specification }
-end
-local function register_expression(expression)
- local converted=lpegmatch(converter,expression)
- local wrapped=format(template_e,converted)
- local runner=load(wrapped)
- runner=(runner and runner()) or function() errorrunner_e(expression,converted) end
- return { kind="expression",expression=expression,converted=converted,evaluator=runner }
-end
-local function register_finalizer(protocol,name,arguments)
- local runner
- if arguments and arguments~="" then
- runner=load(format(template_f_y,protocol or xml.defaultprotocol,name,arguments))
- else
- runner=load(format(template_f_n,protocol or xml.defaultprotocol,name))
- end
- runner=(runner and runner()) or function() errorrunner_f(name,arguments) end
- return { kind="finalizer",name=name,arguments=arguments,finalizer=runner }
-end
-local expression=P { "ex",
- ex="["*C((V("sq")+V("dq")+(1-S("[]"))+V("ex"))^0)*"]",
- sq="'"*(1-S("'"))^0*"'",
- dq='"'*(1-S('"'))^0*'"',
-}
-local arguments=P { "ar",
- ar="("*Cs((V("sq")+V("dq")+V("nq")+P(1-P(")")))^0)*")",
- nq=((1-S("),'\""))^1)/function(s) return format("%q",s) end,
- sq=P("'")*(1-P("'"))^0*P("'"),
- dq=P('"')*(1-P('"'))^0*P('"'),
-}
-local function register_error(str)
- return { kind="error",error=format("unparsed: %s",str) }
-end
-local special_1=P("*")*Cc(register_auto_descendant)*Cc(register_all_nodes)
-local special_2=P("/")*Cc(register_auto_self)
-local special_3=P("")*Cc(register_auto_self)
-local no_nextcolon=P(-1)+#(1-P(":"))
-local no_nextlparent=P(-1)+#(1-P("("))
-local pathparser=Ct { "patterns",
- patterns=spaces*V("protocol")*spaces*(
- (V("special")*spaces*P(-1) )+(V("initial")*spaces*V("step")*spaces*(P("/")*spaces*V("step")*spaces)^0 )
- ),
- protocol=Cg(V("letters"),"protocol")*P("://")+Cg(Cc(nil),"protocol"),
- step=((V("shortcuts")+V("selector")+P("/")+V("axis"))*spaces*V("nodes")^0+V("error"))*spaces*V("expressions")^0*spaces*V("finalizer")^0,
- axis=V("last_match")+V("descendant")+V("child")+V("parent")+V("self")+V("root")+V("ancestor")+V("descendant_or_self")+V("following_sibling")+V("following")+V("reverse_sibling")+V("preceding_sibling")+V("preceding")+V("ancestor_or_self")+#(1-P(-1))*Cc(register_auto_child),
- special=special_1+special_2+special_3,
- initial=(P("/")*spaces*Cc(register_initial_child))^-1,
- error=(P(1)^1)/register_error,
- shortcuts_a=V("s_descendant_or_self")+V("s_descendant")+V("s_child")+V("s_parent")+V("s_self")+V("s_root")+V("s_ancestor")+V("s_lastmatch"),
- shortcuts=V("shortcuts_a")*(spaces*"/"*spaces*V("shortcuts_a"))^0,
- s_descendant_or_self=(P("***/")+P("/"))*Cc(register_descendant_or_self),
- s_descendant=P("**")*Cc(register_descendant),
- s_child=P("*")*no_nextcolon*Cc(register_child),
- s_parent=P("..")*Cc(register_parent),
- s_self=P("." )*Cc(register_self),
- s_root=P("^^")*Cc(register_root),
- s_ancestor=P("^")*Cc(register_ancestor),
- s_lastmatch=P("=")*Cc(register_last_match),
- descendant=P("descendant::")*Cc(register_descendant),
- child=P("child::")*Cc(register_child),
- parent=P("parent::")*Cc(register_parent),
- self=P("self::")*Cc(register_self),
- root=P('root::')*Cc(register_root),
- ancestor=P('ancestor::')*Cc(register_ancestor),
- descendant_or_self=P('descendant-or-self::')*Cc(register_descendant_or_self),
- ancestor_or_self=P('ancestor-or-self::')*Cc(register_ancestor_or_self),
- following=P('following::')*Cc(register_following),
- following_sibling=P('following-sibling::')*Cc(register_following_sibling),
- preceding=P('preceding::')*Cc(register_preceding),
- preceding_sibling=P('preceding-sibling::')*Cc(register_preceding_sibling),
- reverse_sibling=P('reverse-sibling::')*Cc(register_reverse_sibling),
- last_match=P('last-match::')*Cc(register_last_match),
- selector=P("{")*C((1-P("}"))^1)*P("}")/register_selector,
- nodes=(V("nodefunction")*spaces*P("(")*V("nodeset")*P(")")+V("nodetest")*V("nodeset"))/register_nodes,
- expressions=expression/register_expression,
- letters=R("az")^1,
- name=(1-S("/[]()|:*!"))^1,
- negate=P("!")*Cc(false),
- nodefunction=V("negate")+P("not")*Cc(false)+Cc(true),
- nodetest=V("negate")+Cc(true),
- nodename=(V("negate")+Cc(true))*spaces*((V("wildnodename")*P(":")*V("wildnodename"))+(Cc(false)*V("wildnodename"))),
- wildnodename=(C(V("name"))+P("*")*Cc(false))*no_nextlparent,
- nodeset=spaces*Ct(V("nodename")*(spaces*P("|")*spaces*V("nodename"))^0)*spaces,
- finalizer=(Cb("protocol")*P("/")^-1*C(V("name"))*arguments*P(-1))/register_finalizer,
-}
-xmlpatterns.pathparser=pathparser
-local cache={}
-local function nodesettostring(set,nodetest)
- local t={}
- for i=1,#set,3 do
- local directive,ns,tg=set[i],set[i+1],set[i+2]
- if not ns or ns=="" then ns="*" end
- if not tg or tg=="" then tg="*" end
- tg=(tg=="@rt@" and "[root]") or format("%s:%s",ns,tg)
- t[#t+1]=(directive and tg) or format("not(%s)",tg)
- end
- if nodetest==false then
- return format("not(%s)",concat(t,"|"))
- else
- return concat(t,"|")
- end
-end
-local function tagstostring(list)
- if #list==0 then
- return "no elements"
- else
- local t={}
- for i=1,#list do
- local li=list[i]
- local ns=li.ns
- local tg=li.tg
- if not ns or ns=="" then ns="*" end
- if not tg or tg=="" then tg="*" end
- t[i]=(tg=="@rt@" and "[root]") or format("%s:%s",ns,tg)
- end
- return concat(t," ")
- end
-end
-xml.nodesettostring=nodesettostring
-local lpath
-local function lshow(parsed)
- if type(parsed)=="string" then
- parsed=lpath(parsed)
- end
- report_lpath("%s://%s => %s",parsed.protocol or xml.defaultprotocol,parsed.pattern,
- table.serialize(parsed,false))
-end
-xml.lshow=lshow
-local function add_comment(p,str)
- local pc=p.comment
- if not pc then
- p.comment={ str }
- else
- pc[#pc+1]=str
- end
-end
-lpath=function (pattern)
- lpathcalls=lpathcalls+1
- if type(pattern)=="table" then
- return pattern
- else
- local parsed=cache[pattern]
- if parsed then
- lpathcached=lpathcached+1
- else
- parsed=lpegmatch(pathparser,pattern)
- if parsed then
- parsed.pattern=pattern
- local np=#parsed
- if np==0 then
- parsed={ pattern=pattern,register_self,state="parsing error" }
- report_lpath("parsing error in pattern: %s",pattern)
- lshow(parsed)
- else
- local pi=parsed[1]
- if pi.axis=="auto-child" then
- if false then
- add_comment(parsed,"auto-child replaced by auto-descendant-or-self")
- parsed[1]=register_auto_descendant_or_self
- else
- add_comment(parsed,"auto-child replaced by auto-descendant")
- parsed[1]=register_auto_descendant
- end
- elseif pi.axis=="initial-child" and np>1 and parsed[2].axis then
- add_comment(parsed,"initial-child removed")
- remove(parsed,1)
- end
- local np=#parsed
- if np>1 then
- local pnp=parsed[np]
- if pnp.kind=="nodes" and pnp.nodetest==true then
- local nodes=pnp.nodes
- if nodes[1]==true and nodes[2]==false and nodes[3]==false then
- add_comment(parsed,"redundant final wildcard filter removed")
- remove(parsed,np)
- end
- end
- end
- end
- else
- parsed={ pattern=pattern }
- end
- cache[pattern]=parsed
- if trace_lparse and not trace_lprofile then
- lshow(parsed)
- end
- end
- return parsed
- end
-end
-xml.lpath=lpath
-do
- local profiled={}
- xml.profiled=profiled
- local lastmatch=nil
- local keepmatch=nil
- if directives then
- directives.register("xml.path.keeplastmatch",function(v)
- keepmatch=v
- lastmatch=nil
- end)
- end
- apply_axis["last-match"]=function()
- return lastmatch or {}
- end
- local function profiled_apply(list,parsed,nofparsed,order)
- local p=profiled[parsed.pattern]
- if p then
- p.tested=p.tested+1
- else
- p={ tested=1,matched=0,finalized=0 }
- profiled[parsed.pattern]=p
- end
- local collected=list
- for i=1,nofparsed do
- local pi=parsed[i]
- local kind=pi.kind
- if kind=="axis" then
- collected=apply_axis[pi.axis](collected)
- elseif kind=="nodes" then
- collected=apply_nodes(collected,pi.nodetest,pi.nodes)
- elseif kind=="expression" then
- collected=apply_expression(collected,pi.evaluator,order)
- elseif kind=="selector" then
- collected=apply_selector(collected,pi.specification)
- elseif kind=="finalizer" then
- collected=pi.finalizer(collected)
- p.matched=p.matched+1
- p.finalized=p.finalized+1
- return collected
- end
- if not collected or #collected==0 then
- local pn=i<nofparsed and parsed[nofparsed]
- if pn and pn.kind=="finalizer" then
- collected=pn.finalizer(collected)
- p.finalized=p.finalized+1
- return collected
- end
- return nil
- end
- end
- if collected then
- p.matched=p.matched+1
- end
- return collected
- end
- local function traced_apply(list,parsed,nofparsed,order)
- if trace_lparse then
- lshow(parsed)
- end
- report_lpath("collecting: %s",parsed.pattern)
- report_lpath("root tags : %s",tagstostring(list))
- report_lpath("order : %s",order or "unset")
- local collected=list
- for i=1,nofparsed do
- local pi=parsed[i]
- local kind=pi.kind
- if kind=="axis" then
- collected=apply_axis[pi.axis](collected)
- report_lpath("% 10i : ax : %s",(collected and #collected) or 0,pi.axis)
- elseif kind=="nodes" then
- collected=apply_nodes(collected,pi.nodetest,pi.nodes)
- report_lpath("% 10i : ns : %s",(collected and #collected) or 0,nodesettostring(pi.nodes,pi.nodetest))
- elseif kind=="expression" then
- collected=apply_expression(collected,pi.evaluator,order)
- report_lpath("% 10i : ex : %s -> %s",(collected and #collected) or 0,pi.expression,pi.converted)
- elseif kind=="selector" then
- collected=apply_selector(collected,pi.specification)
- report_lpath("% 10i : se : %s ",(collected and #collected) or 0,pi.specification)
- elseif kind=="finalizer" then
- collected=pi.finalizer(collected)
- report_lpath("% 10i : fi : %s : %s(%s)",(type(collected)=="table" and #collected) or 0,parsed.protocol or xml.defaultprotocol,pi.name,pi.arguments or "")
- return collected
- end
- if not collected or #collected==0 then
- local pn=i<nofparsed and parsed[nofparsed]
- if pn and pn.kind=="finalizer" then
- collected=pn.finalizer(collected)
- report_lpath("% 10i : fi : %s : %s(%s)",(type(collected)=="table" and #collected) or 0,parsed.protocol or xml.defaultprotocol,pn.name,pn.arguments or "")
- return collected
- end
- return nil
- end
- end
- return collected
- end
- local function normal_apply(list,parsed,nofparsed,order)
- local collected=list
- for i=1,nofparsed do
- local pi=parsed[i]
- local kind=pi.kind
- if kind=="axis" then
- local axis=pi.axis
- if axis~="self" then
- collected=apply_axis[axis](collected)
- end
- elseif kind=="nodes" then
- collected=apply_nodes(collected,pi.nodetest,pi.nodes)
- elseif kind=="expression" then
- collected=apply_expression(collected,pi.evaluator,order)
- elseif kind=="selector" then
- collected=apply_selector(collected,pi.specification)
- elseif kind=="finalizer" then
- return pi.finalizer(collected)
- end
- if not collected or #collected==0 then
- local pf=i<nofparsed and parsed[nofparsed].finalizer
- if pf then
- return pf(collected)
- end
- return nil
- end
- end
- return collected
- end
- local apply=normal_apply
- if trackers then
- trackers.register("xml.path,xml.parse,xml.profile",function()
- if trace_lprofile then
- apply=profiled_apply
- elseif trace_lpath then
- apply=traced_apply
- else
- apply=normal_apply
- end
- end)
- end
- function xml.applylpath(list,pattern)
- if not list then
- lastmatch=nil
- return
- end
- local parsed=cache[pattern]
- if parsed then
- lpathcalls=lpathcalls+1
- lpathcached=lpathcached+1
- elseif type(pattern)=="table" then
- lpathcalls=lpathcalls+1
- parsed=pattern
- else
- parsed=lpath(pattern) or pattern
- end
- if not parsed then
- lastmatch=nil
- return
- end
- local nofparsed=#parsed
- if nofparsed==0 then
- lastmatch=nil
- return
- end
- local collected=apply({ list },parsed,nofparsed,list.mi)
- lastmatch=keepmatch and collected or nil
- return collected
- end
- function xml.lastmatch()
- return lastmatch
- end
- local stack={}
- function xml.pushmatch()
- insert(stack,lastmatch)
- end
- function xml.popmatch()
- lastmatch=remove(stack)
- end
-end
-local applylpath=xml.applylpath
-function xml.filter(root,pattern)
- return applylpath(root,pattern)
-end
-expressions.child=function(e,pattern)
- return applylpath(e,pattern)
-end
-expressions.count=function(e,pattern)
- local collected=applylpath(e,pattern)
- return pattern and (collected and #collected) or 0
-end
-expressions.attribute=function(e,name,value)
- if type(e)=="table" and name then
- local a=e.at
- if a then
- local v=a[name]
- if value then
- return v==value
- else
- return v
- end
- end
- end
- return nil
-end
-expressions.oneof=function(s,...)
- for i=1,select("#",...) do
- if s==select(i,...) then
- return true
- end
- end
- return false
-end
-expressions.error=function(str)
- xml.errorhandler(format("unknown function in lpath expression: %s",tostring(str or "?")))
- return false
-end
-expressions.undefined=function(s)
- return s==nil
-end
-expressions.quit=function(s)
- if s or s==nil then
- quit_expression=true
- end
- return true
-end
-expressions.print=function(...)
- print(...)
- return true
-end
-expressions.find=find
-expressions.upper=upper
-expressions.lower=lower
-expressions.number=tonumber
-expressions.boolean=toboolean
-function expressions.contains(str,pattern)
- local t=type(str)
- if t=="string" then
- if find(str,pattern) then
- return true
- end
- elseif t=="table" then
- for i=1,#str do
- local d=str[i]
- if type(d)=="string" and find(d,pattern) then
- return true
- end
- end
- end
- return false
-end
-function expressions.idstring(str)
- return type(str)=="string" and gsub(str,"^#","") or ""
-end
-local function traverse(root,pattern,handle)
- local collected=applylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local r=e.__p__
- handle(r,r.dt,e.ni)
- end
- end
-end
-local function selection(root,pattern,handle)
- local collected=applylpath(root,pattern)
- if collected then
- if handle then
- for c=1,#collected do
- handle(collected[c])
- end
- else
- return collected
- end
- end
-end
-xml.traverse=traverse
-xml.selection=selection
-local function dofunction(collected,fnc,...)
- if collected then
- local f=functions[fnc]
- if f then
- for c=1,#collected do
- f(collected[c],...)
- end
- else
- report_lpath("unknown function %a",fnc)
- end
- end
-end
-finalizers.xml["function"]=dofunction
-finalizers.tex["function"]=dofunction
-expressions.text=function(e,n)
- local rdt=e.__p__.dt
- return rdt and rdt[n] or ""
-end
-expressions.name=function(e,n)
- local found=false
- n=tonumber(n) or 0
- if n==0 then
- found=type(e)=="table" and e
- elseif n<0 then
- local d=e.__p__.dt
- local k=e.ni
- for i=k-1,1,-1 do
- local di=d[i]
- if type(di)=="table" then
- if n==-1 then
- found=di
- break
- else
- n=n+1
- end
- end
- end
- else
- local d=e.__p__.dt
- local k=e.ni
- for i=k+1,#d,1 do
- local di=d[i]
- if type(di)=="table" then
- if n==1 then
- found=di
- break
- else
- n=n-1
- end
- end
- end
- end
- if found then
- local ns=found.rn or found.ns or ""
- local tg=found.tg
- if ns~="" then
- return ns..":"..tg
- else
- return tg
- end
- else
- return ""
- end
-end
-expressions.tag=function(e,n)
- if not e then
- return ""
- else
- local found=false
- n=tonumber(n) or 0
- if n==0 then
- found=(type(e)=="table") and e
- elseif n<0 then
- local d=e.__p__.dt
- local k=e.ni
- for i=k-1,1,-1 do
- local di=d[i]
- if type(di)=="table" then
- if n==-1 then
- found=di
- break
- else
- n=n+1
- end
- end
- end
- else
- local d=e.__p__.dt
- local k=e.ni
- for i=k+1,#d,1 do
- local di=d[i]
- if type(di)=="table" then
- if n==1 then
- found=di
- break
- else
- n=n-1
- end
- end
- end
- end
- return (found and found.tg) or ""
- end
-end
-local dummy=function() end
-function xml.elements(root,pattern,reverse)
- local collected=applylpath(root,pattern)
- if not collected then
- return dummy
- end
- local n=#collected
- if n==0 then
- return dummy
- end
- if reverse then
- local c=n+1
- return function()
- if c>1 then
- c=c-1
- local e=collected[c]
- local r=e.__p__
- return r,r.dt,e.ni
- end
- end
- else
- local c=0
- return function()
- if c<n then
- c=c+1
- local e=collected[c]
- local r=e.__p__
- return r,r.dt,e.ni
- end
- end
- end
-end
-function xml.collected(root,pattern,reverse)
- local collected=applylpath(root,pattern)
- if not collected then
- return dummy
- end
- local n=#collected
- if n==0 then
- return dummy
- end
- if reverse then
- local c=n+1
- return function()
- if c>1 then
- c=c-1
- return collected[c]
- end
- end
- else
- local c=0
- return function()
- if c<n then
- c=c+1
- return collected[c]
- end
- end
- end
-end
-function xml.inspect(collection,pattern)
- pattern=pattern or "."
- for e in xml.collected(collection,pattern or ".") do
- report_lpath("pattern: %s\n\n%s\n",pattern,xml.tostring(e))
- end
-end
-local function split(e)
- local dt=e.dt
- if dt then
- for i=1,#dt do
- local dti=dt[i]
- if type(dti)=="string" then
- dti=gsub(dti,"^[\n\r]*(.-)[\n\r]*","%1")
- dti=gsub(dti,"[\n\r]+","\n\n")
- dt[i]=dti
- else
- split(dti)
- end
- end
- end
- return e
-end
-function xml.finalizers.paragraphs(c)
- for i=1,#c do
- split(c[i])
- end
- return c
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-mis"] = package.loaded["lxml-mis"] or true
-
--- original size: 3574, stripped down to: 1808
-
-if not modules then modules={} end modules ['lxml-mis']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local xml,lpeg,string=xml,lpeg,string
-local type=type
-local concat=table.concat
-local format,gsub,match=string.format,string.gsub,string.match
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local P,S,R,C,V,Cc,Cs=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.V,lpeg.Cc,lpeg.Cs
-lpegpatterns.xml=lpegpatterns.xml or {}
-local xmlpatterns=lpegpatterns.xml
-local function xmlgsub(t,old,new)
- local dt=t.dt
- if dt then
- for k=1,#dt do
- local v=dt[k]
- if type(v)=="string" then
- dt[k]=gsub(v,old,new)
- else
- xmlgsub(v,old,new)
- end
- end
- end
-end
-function xml.stripleadingspaces(dk,d,k)
- if d and k then
- local dkm=d[k-1]
- if dkm and type(dkm)=="string" then
- local s=match(dkm,"\n(%s+)")
- xmlgsub(dk,"\n"..rep(" ",#s),"\n")
- end
- end
-end
-local normal=(1-S("<&>"))^0
-local special=P("<")/"&lt;"+P(">")/"&gt;"+P("&")/"&amp;"
-local escaped=Cs(normal*(special*normal)^0)
-local normal=(1-S"&")^0
-local special=P("&lt;")/"<"+P("&gt;")/">"+P("&amp;")/"&"
-local unescaped=Cs(normal*(special*normal)^0)
-local cleansed=Cs(((P("<")*(1-P(">"))^0*P(">"))/""+1)^0)
-xmlpatterns.escaped=escaped
-xmlpatterns.unescaped=unescaped
-xmlpatterns.cleansed=cleansed
-function xml.escaped (str) return lpegmatch(escaped,str) end
-function xml.unescaped(str) return lpegmatch(unescaped,str) end
-function xml.cleansed (str) return lpegmatch(cleansed,str) end
-function xml.fillin(root,pattern,str,check)
- local e=xml.first(root,pattern)
- if e then
- local n=#e.dt
- if not check or n==0 or (n==1 and e.dt[1]=="") then
- e.dt={ str }
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-aux"] = package.loaded["lxml-aux"] or true
-
--- original size: 33708, stripped down to: 20953
-
-if not modules then modules={} end modules ['lxml-aux']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local trace_manipulations=false trackers.register("lxml.manipulations",function(v) trace_manipulations=v end)
-local trace_inclusions=false trackers.register("lxml.inclusions",function(v) trace_inclusions=v end)
-local report_xml=logs.reporter("xml")
-local xml=xml
-local xmlcopy,xmlname=xml.copy,xml.name
-local xmlinheritedconvert=xml.inheritedconvert
-local xmlapplylpath=xml.applylpath
-local type,next,setmetatable,getmetatable=type,next,setmetatable,getmetatable
-local insert,remove,fastcopy,concat=table.insert,table.remove,table.fastcopy,table.concat
-local gmatch,gsub,format,find,strip,match=string.gmatch,string.gsub,string.format,string.find,string.strip,string.match
-local utfbyte=utf.byte
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local striplinepatterns=utilities.strings.striplinepatterns
-local function report(what,pattern,c,e)
- report_xml("%s element %a, root %a, position %a, index %a, pattern %a",what,xmlname(e),xmlname(e.__p__),c,e.ni,pattern)
-end
-local function withelements(e,handle,depth)
- if e and handle then
- local edt=e.dt
- if edt then
- depth=depth or 0
- for i=1,#edt do
- local e=edt[i]
- if type(e)=="table" then
- handle(e,depth)
- withelements(e,handle,depth+1)
- end
- end
- end
- end
-end
-xml.withelements=withelements
-function xml.withelement(e,n,handle)
- if e and n~=0 and handle then
- local edt=e.dt
- if edt then
- if n>0 then
- for i=1,#edt do
- local ei=edt[i]
- if type(ei)=="table" then
- if n==1 then
- handle(ei)
- return
- else
- n=n-1
- end
- end
- end
- elseif n<0 then
- for i=#edt,1,-1 do
- local ei=edt[i]
- if type(ei)=="table" then
- if n==-1 then
- handle(ei)
- return
- else
- n=n+1
- end
- end
- end
- end
- end
- end
-end
-function xml.each(root,pattern,handle,reverse)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- if handle then
- if reverse then
- for c=#collected,1,-1 do
- handle(collected[c])
- end
- else
- for c=1,#collected do
- handle(collected[c])
- end
- end
- end
- return collected
- end
-end
-function xml.processattributes(root,pattern,handle)
- local collected=xmlapplylpath(root,pattern)
- if collected and handle then
- for c=1,#collected do
- handle(collected[c].at)
- end
- end
- return collected
-end
-function xml.collect(root,pattern)
- return xmlapplylpath(root,pattern)
-end
-function xml.collecttexts(root,pattern,flatten)
- local collected=xmlapplylpath(root,pattern)
- if collected and flatten then
- local xmltostring=xml.tostring
- for c=1,#collected do
- collected[c]=xmltostring(collected[c].dt)
- end
- end
- return collected or {}
-end
-function xml.collect_tags(root,pattern,nonamespace)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- local t={}
- local n=0
- for c=1,#collected do
- local e=collected[c]
- local ns=e.ns
- local tg=e.tg
- n=n+1
- if nonamespace then
- t[n]=tg
- elseif ns=="" then
- t[n]=tg
- else
- t[n]=ns..":"..tg
- end
- end
- return t
- end
-end
-local no_root={ no_root=true }
-local function redo_ni(d)
- for k=1,#d do
- local dk=d[k]
- if type(dk)=="table" then
- dk.ni=k
- end
- end
-end
-xml.reindex=redo_ni
-local function xmltoelement(whatever,root)
- if not whatever then
- return nil
- end
- local element
- if type(whatever)=="string" then
- element=xmlinheritedconvert(whatever,root,true)
- else
- element=whatever
- end
- if element.error then
- return whatever
- end
- if element then
- end
- return element
-end
-xml.toelement=xmltoelement
-local function copiedelement(element,newparent)
- if type(element)~="string" then
- element=xmlcopy(element).dt
- if newparent and type(element)=="table" then
- for i=1,#element do
- local e=element[i]
- if type(e)=="table" then
- e.__p__=newparent
- end
- end
- end
- end
- return element
-end
-function xml.delete(root,pattern)
- if not pattern or pattern=="" then
- local p=root.__p__
- if p then
- if trace_manipulations then
- report('deleting',"--",c,root)
- end
- local d=p.dt
- remove(d,root.ni)
- redo_ni(d)
- end
- else
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local p=e.__p__
- if p then
- if trace_manipulations then
- report('deleting',pattern,c,e)
- end
- local d=p.dt
- local ni=e.ni
- if ni<=#d then
- if false then
- p.dt[ni]=""
- else
- remove(d,ni)
- redo_ni(d)
- end
- else
- end
- end
- end
- end
- end
-end
-function xml.wipe(root,pattern)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local p=e.__p__
- if p then
- local d=p.dt
- local ni=e.ni
- if ni<=#d then
- local dt=e.dt
- if #dt==1 then
- local d1=dt[1]
- if type(d1)=="string" and match(d1,"^%s*$") then
- if trace_manipulations then
- report('wiping',pattern,c,e)
- end
- remove(d,ni)
- redo_ni(d)
- end
- end
- end
- end
- end
- end
-end
-function xml.replace(root,pattern,whatever)
- local element=root and xmltoelement(whatever,root)
- local collected=element and xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local p=e.__p__
- if p then
- if trace_manipulations then
- report('replacing',pattern,c,e)
- end
- local d=p.dt
- local n=e.ni
- local t=copiedelement(element,p)
- if type(t)=="table" then
- d[n]=t[1]
- for i=2,#t do
- n=n+1
- insert(d,n,t[i])
- end
- else
- d[n]=t
- end
- redo_ni(d)
- end
- end
- end
-end
-local function wrap(e,wrapper)
- local t={
- rn=e.rn,
- tg=e.tg,
- ns=e.ns,
- at=e.at,
- dt=e.dt,
- __p__=e,
- }
- setmetatable(t,getmetatable(e))
- e.rn=wrapper.rn or e.rn or ""
- e.tg=wrapper.tg or e.tg or ""
- e.ns=wrapper.ns or e.ns or ""
- e.at=fastcopy(wrapper.at)
- e.dt={ t }
-end
-function xml.wrap(root,pattern,whatever)
- if whatever then
- local wrapper=xmltoelement(whatever,root)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- if trace_manipulations then
- report('wrapping',pattern,c,e)
- end
- wrap(e,wrapper)
- end
- end
- else
- wrap(root,xmltoelement(pattern))
- end
-end
-local function inject_element(root,pattern,whatever,prepend)
- local element=root and xmltoelement(whatever,root)
- local collected=element and xmlapplylpath(root,pattern)
- local function inject_e(e)
- local r=e.__p__
- local d=r.dt
- local k=e.ni
- local rri=r.ri
- local edt=(rri and d[rri].dt) or (d and d[k] and d[k].dt)
- if edt then
- local be,af
- local cp=copiedelement(element,e)
- if prepend then
- be,af=cp,edt
- else
- be,af=edt,cp
- end
- local bn=#be
- for i=1,#af do
- bn=bn+1
- be[bn]=af[i]
- end
- if rri then
- r.dt[rri].dt=be
- else
- d[k].dt=be
- end
- redo_ni(d)
- end
- end
- if not collected then
- elseif collected.tg then
- inject_e(collected)
- else
- for c=1,#collected do
- inject_e(collected[c])
- end
- end
-end
-local function insert_element(root,pattern,whatever,before)
- local element=root and xmltoelement(whatever,root)
- local collected=element and xmlapplylpath(root,pattern)
- local function insert_e(e)
- local r=e.__p__
- local d=r.dt
- local k=e.ni
- if not before then
- k=k+1
- end
- insert(d,k,copiedelement(element,r))
- redo_ni(d)
- end
- if not collected then
- elseif collected.tg then
- insert_e(collected)
- else
- for c=1,#collected do
- insert_e(collected[c])
- end
- end
-end
-xml.insert_element=insert_element
-xml.insertafter=insert_element
-xml.insertbefore=function(r,p,e) insert_element(r,p,e,true) end
-xml.injectafter=inject_element
-xml.injectbefore=function(r,p,e) inject_element(r,p,e,true) end
-local function include(xmldata,pattern,attribute,recursive,loaddata,level)
- pattern=pattern or 'include'
- loaddata=loaddata or io.loaddata
- local collected=xmlapplylpath(xmldata,pattern)
- if collected then
- if not level then
- level=1
- end
- for c=1,#collected do
- local ek=collected[c]
- local name=nil
- local ekdt=ek.dt
- if ekdt then
- local ekat=ek.at
- local ekrt=ek.__p__
- if ekrt then
- local epdt=ekrt.dt
- if not attribute or attribute=="" then
- name=(type(ekdt)=="table" and ekdt[1]) or ekdt
- end
- if not name then
- for a in gmatch(attribute or "href","([^|]+)") do
- name=ekat[a]
- if name then
- break
- end
- end
- end
- local data=nil
- if name and name~="" then
- local d,n=loaddata(name)
- data=d or ""
- name=n or name
- if trace_inclusions then
- report_xml("including %s bytes from %a at level %s by pattern %a and attribute %a (%srecursing)",#data,name,level,pattern,attribute or "",recursive and "" or "not ")
- end
- end
- if not data or data=="" then
- epdt[ek.ni]=""
- elseif ekat["parse"]=="text" then
- epdt[ek.ni]=xml.escaped(data)
- else
- local settings=xmldata.settings
- local savedresource=settings.currentresource
- settings.currentresource=name
- local xi=xmlinheritedconvert(data,xmldata,true)
- if not xi then
- epdt[ek.ni]=""
- else
- if recursive then
- include(xi,pattern,attribute,recursive,loaddata,level+1)
- end
- local child=xml.body(xi)
- child.__p__=ekrt
- child.__f__=name
- child.cf=name
- epdt[ek.ni]=child
- local settings=xmldata.settings
- local inclusions=settings and settings.inclusions
- if inclusions then
- inclusions[#inclusions+1]=name
- elseif settings then
- settings.inclusions={ name }
- else
- settings={ inclusions={ name } }
- xmldata.settings=settings
- end
- if child.er then
- local badinclusions=settings.badinclusions
- if badinclusions then
- badinclusions[#badinclusions+1]=name
- else
- settings.badinclusions={ name }
- end
- end
- end
-settings.currentresource=savedresource
- end
- end
- end
- end
- end
-end
-xml.include=include
-function xml.inclusion(e,default)
- while e do
- local f=e.__f__
- if f then
- return f
- else
- e=e.__p__
- end
- end
- return default
-end
-local function getinclusions(key,e,sorted)
- while e do
- local settings=e.settings
- if settings then
- local inclusions=settings[key]
- if inclusions then
- inclusions=table.unique(inclusions)
- if sorted then
- table.sort(inclusions)
- end
- return inclusions
- else
- e=e.__p__
- end
- else
- e=e.__p__
- end
- end
-end
-function xml.inclusions(e,sorted)
- return getinclusions("inclusions",e,sorted)
-end
-function xml.badinclusions(e,sorted)
- return getinclusions("badinclusions",e,sorted)
-end
-local b_collapser=lpegpatterns.b_collapser
-local m_collapser=lpegpatterns.m_collapser
-local e_collapser=lpegpatterns.e_collapser
-local x_collapser=lpegpatterns.x_collapser
-local b_stripper=lpegpatterns.b_stripper
-local m_stripper=lpegpatterns.m_stripper
-local e_stripper=lpegpatterns.e_stripper
-local x_stripper=lpegpatterns.x_stripper
-local function stripelement(e,nolines,anywhere,everything)
- local edt=e.dt
- if edt then
- local n=#edt
- if n==0 then
- return e
- elseif everything then
- local t={}
- local m=0
- for i=1,n do
- local str=edt[i]
- if type(str)~="string" then
- m=m+1
- t[m]=str
- elseif str~="" then
- str=lpegmatch(x_collapser,str)
- if str~="" then
- m=m+1
- t[m]=str
- end
- end
- end
- e.dt=t
- elseif anywhere then
- local t={}
- local m=0
- for i=1,n do
- local str=edt[i]
- if type(str)~="string" then
- m=m+1
- t[m]=str
- elseif str~="" then
- if nolines then
- str=lpegmatch((i==1 and b_collapser) or (i==m and e_collapser) or m_collapser,str)
- else
- str=lpegmatch((i==1 and b_stripper) or (i==m and e_stripper) or m_stripper,str)
- end
- if str~="" then
- m=m+1
- t[m]=str
- end
- end
- end
- e.dt=t
- else
- local str=edt[1]
- if type(str)=="string" then
- if str~="" then
- str=lpegmatch(nolines and b_collapser or b_stripper,str)
- end
- if str=="" then
- remove(edt,1)
- n=n-1
- else
- edt[1]=str
- end
- end
- if n>0 then
- str=edt[n]
- if type(str)=="string" then
- if str=="" then
- remove(edt)
- else
- str=lpegmatch(nolines and e_collapser or e_stripper,str)
- if str=="" then
- remove(edt)
- else
- edt[n]=str
- end
- end
- end
- end
- end
- end
- return e
-end
-xml.stripelement=stripelement
-function xml.strip(root,pattern,nolines,anywhere,everything)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for i=1,#collected do
- stripelement(collected[i],nolines,anywhere,everything)
- end
- end
-end
-local function compactelement(e)
- local edt=e.dt
- if edt then
- for e=1,#edt do
- local str=edt[e]
- if type(str)=="string" and not find(str,"%S") then
- edt[e]=""
- end
- end
- end
- return e
-end
-xml.compactelement=compactelement
-local function renamespace(root,oldspace,newspace)
- local ndt=#root.dt
- for i=1,ndt or 0 do
- local e=root[i]
- if type(e)=="table" then
- if e.ns==oldspace then
- e.ns=newspace
- if e.rn then
- e.rn=newspace
- end
- end
- local edt=e.dt
- if edt then
- renamespace(edt,oldspace,newspace)
- end
- end
- end
-end
-xml.renamespace=renamespace
-function xml.remaptag(root,pattern,newtg)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- collected[c].tg=newtg
- end
- end
-end
-function xml.remapnamespace(root,pattern,newns)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- collected[c].ns=newns
- end
- end
-end
-function xml.checknamespace(root,pattern,newns)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- if (not e.rn or e.rn=="") and e.ns=="" then
- e.rn=newns
- end
- end
- end
-end
-function xml.remapname(root,pattern,newtg,newns,newrn)
- local collected=xmlapplylpath(root,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- e.tg,e.ns,e.rn=newtg,newns,newrn
- end
- end
-end
-function xml.cdatatotext(e)
- local dt=e.dt
- if #dt==1 then
- local first=dt[1]
- if first.tg=="@cd@" then
- e.dt=first.dt
- end
- else
- end
-end
-function xml.texttocdata(e)
- local dt=e.dt
- local s=xml.tostring(dt)
- e.tg="@cd@"
- e.special=true
- e.ns=""
- e.rn=""
- e.dt={ s }
- e.at=nil
-end
-function xml.elementtocdata(e)
- local dt=e.dt
- local s=xml.tostring(e)
- e.tg="@cd@"
- e.special=true
- e.ns=""
- e.rn=""
- e.dt={ s }
- e.at=nil
-end
-xml.builtinentities=table.tohash { "amp","quot","apos","lt","gt" }
-local entities=characters and characters.entities or nil
-local builtinentities=xml.builtinentities
-function xml.addentitiesdoctype(root,option)
- if not entities then
- require("char-ent")
- entities=characters.entities
- end
- if entities and root and root.tg=="@rt@" and root.statistics then
- local list={}
- local hexify=option=="hexadecimal"
- for k,v in table.sortedhash(root.statistics.entities.names) do
- if not builtinentities[k] then
- local e=entities[k]
- if not e then
- e=format("[%s]",k)
- elseif hexify then
- e=format("&#%05X;",utfbyte(k))
- end
- list[#list+1]=format(" <!ENTITY %s %q >",k,e)
- end
- end
- local dt=root.dt
- local n=dt[1].tg=="@pi@" and 2 or 1
- if #list>0 then
- insert(dt,n,{ "\n" })
- insert(dt,n,{
- tg="@dt@",
- dt={ format("Something [\n%s\n] ",concat(list)) },
- ns="",
- special=true,
- })
- insert(dt,n,{ "\n\n" })
- else
- end
- end
-end
-xml.all=xml.each
-xml.insert=xml.insertafter
-xml.inject=xml.injectafter
-xml.after=xml.insertafter
-xml.before=xml.insertbefore
-xml.process=xml.each
-xml.obsolete=xml.obsolete or {}
-local obsolete=xml.obsolete
-xml.strip_whitespace=xml.strip obsolete.strip_whitespace=xml.strip
-xml.collect_elements=xml.collect obsolete.collect_elements=xml.collect
-xml.delete_element=xml.delete obsolete.delete_element=xml.delete
-xml.replace_element=xml.replace obsolete.replace_element=xml.replace
-xml.each_element=xml.each obsolete.each_element=xml.each
-xml.process_elements=xml.process obsolete.process_elements=xml.process
-xml.insert_element_after=xml.insertafter obsolete.insert_element_after=xml.insertafter
-xml.insert_element_before=xml.insertbefore obsolete.insert_element_before=xml.insertbefore
-xml.inject_element_after=xml.injectafter obsolete.inject_element_after=xml.injectafter
-xml.inject_element_before=xml.injectbefore obsolete.inject_element_before=xml.injectbefore
-xml.process_attributes=xml.processattributes obsolete.process_attributes=xml.processattributes
-xml.collect_texts=xml.collecttexts obsolete.collect_texts=xml.collecttexts
-xml.inject_element=xml.inject obsolete.inject_element=xml.inject
-xml.remap_tag=xml.remaptag obsolete.remap_tag=xml.remaptag
-xml.remap_name=xml.remapname obsolete.remap_name=xml.remapname
-xml.remap_namespace=xml.remapnamespace obsolete.remap_namespace=xml.remapnamespace
-function xml.cdata(e)
- if e then
- local dt=e.dt
- if dt and #dt==1 then
- local first=dt[1]
- return first.tg=="@cd@" and first.dt[1] or ""
- end
- end
- return ""
-end
-function xml.finalizers.xml.cdata(collected)
- if collected then
- local e=collected[1]
- if e then
- local dt=e.dt
- if dt and #dt==1 then
- local first=dt[1]
- return first.tg=="@cd@" and first.dt[1] or ""
- end
- end
- end
- return ""
-end
-function xml.insertcomment(e,str,n)
- insert(e.dt,n or 1,{
- tg="@cm@",
- ns="",
- special=true,
- at={},
- dt={ str },
- })
-end
-function xml.insertcdata(e,str,n)
- insert(e.dt,n or 1,{
- tg="@cd@",
- ns="",
- special=true,
- at={},
- dt={ str },
- })
-end
-function xml.setcomment(e,str,n)
- e.dt={ {
- tg="@cm@",
- ns="",
- special=true,
- at={},
- dt={ str },
- } }
-end
-function xml.setcdata(e,str)
- e.dt={ {
- tg="@cd@",
- ns="",
- special=true,
- at={},
- dt={ str },
- } }
-end
-function xml.separate(x,pattern)
- local collected=xmlapplylpath(x,pattern)
- if collected then
- for c=1,#collected do
- local e=collected[c]
- local d=e.dt
- if d==x then
- report_xml("warning: xml.separate changes root")
- x=d
- end
- local t={ "\n" }
- local n=1
- local i=1
- local nd=#d
- while i<=nd do
- while i<=nd do
- local di=d[i]
- if type(di)=="string" then
- if di=="\n" or find(di,"^%s+$") then
- i=i+1
- else
- d[i]=strip(di)
- break
- end
- else
- break
- end
- end
- if i>nd then
- break
- end
- t[n+1]="\n"
- t[n+2]=d[i]
- t[n+3]="\n"
- n=n+3
- i=i+1
- end
- t[n+1]="\n"
- setmetatable(t,getmetatable(d))
- e.dt=t
- end
- end
- return x
-end
-local helpers=xml.helpers or {}
-xml.helpers=helpers
-local function normal(e,action)
- local edt=e.dt
- if edt then
- for i=1,#edt do
- local str=edt[i]
- if type(str)=="string" and str~="" then
- edt[i]=action(str)
- end
- end
- end
-end
-local function recurse(e,action)
- local edt=e.dt
- if edt then
- for i=1,#edt do
- local str=edt[i]
- if type(str)~="string" then
- recurse(str,action)
- elseif str~="" then
- edt[i]=action(str)
- end
- end
- end
-end
-function helpers.recursetext(collected,action,recursive)
- if recursive then
- for i=1,#collected do
- recurse(collected[i],action)
- end
- else
- for i=1,#collected do
- normal(collected[i],action)
- end
- end
-end
-local specials={
- ["@rt@"]="root",
- ["@pi@"]="instruction",
- ["@cm@"]="comment",
- ["@dt@"]="declaration",
- ["@cd@"]="cdata",
-}
-local function convert(x,strip,flat)
- local ns=x.ns
- local tg=x.tg
- local at=x.at
- local dt=x.dt
- local node=flat and {
- [0]=(not x.special and (ns~="" and ns..":"..tg or tg)) or nil,
- } or {
- _namespace=ns~="" and ns or nil,
- _tag=not x.special and tg or nil,
- _type=specials[tg] or "_element",
- }
- if at then
- for k,v in next,at do
- node[k]=v
- end
- end
- local n=0
- for i=1,#dt do
- local di=dt[i]
- if type(di)=="table" then
- if flat and di.special then
- else
- di=convert(di,strip,flat)
- if di then
- n=n+1
- node[n]=di
- end
- end
- elseif strip then
- di=lpegmatch(strip,di)
- if di~="" then
- n=n+1
- node[n]=di
- end
- else
- n=n+1
- node[n]=di
- end
- end
- if next(node) then
- return node
- end
-end
-function xml.totable(x,strip,flat)
- if type(x)=="table" then
- if strip then
- strip=striplinepatterns[strip]
- end
- return convert(x,strip,flat)
- end
-end
-function xml.rename(e,namespace,name,attributes)
- if type(e)~="table" or not e.tg then
- return
- end
- if type(name)=="table" then
- attributes=name
- name=namespace
- namespace=""
- elseif type(name)~="string" then
- attributes={}
- name=namespace
- namespace=""
- end
- if type(attributes)~="table" then
- attributes={}
- end
- e.ns=namespace
- e.rn=namespace
- e.tg=name
- e.at=attributes
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["lxml-xml"] = package.loaded["lxml-xml"] or true
-
--- original size: 11096, stripped down to: 7702
-
-if not modules then modules={} end modules ['lxml-xml']={
- version=1.001,
- comment="this module is the basis for the lxml-* ones",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local tonumber,next=tonumber,next
-local concat=table.concat
-local find,lower,upper=string.find,string.lower,string.upper
-local xml=xml
-local finalizers=xml.finalizers.xml
-local xmlfilter=xml.filter
-local xmltostring=xml.tostring
-local xmlserialize=xml.serialize
-local xmlcollected=xml.collected
-local xmlnewhandlers=xml.newhandlers
-local reparsedentity=xml.reparsedentitylpeg
-local unescapedentity=xml.unescapedentitylpeg
-local parsedentity=reparsedentity
-local function first(collected)
- return collected and collected[1]
-end
-local function last(collected)
- return collected and collected[#collected]
-end
-local function all(collected)
- return collected
-end
-local reverse=table.reversed
-local function attribute(collected,name)
- if collected and #collected>0 then
- local at=collected[1].at
- return at and at[name]
- end
-end
-local function att(id,name)
- local at=id.at
- return at and at[name]
-end
-local function count(collected)
- return collected and #collected or 0
-end
-local function position(collected,n)
- if not collected then
- return 0
- end
- local nc=#collected
- if nc==0 then
- return 0
- end
- n=tonumber(n) or 0
- if n<0 then
- return collected[nc+n+1]
- elseif n>0 then
- return collected[n]
- else
- return collected[1].mi or 0
- end
-end
-local function match(collected)
- return collected and #collected>0 and collected[1].mi or 0
-end
-local function index(collected)
- return collected and #collected>0 and collected[1].ni or 0
-end
-local function attributes(collected,arguments)
- if collected and #collected>0 then
- local at=collected[1].at
- if arguments then
- return at[arguments]
- elseif next(at) then
- return at
- end
- end
-end
-local function chainattribute(collected,arguments)
- if collected and #collected>0 then
- local e=collected[1]
- while e do
- local at=e.at
- if at then
- local a=at[arguments]
- if a then
- return a
- end
- else
- break
- end
- e=e.__p__
- end
- end
- return ""
-end
-local function raw(collected)
- if collected and #collected>0 then
- local e=collected[1] or collected
- return e and xmltostring(e) or ""
- else
- return ""
- end
-end
-local xmltexthandler=xmlnewhandlers {
- name="string",
- initialize=function()
- result={}
- return result
- end,
- finalize=function()
- return concat(result)
- end,
- handle=function(...)
- result[#result+1]=concat {... }
- end,
- escape=false,
-}
-local function xmltotext(root)
- local dt=root.dt
- if not dt then
- return ""
- end
- local nt=#dt
- if nt==0 then
- return ""
- elseif nt==1 and type(dt[1])=="string" then
- return dt[1]
- else
- return xmlserialize(root,xmltexthandler) or ""
- end
-end
-function xml.serializetotext(root)
- return root and xmlserialize(root,xmltexthandler) or ""
-end
-local function text(collected)
- if collected then
- local e=collected[1] or collected
- return e and xmltotext(e) or ""
- else
- return ""
- end
-end
-local function texts(collected)
- if not collected then
- return {}
- end
- local nc=#collected
- if nc==0 then
- return {}
- end
- local t,n={},0
- for c=1,nc do
- local e=collected[c]
- if e and e.dt then
- n=n+1
- t[n]=e.dt
- end
- end
- return t
-end
-local function tag(collected,n)
- if not collected then
- return
- end
- local nc=#collected
- if nc==0 then
- return
- end
- local c
- if n==0 or not n then
- c=collected[1]
- elseif n>1 then
- c=collected[n]
- else
- c=collected[nc-n+1]
- end
- return c and c.tg
-end
-local function name(collected,n)
- if not collected then
- return
- end
- local nc=#collected
- if nc==0 then
- return
- end
- local c
- if n==0 or not n then
- c=collected[1]
- elseif n>1 then
- c=collected[n]
- else
- c=collected[nc-n+1]
- end
- if not c then
- elseif c.ns=="" then
- return c.tg
- else
- return c.ns..":"..c.tg
- end
-end
-local function tags(collected,nonamespace)
- if not collected then
- return
- end
- local nc=#collected
- if nc==0 then
- return
- end
- local t,n={},0
- for c=1,nc do
- local e=collected[c]
- local ns,tg=e.ns,e.tg
- n=n+1
- if nonamespace or ns=="" then
- t[n]=tg
- else
- t[n]=ns..":"..tg
- end
- end
- return t
-end
-local function empty(collected,spacesonly)
- if not collected then
- return true
- end
- local nc=#collected
- if nc==0 then
- return true
- end
- for c=1,nc do
- local e=collected[c]
- if e then
- local edt=e.dt
- if edt then
- local n=#edt
- if n==1 then
- local edk=edt[1]
- local typ=type(edk)
- if typ=="table" then
- return false
- elseif edk~="" then
- return false
- elseif spacesonly and not find(edk,"%S") then
- return false
- end
- elseif n>1 then
- return false
- end
- end
- end
- end
- return true
-end
-finalizers.first=first
-finalizers.last=last
-finalizers.all=all
-finalizers.reverse=reverse
-finalizers.elements=all
-finalizers.default=all
-finalizers.attribute=attribute
-finalizers.att=att
-finalizers.count=count
-finalizers.position=position
-finalizers.match=match
-finalizers.index=index
-finalizers.attributes=attributes
-finalizers.chainattribute=chainattribute
-finalizers.text=text
-finalizers.texts=texts
-finalizers.tag=tag
-finalizers.name=name
-finalizers.tags=tags
-finalizers.empty=empty
-function xml.first(id,pattern)
- return first(xmlfilter(id,pattern))
-end
-function xml.last(id,pattern)
- return last(xmlfilter(id,pattern))
-end
-function xml.count(id,pattern)
- return count(xmlfilter(id,pattern))
-end
-function xml.attribute(id,pattern,a,default)
- return attribute(xmlfilter(id,pattern),a,default)
-end
-function xml.raw(id,pattern)
- if pattern then
- return raw(xmlfilter(id,pattern))
- else
- return raw(id)
- end
-end
-function xml.text(id,pattern)
- if pattern then
- local collected=xmlfilter(id,pattern)
- return collected and #collected>0 and xmltotext(collected[1]) or ""
- elseif id then
- return xmltotext(id) or ""
- else
- return ""
- end
-end
-function xml.pure(id,pattern)
- if pattern then
- local collected=xmlfilter(id,pattern)
- if collected and #collected>0 then
- parsedentity=unescapedentity
- local s=collected and #collected>0 and xmltotext(collected[1]) or ""
- parsedentity=reparsedentity
- return s
- else
- return ""
- end
- else
- parsedentity=unescapedentity
- local s=xmltotext(id) or ""
- parsedentity=reparsedentity
- return s
- end
-end
-xml.content=text
-function xml.position(id,pattern,n)
- return position(xmlfilter(id,pattern),n)
-end
-function xml.match(id,pattern)
- return match(xmlfilter(id,pattern))
-end
-function xml.empty(id,pattern,spacesonly)
- return empty(xmlfilter(id,pattern),spacesonly)
-end
-xml.all=xml.filter
-xml.index=xml.position
-xml.found=xml.filter
-local function totable(x)
- local t={}
- for e in xmlcollected(x[1] or x,"/*") do
- t[e.tg]=xmltostring(e.dt) or ""
- end
- return next(t) and t or nil
-end
-xml.table=totable
-finalizers.table=totable
-local function textonly(e,t)
- if e then
- local edt=e.dt
- if edt then
- for i=1,#edt do
- local e=edt[i]
- if type(e)=="table" then
- textonly(e,t)
- else
- t[#t+1]=e
- end
- end
- end
- end
- return t
-end
-function xml.textonly(e)
- return concat(textonly(e,{}))
-end
-function finalizers.lowerall(collected)
- for c=1,#collected do
- local e=collected[c]
- if not e.special then
- e.tg=lower(e.tg)
- local eat=e.at
- if eat then
- local t={}
- for k,v in next,eat do
- t[lower(k)]=v
- end
- e.at=t
- end
- end
- end
-end
-function finalizers.upperall(collected)
- for c=1,#collected do
- local e=collected[c]
- if not e.special then
- e.tg=upper(e.tg)
- local eat=e.at
- if eat then
- local t={}
- for k,v in next,eat do
- t[upper(k)]=v
- end
- e.at=t
- end
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["trac-xml"] = package.loaded["trac-xml"] or true
-
--- original size: 6407, stripped down to: 4640
-
-if not modules then modules={} end modules ['trac-xml']={
- version=1.001,
- comment="companion to trac-log.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local formatters=string.formatters
-local reporters=logs.reporters
-local xmlserialize=xml.serialize
-local xmlcollected=xml.collected
-local xmltext=xml.text
-local xmlfirst=xml.first
-local function showhelp(specification,...)
- local root=xml.convert(specification.helpinfo or "")
- if not root then
- return
- end
- local xs=xml.gethandlers("string")
- xml.sethandlersfunction(xs,"short",function(e,handler) xmlserialize(e.dt,handler) end)
- xml.sethandlersfunction(xs,"ref",function(e,handler) handler.handle("--"..e.at.name) end)
- local wantedcategories=select("#",...)==0 and true or table.tohash {... }
- local nofcategories=xml.count(root,"/application/flags/category")
- local report=specification.report
- for category in xmlcollected(root,"/application/flags/category") do
- local categoryname=category.at.name or ""
- if wantedcategories==true or wantedcategories[categoryname] then
- if nofcategories>1 then
- report("%s options:",categoryname)
- report()
- end
- for subcategory in xmlcollected(category,"/subcategory") do
- for flag in xmlcollected(subcategory,"/flag") do
- local name=flag.at.name
- local value=flag.at.value
- local short=xmltext(xmlfirst(flag,"/short"))
- if value then
- report("--%-20s %s",formatters["%s=%s"](name,value),short)
- else
- report("--%-20s %s",name,short)
- end
- end
- report()
- end
- end
- end
- for category in xmlcollected(root,"/application/examples/category") do
- local title=xmltext(xmlfirst(category,"/title"))
- if title and title~="" then
- report()
- report(title)
- report()
- end
- for subcategory in xmlcollected(category,"/subcategory") do
- for example in xmlcollected(subcategory,"/example") do
- local command=xmltext(xmlfirst(example,"/command"))
- local comment=xmltext(xmlfirst(example,"/comment"))
- report(command)
- end
- report()
- end
- end
- for comment in xmlcollected(root,"/application/comments/comment") do
- local comment=xmltext(comment)
- report()
- report(comment)
- report()
- end
-end
-local reporthelp=reporters.help
-local exporthelp=reporters.export
-local function xmlfound(t)
- local helpinfo=t.helpinfo
- if type(helpinfo)=="table" then
- return false
- end
- if type(helpinfo)~="string" then
- helpinfo="Warning: no helpinfo found."
- t.helpinfo=helpinfo
- return false
- end
- if string.find(helpinfo,".xml$") then
- local ownscript=environment.ownscript
- local helpdata=false
- if ownscript then
- local helpfile=file.join(file.pathpart(ownscript),helpinfo)
- helpdata=io.loaddata(helpfile)
- if helpdata=="" then
- helpdata=false
- end
- end
- if not helpdata then
- local helpfile=resolvers.findfile(helpinfo,"tex")
- helpdata=helpfile and io.loaddata(helpfile)
- end
- if helpdata and helpdata~="" then
- helpinfo=helpdata
- else
- helpinfo=formatters["Warning: help file %a is not found."](helpinfo)
- end
- end
- t.helpinfo=helpinfo
- return string.find(t.helpinfo,"^<%?xml") and true or false
-end
-function reporters.help(t,...)
- if xmlfound(t) then
- showhelp(t,...)
- else
- reporthelp(t,...)
- end
-end
-function reporters.export(t,methods,filename)
- if not xmlfound(t) then
- return exporthelp(t)
- end
- if not methods or methods=="" then
- methods=environment.arguments["exporthelp"]
- end
- if not filename or filename=="" then
- filename=environment.files[1]
- end
- dofile(resolvers.findfile("trac-exp.lua","tex"))
- local exporters=logs.exporters
- if not exporters or not methods then
- return exporthelp(t)
- end
- if methods=="all" then
- methods=table.keys(exporters)
- elseif type(methods)=="string" then
- methods=utilities.parsers.settings_to_array(methods)
- else
- return exporthelp(t)
- end
- if type(filename)~="string" or filename=="" then
- filename=false
- elseif file.pathpart(filename)=="" then
- t.report("export file %a will not be saved on the current path (safeguard)",filename)
- return
- end
- for i=1,#methods do
- local method=methods[i]
- local exporter=exporters[method]
- if exporter then
- local result=exporter(t,method)
- if result and result~="" then
- if filename then
- local fullname=file.replacesuffix(filename,method)
- t.report("saving export in %a",fullname)
- dir.mkdirs(file.pathpart(fullname))
- io.savedata(fullname,result)
- else
- reporters.lines(t,result)
- end
- else
- t.report("no output from exporter %a",method)
- end
- else
- t.report("unknown exporter %a",method)
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-ini"] = package.loaded["data-ini"] or true
-
--- original size: 10947, stripped down to: 7176
-
-if not modules then modules={} end modules ['data-ini']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local next,type,getmetatable,rawset=next,type,getmetatable,rawset
-local gsub,find,gmatch,char=string.gsub,string.find,string.gmatch,string.char
-local filedirname,filebasename,filejoin=file.dirname,file.basename,file.join
-local ostype,osname,osuname,ossetenv,osgetenv=os.type,os.name,os.uname,os.setenv,os.getenv
-local sortedpairs=table.sortedpairs
-local P,S,R,C,Cs,Cc,lpegmatch=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.Cs,lpeg.Cc,lpeg.match
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local trace_expansions=false trackers.register("resolvers.expansions",function(v) trace_expansions=v end)
-local report_initialization=logs.reporter("resolvers","initialization")
-resolvers=resolvers or {}
-local resolvers=resolvers
-texconfig.kpse_init=false
-texconfig.shell_escape='t'
-if not (environment and environment.default_texmfcnf) and kpse and kpse.default_texmfcnf then
- local default_texmfcnf=kpse.default_texmfcnf()
- default_texmfcnf=gsub(default_texmfcnf,"$SELFAUTOLOC","selfautoloc:")
- default_texmfcnf=gsub(default_texmfcnf,"$SELFAUTODIR","selfautodir:")
- default_texmfcnf=gsub(default_texmfcnf,"$SELFAUTOPARENT","selfautoparent:")
- default_texmfcnf=gsub(default_texmfcnf,"$HOME","home:")
- environment.default_texmfcnf=default_texmfcnf
-end
-kpse={ original=kpse }
-setmetatable(kpse,{
- __index=function(kp,name)
- report_initialization("fatal error: kpse library is accessed (key: %s)",name)
- os.exit()
- end
-} )
-do
- local osfontdir=osgetenv("OSFONTDIR")
- if osfontdir and osfontdir~="" then
- elseif osname=="windows" then
- ossetenv("OSFONTDIR","c:/windows/fonts//")
- elseif osname=="macosx" then
- ossetenv("OSFONTDIR","$HOME/Library/Fonts//;/Library/Fonts//;/System/Library/Fonts//")
- end
-end
-if not environment.homedir then
- local oldhome=osgetenv('HOME')
- local homedir=osgetenv(ostype=="windows" and 'USERPROFILE' or 'HOME') or ''
- if not homedir or homedir=="" then
- homedir=char(127)
- end
- homedir=file.collapsepath(homedir)
- ossetenv("HOME",homedir)
- ossetenv("USERPROFILE",homedir)
- environment.oldhome=oldhome
- environment.homedir=homedir
-end
-do
- local args=environment.originalarguments or arg
- if not environment.ownmain then
- environment.ownmain=status and string.match(string.lower(status.banner),"this is ([%a]+)") or "luatex"
- end
- local ownbin=environment.ownbin or args[-2] or arg[-2] or args[-1] or arg[-1] or arg[0] or "luatex"
- local ownpath=environment.ownpath or os.selfdir
- ownbin=file.collapsepath(ownbin)
- ownpath=file.collapsepath(ownpath)
- if not ownpath or ownpath=="" or ownpath=="unset" then
- ownpath=args[-1] or arg[-1]
- ownpath=ownpath and filedirname(gsub(ownpath,"\\","/"))
- if not ownpath or ownpath=="" then
- ownpath=args[-0] or arg[-0]
- ownpath=ownpath and filedirname(gsub(ownpath,"\\","/"))
- end
- local binary=ownbin
- if not ownpath or ownpath=="" then
- ownpath=ownpath and filedirname(binary)
- end
- if not ownpath or ownpath=="" then
- if os.binsuffix~="" then
- binary=file.replacesuffix(binary,os.binsuffix)
- end
- local path=osgetenv("PATH")
- if path then
- for p in gmatch(path,"[^"..io.pathseparator.."]+") do
- local b=filejoin(p,binary)
- if lfs.isfile(b) then
- local olddir=lfs.currentdir()
- if lfs.chdir(p) then
- local pp=lfs.currentdir()
- if trace_locating and p~=pp then
- report_initialization("following symlink %a to %a",p,pp)
- end
- ownpath=pp
- lfs.chdir(olddir)
- else
- if trace_locating then
- report_initialization("unable to check path %a",p)
- end
- ownpath=p
- end
- break
- end
- end
- end
- end
- if not ownpath or ownpath=="" then
- ownpath="."
- report_initialization("forcing fallback to ownpath %a",ownpath)
- elseif trace_locating then
- report_initialization("using ownpath %a",ownpath)
- end
- end
- environment.ownbin=ownbin
- environment.ownpath=ownpath
-end
-resolvers.ownpath=environment.ownpath
-function resolvers.getownpath()
- return environment.ownpath
-end
-do
- local ownpath=environment.ownpath or dir.current()
- if ownpath then
- ossetenv('SELFAUTOLOC',file.collapsepath(ownpath))
- ossetenv('SELFAUTODIR',file.collapsepath(ownpath.."/.."))
- ossetenv('SELFAUTOPARENT',file.collapsepath(ownpath.."/../.."))
- else
- report_initialization("error: unable to locate ownpath")
- os.exit()
- end
-end
-local texos=environment.texos or osgetenv("TEXOS")
-local texmfos=environment.texmfos or osgetenv('SELFAUTODIR')
-if not texos or texos=="" then
- texos=file.basename(texmfos)
-end
-ossetenv('TEXMFOS',texmfos)
-ossetenv('TEXOS',texos)
-ossetenv('SELFAUTOSYSTEM',os.platform)
-environment.texos=texos
-environment.texmfos=texmfos
-local texroot=environment.texroot or osgetenv("TEXROOT")
-if not texroot or texroot=="" then
- texroot=osgetenv('SELFAUTOPARENT')
- ossetenv('TEXROOT',texroot)
-end
-environment.texroot=file.collapsepath(texroot)
-local prefixes=utilities.storage.allocate()
-resolvers.prefixes=prefixes
-local resolved={}
-local abstract={}
-local dynamic={}
-function resolvers.resetresolve(str)
- resolved,abstract={},{}
-end
-function resolvers.allprefixes(separator)
- local all=table.sortedkeys(prefixes)
- if separator then
- for i=1,#all do
- all[i]=all[i]..":"
- end
- end
- return all
-end
-local function _resolve_(method,target)
- local action=prefixes[method]
- if action then
- return action(target)
- else
- return method..":"..target
- end
-end
-function resolvers.unresolve(str)
- return abstract[str] or str
-end
-function resolvers.setdynamic(str)
- dynamic[str]=true
-end
-local pattern=Cs((C(R("az")^2)*P(":")*C((1-S(" \"\';,"))^1)/_resolve_+P(1))^0)
-local prefix=C(R("az")^2)*P(":")
-local target=C((1-S(" \"\';,"))^1)
-local notarget=(#S(";,")+P(-1))*Cc("")
-local p_resolve=Cs(((prefix*(target+notarget))/_resolve_+P(1))^0)
-local p_simple=prefix*P(-1)
-local function resolve(str)
- if type(str)=="table" then
- local res={}
- for i=1,#str do
- res[i]=resolve(str[i])
- end
- return res
- end
- local res=resolved[str]
- if res then
- return res
- end
- local simple=lpegmatch(p_simple,str)
- local action=prefixes[simple]
- if action then
- local res=action(res)
- if not dynamic[simple] then
- resolved[simple]=res
- abstract[res]=simple
- end
- return res
- end
- res=lpegmatch(p_resolve,str)
- resolved[str]=res
- abstract[res]=str
- return res
-end
-resolvers.resolve=resolve
-if type(osuname)=="function" then
- for k,v in next,osuname() do
- if not prefixes[k] then
- prefixes[k]=function() return v end
- end
- end
-end
-if ostype=="unix" then
- local pattern
- local function makepattern(t,k,v)
- if t then
- rawset(t,k,v)
- end
- local colon=P(":")
- for k,v in sortedpairs(prefixes) do
- if p then
- p=P(k)+p
- else
- p=P(k)
- end
- end
- pattern=Cs((p*colon+colon/";"+P(1))^0)
- end
- makepattern()
- table.setmetatablenewindex(prefixes,makepattern)
- function resolvers.repath(str)
- return lpegmatch(pattern,str)
- end
-else
- function resolvers.repath(str)
- return str
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-exp"] = package.loaded["data-exp"] or true
-
--- original size: 18179, stripped down to: 10432
-
-if not modules then modules={} end modules ['data-exp']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local format,find,gmatch,lower,char,sub=string.format,string.find,string.gmatch,string.lower,string.char,string.sub
-local concat,sort=table.concat,table.sort
-local sortedkeys=table.sortedkeys
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local Ct,Cs,Cc,Carg,P,C,S=lpeg.Ct,lpeg.Cs,lpeg.Cc,lpeg.Carg,lpeg.P,lpeg.C,lpeg.S
-local type,next=type,next
-local isdir=lfs.isdir
-local collapsepath,joinpath,basename=file.collapsepath,file.join,file.basename
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local trace_expansions=false trackers.register("resolvers.expansions",function(v) trace_expansions=v end)
-local trace_globbing=true trackers.register("resolvers.globbing",function(v) trace_globbing=v end)
-local report_expansions=logs.reporter("resolvers","expansions")
-local report_globbing=logs.reporter("resolvers","globbing")
-local resolvers=resolvers
-local resolveprefix=resolvers.resolve
-local function f_both(a,b)
- local t,n={},0
- for sb in gmatch(b,"[^,]+") do
- for sa in gmatch(a,"[^,]+") do
- n=n+1;t[n]=sa..sb
- end
- end
- return concat(t,",")
-end
-local comma=P(",")
-local nocomma=(1-comma)^1
-local docomma=comma^1/","
-local before=Cs((nocomma*Carg(1)+docomma)^0)
-local after=Cs((Carg(1)*nocomma+docomma)^0)
-local both=Cs(((C(nocomma)*Carg(1))/function(a,b) return lpegmatch(before,b,1,a) end+docomma)^0)
-local function f_first (a,b) return lpegmatch(after,b,1,a) end
-local function f_second(a,b) return lpegmatch(before,a,1,b) end
-local function f_both (a,b) return lpegmatch(both,b,1,a) end
-local left=P("{")
-local right=P("}")
-local var=P((1-S("{}" ))^0)
-local set=P((1-S("{},"))^0)
-local other=P(1)
-local l_first=Cs((Cc("{")*(C(set)*left*C(var)*right/f_first)*Cc("}")+other )^0 )
-local l_second=Cs((Cc("{")*(left*C(var)*right*C(set)/f_second)*Cc("}")+other )^0 )
-local l_both=Cs((Cc("{")*(left*C(var)*right*left*C(var)*right/f_both)*Cc("}")+other )^0 )
-local l_rest=Cs((left*var*(left/"")*var*(right/"")*var*right+other )^0 )
-local stripper_1=lpeg.stripper ("{}@")
-local replacer_1=lpeg.replacer { { ",}",",@}" },{ "{,","{@," },}
-local function splitpathexpr(str,newlist,validate)
- if trace_expansions then
- report_expansions("expanding variable %a",str)
- end
- local t,ok,done=newlist or {},false,false
- local n=#t
- str=lpegmatch(replacer_1,str)
- repeat
- local old=str
- repeat
- local old=str
- str=lpegmatch(l_first,str)
- until old==str
- repeat
- local old=str
- str=lpegmatch(l_second,str)
- until old==str
- repeat
- local old=str
- str=lpegmatch(l_both,str)
- until old==str
- repeat
- local old=str
- str=lpegmatch(l_rest,str)
- until old==str
- until old==str
- str=lpegmatch(stripper_1,str)
- if validate then
- for s in gmatch(str,"[^,]+") do
- s=validate(s)
- if s then
- n=n+1
- t[n]=s
- end
- end
- else
- for s in gmatch(str,"[^,]+") do
- n=n+1
- t[n]=s
- end
- end
- if trace_expansions then
- for k=1,#t do
- report_expansions("% 4i: %s",k,t[k])
- end
- end
- return t
-end
-local function validate(s)
- s=collapsepath(s)
- return s~="" and not find(s,"^!*unset/*$") and s
-end
-resolvers.validatedpath=validate
-function resolvers.expandedpathfromlist(pathlist)
- local newlist={}
- for k=1,#pathlist do
- splitpathexpr(pathlist[k],newlist,validate)
- end
- return newlist
-end
-local usedhomedir=nil
-local donegation=(P("!")/"" )^0
-local doslashes=(P("\\")/"/"+1)^0
-local function expandedhome()
- if not usedhomedir then
- usedhomedir=lpegmatch(Cs(donegation*doslashes),environment.homedir or "")
- if usedhomedir=="~" or usedhomedir=="" or not isdir(usedhomedir) then
- if trace_expansions then
- report_expansions("no home dir set, ignoring dependent path using current path")
- end
- usedhomedir="."
- end
- end
- return usedhomedir
-end
-local dohome=((P("~")+P("$HOME")+P("%HOME%"))/expandedhome)^0
-local cleanup=Cs(donegation*dohome*doslashes)
-resolvers.cleanpath=function(str)
- return str and lpegmatch(cleanup,str) or ""
-end
-local expandhome=P("~")/"$HOME"
-local dodouble=P('"')/""*(expandhome+(1-P('"')))^0*P('"')/""
-local dosingle=P("'")/""*(expandhome+(1-P("'")))^0*P("'")/""
-local dostring=(expandhome+1 )^0
-local stripper=Cs(
- lpegpatterns.unspacer*(dosingle+dodouble+dostring)*lpegpatterns.unspacer
-)
-function resolvers.checkedvariable(str)
- return type(str)=="string" and lpegmatch(stripper,str) or str
-end
-local cache={}
-local splitter=lpeg.tsplitat(";")
-local backslashswapper=lpeg.replacer("\\","/")
-local function splitconfigurationpath(str)
- if str then
- local found=cache[str]
- if not found then
- if str=="" then
- found={}
- else
- local split=lpegmatch(splitter,lpegmatch(backslashswapper,str))
- found={}
- local noffound=0
- for i=1,#split do
- local s=split[i]
- if not find(s,"^{*unset}*") then
- noffound=noffound+1
- found[noffound]=s
- end
- end
- if trace_expansions then
- report_expansions("splitting path specification %a",str)
- for k=1,noffound do
- report_expansions("% 4i: %s",k,found[k])
- end
- end
- cache[str]=found
- end
- end
- return found
- end
-end
-resolvers.splitconfigurationpath=splitconfigurationpath
-function resolvers.splitpath(str)
- if type(str)=='table' then
- return str
- else
- return splitconfigurationpath(str)
- end
-end
-function resolvers.joinpath(str)
- if type(str)=='table' then
- return joinpath(str)
- else
- return str
- end
-end
-local attributes,directory=lfs.attributes,lfs.dir
-local weird=P(".")^1+lpeg.anywhere(S("~`!#$%^&*()={}[]:;\"\'||<>,?\n\r\t"))
-local lessweird=P(".")^1+lpeg.anywhere(S("~`#$%^&*:;\"\'||<>,?\n\r\t"))
-local timer={}
-local scanned={}
-local nofscans=0
-local scancache={}
-local fullcache={}
-local nofsharedscans=0
-local addcasecraptoo=true
-local function scan(files,remap,spec,path,n,m,r,onlyone,tolerant)
- local full=path=="" and spec or (spec..path..'/')
- local dirlist={}
- local nofdirs=0
- local pattern=tolerant and lessweird or weird
- local filelist={}
- local noffiles=0
- for name,mode in directory(full) do
- if not lpegmatch(pattern,name) then
- if not mode then
- mode=attributes(full..name,"mode")
- end
- if mode=="file" then
- n=n+1
- noffiles=noffiles+1
- filelist[noffiles]=name
- elseif mode=="directory" then
- m=m+1
- nofdirs=nofdirs+1
- if path~="" then
- dirlist[nofdirs]=path.."/"..name
- else
- dirlist[nofdirs]=name
- end
- end
- end
- end
- if noffiles>0 then
- sort(filelist)
- for i=1,noffiles do
- local name=filelist[i]
- local lower=lower(name)
- local paths=files[lower]
- if paths then
- if onlyone then
- else
- if name~=lower then
- local rl=remap[lower]
- if not rl then
- remap[lower]=name
- r=r+1
- elseif trace_globbing and rl~=name then
- report_globbing("confusing filename, name: %a, lower: %a, already: %a",name,lower,rl)
- end
- if addcasecraptoo then
- local paths=files[name]
- if not paths then
- files[name]=path
- elseif type(paths)=="string" then
- files[name]={ paths,path }
- else
- paths[#paths+1]=path
- end
- end
- end
- if type(paths)=="string" then
- files[lower]={ paths,path }
- else
- paths[#paths+1]=path
- end
- end
- else
- files[lower]=path
- if name~=lower then
- local rl=remap[lower]
- if not rl then
- remap[lower]=name
- r=r+1
- elseif trace_globbing and rl~=name then
- report_globbing("confusing filename, name: %a, lower: %a, already: %a",name,lower,rl)
- end
- end
- end
- end
- end
- if nofdirs>0 then
- sort(dirlist)
- for i=1,nofdirs do
- files,remap,n,m,r=scan(files,remap,spec,dirlist[i],n,m,r,onlyonce,tolerant)
- end
- end
- scancache[sub(full,1,-2)]=files
- return files,remap,n,m,r
-end
-local function scanfiles(path,branch,usecache,onlyonce,tolerant)
- local realpath=resolveprefix(path)
- if usecache then
- local content=fullcache[realpath]
- if content then
- if trace_locating then
- report_expansions("using cached scan of path %a, branch %a",path,branch or path)
- end
- nofsharedscans=nofsharedscans+1
- return content
- end
- end
- statistics.starttiming(timer)
- if trace_locating then
- report_expansions("scanning path %a, branch %a",path,branch or path)
- end
- local content
- if isdir(realpath) then
- local files,remap,n,m,r=scan({},{},realpath..'/',"",0,0,0,onlyonce,tolerant)
- content={
- metadata={
- path=path,
- files=n,
- directories=m,
- remappings=r,
- },
- files=files,
- remap=remap,
- }
- if trace_locating then
- report_expansions("%s files found on %s directories with %s uppercase remappings",n,m,r)
- end
- else
- content={
- metadata={
- path=path,
- files=0,
- directories=0,
- remappings=0,
- },
- files={},
- remap={},
- }
- if trace_locating then
- report_expansions("invalid path %a",realpath)
- end
- end
- if usecache then
- scanned[#scanned+1]=realpath
- fullcache[realpath]=content
- end
- nofscans=nofscans+1
- statistics.stoptiming(timer)
- return content
-end
-resolvers.scanfiles=scanfiles
-function resolvers.simplescanfiles(path,branch,usecache)
- return scanfiles(path,branch,usecache,true,true)
-end
-function resolvers.scandata()
- table.sort(scanned)
- return {
- n=nofscans,
- shared=nofsharedscans,
- time=statistics.elapsedtime(timer),
- paths=scanned,
- }
-end
-function resolvers.get_from_content(content,path,name)
- if not content then
- return
- end
- local files=content.files
- if not files then
- return
- end
- local remap=content.remap
- if not remap then
- return
- end
- if name then
- local used=lower(name)
- return path,remap[used] or used
- else
- local name=path
- local used=lower(name)
- local path=files[used]
- if path then
- return path,remap[used] or used
- end
- end
-end
-local nothing=function() end
-function resolvers.filtered_from_content(content,pattern)
- if content and type(pattern)=="string" then
- local pattern=lower(pattern)
- local files=content.files
- local remap=content.remap
- if files and remap then
- local f=sortedkeys(files)
- local n=#f
- local i=0
- local function iterator()
- while i<n do
- i=i+1
- local k=f[i]
- if find(k,pattern) then
- return files[k],remap and remap[k] or k
- end
- end
- end
- return iterator
- end
- end
- return nothing
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-env"] = package.loaded["data-env"] or true
-
--- original size: 9501, stripped down to: 6411
-
-if not modules then modules={} end modules ['data-env']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local lower,gsub=string.lower,string.gsub
-local next,rawget=next,rawget
-local resolvers=resolvers
-local allocate=utilities.storage.allocate
-local setmetatableindex=table.setmetatableindex
-local suffixonly=file.suffixonly
-local formats=allocate()
-local suffixes=allocate()
-local dangerous=allocate()
-local suffixmap=allocate()
-local usertypes=allocate()
-resolvers.formats=formats
-resolvers.suffixes=suffixes
-resolvers.dangerous=dangerous
-resolvers.suffixmap=suffixmap
-resolvers.usertypes=usertypes
-local luasuffixes=utilities.lua.suffixes
-local relations=allocate {
- core={
- ofm={
- names={ "ofm","omega font metric","omega font metrics" },
- variable='OFMFONTS',
- suffixes={ 'ofm','tfm' },
- },
- ovf={
- names={ "ovf","omega virtual font","omega virtual fonts" },
- variable='OVFFONTS',
- suffixes={ 'ovf','vf' },
- },
- tfm={
- names={ "tfm","tex font metric","tex font metrics" },
- variable='TFMFONTS',
- suffixes={ 'tfm' },
- },
- vf={
- names={ "vf","virtual font","virtual fonts" },
- variable='VFFONTS',
- suffixes={ 'vf' },
- },
- otf={
- names={ "otf","opentype","opentype font","opentype fonts"},
- variable='OPENTYPEFONTS',
- suffixes={ 'otf' },
- },
- ttf={
- names={ "ttf","truetype","truetype font","truetype fonts","truetype collection","truetype collections","truetype dictionary","truetype dictionaries" },
- variable='TTFONTS',
- suffixes={ 'ttf','ttc','dfont' },
- },
- afm={
- names={ "afm","adobe font metric","adobe font metrics" },
- variable="AFMFONTS",
- suffixes={ "afm" },
- },
- pfb={
- names={ "pfb","type1","type 1","type1 font","type 1 font","type1 fonts","type 1 fonts" },
- variable='T1FONTS',
- suffixes={ 'pfb','pfa' },
- },
- fea={
- names={ "fea","font feature","font features","font feature file","font feature files" },
- variable='FONTFEATURES',
- suffixes={ 'fea' },
- },
- cid={
- names={ "cid","cid map","cid maps","cid file","cid files" },
- variable='FONTCIDMAPS',
- suffixes={ 'cid','cidmap' },
- },
- fmt={
- names={ "fmt","format","tex format" },
- variable='TEXFORMATS',
- suffixes={ 'fmt' },
- },
- mem={
- names={ 'mem',"metapost format" },
- variable='MPMEMS',
- suffixes={ 'mem' },
- },
- mp={
- names={ "mp" },
- variable='MPINPUTS',
- suffixes=CONTEXTLMTXMODE>0
- and { 'mp','mpxl','mpvi','mpiv','mpii' }
- or { 'mp','mpvi','mpiv','mpii' },
- usertype=true,
- },
- tex={
- names={ "tex" },
- variable='TEXINPUTS',
- suffixes={ "tex","mkiv","mkvi","mkxl","mklx","mkii","cld","lfg","xml" },
- usertype=true,
- },
- icc={
- names={ "icc","icc profile","icc profiles" },
- variable='ICCPROFILES',
- suffixes={ 'icc' },
- },
- texmfscripts={
- names={ "texmfscript","texmfscripts","script","scripts" },
- variable='TEXMFSCRIPTS',
- suffixes={ 'lua','rb','pl','py' },
- },
- lua={
- names={ "lua" },
- variable='LUAINPUTS',
- suffixes={ luasuffixes.lua,luasuffixes.luc,luasuffixes.tma,luasuffixes.tmc },
- usertype=true,
- },
- lib={
- names={ "lib" },
- variable='CLUAINPUTS',
- suffixes=os.libsuffix and { os.libsuffix } or { 'dll','so' },
- },
- bib={
- names={ 'bib' },
- variable='BIBINPUTS',
- suffixes={ 'bib' },
- usertype=true,
- },
- bst={
- names={ 'bst' },
- variable='BSTINPUTS',
- suffixes={ 'bst' },
- usertype=true,
- },
- fontconfig={
- names={ 'fontconfig','fontconfig file','fontconfig files' },
- variable='FONTCONFIG_PATH',
- },
- pk={
- names={ "pk" },
- variable='PKFONTS',
- suffixes={ 'pk' },
- },
- },
- obsolete={
- enc={
- names={ "enc","enc files","enc file","encoding files","encoding file" },
- variable='ENCFONTS',
- suffixes={ 'enc' },
- },
- map={
- names={ "map","map files","map file" },
- variable='TEXFONTMAPS',
- suffixes={ 'map' },
- },
- lig={
- names={ "lig files","lig file","ligature file","ligature files" },
- variable='LIGFONTS',
- suffixes={ 'lig' },
- },
- opl={
- names={ "opl" },
- variable='OPLFONTS',
- suffixes={ 'opl' },
- },
- ovp={
- names={ "ovp" },
- variable='OVPFONTS',
- suffixes={ 'ovp' },
- },
- },
- kpse={
- base={
- names={ 'base',"metafont format" },
- variable='MFBASES',
- suffixes={ 'base','bas' },
- },
- cmap={
- names={ 'cmap','cmap files','cmap file' },
- variable='CMAPFONTS',
- suffixes={ 'cmap' },
- },
- cnf={
- names={ 'cnf' },
- suffixes={ 'cnf' },
- },
- web={
- names={ 'web' },
- suffixes={ 'web','ch' }
- },
- cweb={
- names={ 'cweb' },
- suffixes={ 'w','web','ch' },
- },
- gf={
- names={ 'gf' },
- suffixes={ '<resolution>gf' },
- },
- mf={
- names={ 'mf' },
- variable='MFINPUTS',
- suffixes={ 'mf' },
- },
- mft={
- names={ 'mft' },
- suffixes={ 'mft' },
- },
- pk={
- names={ 'pk' },
- suffixes={ '<resolution>pk' },
- },
- },
-}
-resolvers.relations=relations
-function resolvers.updaterelations()
- for category,categories in next,relations do
- for name,relation in next,categories do
- local rn=relation.names
- local rv=relation.variable
- if rn and rv then
- local rs=relation.suffixes
- local ru=relation.usertype
- for i=1,#rn do
- local rni=lower(gsub(rn[i]," ",""))
- formats[rni]=rv
- if rs then
- suffixes[rni]=rs
- for i=1,#rs do
- local rsi=rs[i]
- suffixmap[rsi]=rni
- end
- end
- end
- if ru then
- usertypes[name]=true
- end
- end
- end
- end
-end
-resolvers.updaterelations()
-local function simplified(t,k)
- return k and rawget(t,lower(gsub(k," ",""))) or nil
-end
-setmetatableindex(formats,simplified)
-setmetatableindex(suffixes,simplified)
-setmetatableindex(suffixmap,simplified)
-function resolvers.suffixofformat(str)
- local s=suffixes[str]
- return s and s[1] or ""
-end
-function resolvers.suffixofformat(str)
- return suffixes[str] or {}
-end
-for name,format in next,formats do
- dangerous[name]=true
-end
-dangerous.tex=nil
-function resolvers.formatofvariable(str)
- return formats[str] or ''
-end
-function resolvers.formatofsuffix(str)
- return suffixmap[suffixonly(str)] or 'tex'
-end
-function resolvers.variableofformat(str)
- return formats[str] or ''
-end
-function resolvers.variableofformatorsuffix(str)
- local v=formats[str]
- if v then
- return v
- end
- v=suffixmap[suffixonly(str)]
- if v then
- return formats[v]
- end
- return ''
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-tmp"] = package.loaded["data-tmp"] or true
-
--- original size: 16409, stripped down to: 11591
-
-if not modules then modules={} end modules ['data-tmp']={
- version=1.100,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local next,type=next,type
-local pcall,loadfile,collectgarbage=pcall,loadfile,collectgarbage
-local format,lower,gsub=string.format,string.lower,string.gsub
-local concat,serialize,fastserialize,serializetofile=table.concat,table.serialize,table.fastserialize,table.tofile
-local mkdirs,expanddirname,isdir,isfile=dir.mkdirs,dir.expandname,lfs.isdir,lfs.isfile
-local is_writable,is_readable=file.is_writable,file.is_readable
-local collapsepath,joinfile,addsuffix,dirname=file.collapsepath,file.join,file.addsuffix,file.dirname
-local savedata=file.savedata
-local formatters=string.formatters
-local osexit,osdate,osuuid=os.exit,os.date,os.uuid
-local removefile=os.remove
-local md5hex=md5.hex
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local trace_cache=false trackers.register("resolvers.cache",function(v) trace_cache=v end)
-local report_caches=logs.reporter("resolvers","caches")
-local report_resolvers=logs.reporter("resolvers","caching")
-local resolvers=resolvers
-local cleanpath=resolvers.cleanpath
-local resolvepath=resolvers.resolve
-local luautilities=utilities.lua
-do
- local directive_cleanup=false directives.register("system.compile.cleanup",function(v) directive_cleanup=v end)
- local directive_strip=false directives.register("system.compile.strip",function(v) directive_strip=v end)
- local compilelua=luautilities.compile
- function luautilities.compile(luafile,lucfile,cleanup,strip)
- if cleanup==nil then cleanup=directive_cleanup end
- if strip==nil then strip=directive_strip end
- return compilelua(luafile,lucfile,cleanup,strip)
- end
-end
-caches=caches or {}
-local caches=caches
-local writable=nil
-local readables={}
-local usedreadables={}
-local compilelua=luautilities.compile
-local luasuffixes=luautilities.suffixes
-caches.base=caches.base or "luatex-cache"
-caches.more=caches.more or "context"
-caches.defaults={ "TMPDIR","TEMPDIR","TMP","TEMP","HOME","HOMEPATH" }
-local direct_cache=false
-local fast_cache=false
-local cache_tree=false
-directives.register("system.caches.direct",function(v) direct_cache=true end)
-directives.register("system.caches.fast",function(v) fast_cache=true end)
-local function configfiles()
- return concat(resolvers.configurationfiles(),";")
-end
-local function hashed(tree)
- tree=gsub(tree,"[\\/]+$","")
- tree=lower(tree)
- local hash=md5hex(tree)
- if trace_cache or trace_locating then
- report_caches("hashing tree %a, hash %a",tree,hash)
- end
- return hash
-end
-local function treehash()
- local tree=configfiles()
- if not tree or tree=="" then
- return false
- else
- return hashed(tree)
- end
-end
-caches.hashed=hashed
-caches.treehash=treehash
-caches.configfiles=configfiles
-local function identify()
- local texmfcaches=resolvers.cleanpathlist("TEXMFCACHE")
- if texmfcaches then
- for k=1,#texmfcaches do
- local cachepath=texmfcaches[k]
- if cachepath~="" then
- cachepath=resolvepath(cachepath)
- cachepath=cleanpath(cachepath)
- cachepath=collapsepath(cachepath)
- local valid=isdir(cachepath)
- if valid then
- if is_readable(cachepath) then
- readables[#readables+1]=cachepath
- if not writable and is_writable(cachepath) then
- writable=cachepath
- end
- end
- elseif not writable then
- local cacheparent=dirname(cachepath)
- if is_writable(cacheparent) then
- mkdirs(cachepath)
- if isdir(cachepath) and is_writable(cachepath) then
- report_caches("path %a created",cachepath)
- writable=cachepath
- readables[#readables+1]=cachepath
- end
- end
- end
- end
- end
- end
- local texmfcaches=caches.defaults
- if texmfcaches then
- for k=1,#texmfcaches do
- local cachepath=texmfcaches[k]
- cachepath=resolvers.expansion(cachepath)
- if cachepath~="" then
- cachepath=resolvepath(cachepath)
- cachepath=cleanpath(cachepath)
- local valid=isdir(cachepath)
- if valid and is_readable(cachepath) then
- if not writable and is_writable(cachepath) then
- readables[#readables+1]=cachepath
- writable=cachepath
- break
- end
- end
- end
- end
- end
- if not writable then
- report_caches("fatal error: there is no valid writable cache path defined")
- osexit()
- elseif #readables==0 then
- report_caches("fatal error: there is no valid readable cache path defined")
- osexit()
- end
- writable=expanddirname(cleanpath(writable))
- local base=caches.base
- local more=caches.more
- local tree=cache_tree or treehash()
- if tree then
- cache_tree=tree
- writable=mkdirs(writable,base,more,tree)
- for i=1,#readables do
- readables[i]=joinfile(readables[i],base,more,tree)
- end
- else
- writable=mkdirs(writable,base,more)
- for i=1,#readables do
- readables[i]=joinfile(readables[i],base,more)
- end
- end
- if trace_cache then
- for i=1,#readables do
- report_caches("using readable path %a (order %s)",readables[i],i)
- end
- report_caches("using writable path %a",writable)
- end
- identify=function()
- return writable,readables
- end
- return writable,readables
-end
-function caches.usedpaths(separator)
- local writable,readables=identify()
- if #readables>1 then
- local result={}
- local done={}
- for i=1,#readables do
- local readable=readables[i]
- if readable==writable then
- done[readable]=true
- result[#result+1]=formatters["readable+writable: %a"](readable)
- elseif usedreadables[i] then
- done[readable]=true
- result[#result+1]=formatters["readable: %a"](readable)
- end
- end
- if not done[writable] then
- result[#result+1]=formatters["writable: %a"](writable)
- end
- return concat(result,separator or " | ")
- else
- return writable or "?"
- end
-end
-local r_cache={}
-local w_cache={}
-local function getreadablepaths(...)
- local tags={... }
- local hash=concat(tags,"/")
- local done=r_cache[hash]
- if not done then
- local writable,readables=identify()
- if #tags>0 then
- done={}
- for i=1,#readables do
- done[i]=joinfile(readables[i],...)
- end
- else
- done=readables
- end
- r_cache[hash]=done
- end
- return done
-end
-local function getwritablepath(...)
- local tags={... }
- local hash=concat(tags,"/")
- local done=w_cache[hash]
- if not done then
- local writable,readables=identify()
- if #tags>0 then
- done=mkdirs(writable,...)
- else
- done=writable
- end
- w_cache[hash]=done
- end
- return done
-end
-local function setfirstwritablefile(filename,...)
- local wr=getwritablepath(...)
- local fullname=joinfile(wr,filename)
- return fullname,wr
-end
-local function setluanames(path,name)
- return
- format("%s/%s.%s",path,name,luasuffixes.tma),
- format("%s/%s.%s",path,name,luasuffixes.tmc)
-end
-local function getfirstreadablefile(filename,...)
- local fullname,path=setfirstwritablefile(filename,...)
- if is_readable(fullname) then
- return fullname,path
- end
- local rd=getreadablepaths(...)
- for i=1,#rd do
- local path=rd[i]
- local fullname=joinfile(path,filename)
- if is_readable(fullname) then
- usedreadables[i]=true
- return fullname,path
- end
- end
- return fullname,path
-end
-caches.getreadablepaths=getreadablepaths
-caches.getwritablepath=getwritablepath
-caches.setfirstwritablefile=setfirstwritablefile
-caches.getfirstreadablefile=getfirstreadablefile
-caches.setluanames=setluanames
-local checkmemory=utilities and utilities.lua and utilities.lua.checkmemory
-local threshold=100
-function caches.loaddata(readables,name,writable)
- local used=checkmemory and checkmemory()
- if type(readables)=="string" then
- readables={ readables }
- end
- for i=1,#readables do
- local path=readables[i]
- local loader=false
- local state=false
- local tmaname,tmcname=setluanames(path,name)
- if isfile(tmcname) then
- state,loader=pcall(loadfile,tmcname)
- end
- if not loader and isfile(tmaname) then
- local tmacrap,tmcname=setluanames(writable,name)
- if isfile(tmcname) then
- state,loader=pcall(loadfile,tmcname)
- end
- compilelua(tmaname,tmcname)
- if isfile(tmcname) then
- state,loader=pcall(loadfile,tmcname)
- end
- if not loader then
- state,loader=pcall(loadfile,tmaname)
- end
- end
- if loader then
- loader=loader()
- if checkmemory then
- checkmemory(used,threshold)
- else
- collectgarbage("step")
- end
- return loader
- end
- end
- return false
-end
-function caches.is_writable(filepath,filename)
- local tmaname,tmcname=setluanames(filepath,filename)
- return is_writable(tmaname)
-end
-local saveoptions={ compact=true,accurate=not JITSUPPORTED }
-function caches.savedata(filepath,filename,data,fast)
- local tmaname,tmcname=setluanames(filepath,filename)
- data.cache_uuid=osuuid()
- if fast or fast_cache then
- savedata(tmaname,fastserialize(data,true))
- elseif direct_cache then
- savedata(tmaname,serialize(data,true,saveoptions))
- else
- serializetofile(tmaname,data,true,saveoptions)
- end
- compilelua(tmaname,tmcname)
-end
-local content_state={}
-function caches.contentstate()
- return content_state or {}
-end
-function caches.loadcontent(cachename,dataname,filename)
- if not filename then
- local name=hashed(cachename)
- local full,path=getfirstreadablefile(addsuffix(name,luasuffixes.lua),"trees")
- filename=joinfile(path,name)
- end
- local state,blob=pcall(loadfile,addsuffix(filename,luasuffixes.luc))
- if not blob then
- state,blob=pcall(loadfile,addsuffix(filename,luasuffixes.lua))
- end
- if blob then
- local data=blob()
- if data and data.content then
- if data.type==dataname then
- if data.version==resolvers.cacheversion then
- content_state[#content_state+1]=data.uuid
- if trace_locating then
- report_resolvers("loading %a for %a from %a",dataname,cachename,filename)
- end
- return data.content
- else
- report_resolvers("skipping %a for %a from %a (version mismatch)",dataname,cachename,filename)
- end
- else
- report_resolvers("skipping %a for %a from %a (datatype mismatch)",dataname,cachename,filename)
- end
- elseif trace_locating then
- report_resolvers("skipping %a for %a from %a (no content)",dataname,cachename,filename)
- end
- elseif trace_locating then
- report_resolvers("skipping %a for %a from %a (invalid file)",dataname,cachename,filename)
- end
-end
-function caches.collapsecontent(content)
- for k,v in next,content do
- if type(v)=="table" and #v==1 then
- content[k]=v[1]
- end
- end
-end
-function caches.savecontent(cachename,dataname,content,filename)
- if not filename then
- local name=hashed(cachename)
- local full,path=setfirstwritablefile(addsuffix(name,luasuffixes.lua),"trees")
- filename=joinfile(path,name)
- end
- local luaname=addsuffix(filename,luasuffixes.lua)
- local lucname=addsuffix(filename,luasuffixes.luc)
- if trace_locating then
- report_resolvers("preparing %a for %a",dataname,cachename)
- end
- local data={
- type=dataname,
- root=cachename,
- version=resolvers.cacheversion,
- date=osdate("%Y-%m-%d"),
- time=osdate("%H:%M:%S"),
- content=content,
- uuid=osuuid(),
- }
- local ok=savedata(luaname,serialize(data,true))
- if ok then
- if trace_locating then
- report_resolvers("category %a, cachename %a saved in %a",dataname,cachename,luaname)
- end
- if compilelua(luaname,lucname) then
- if trace_locating then
- report_resolvers("%a compiled to %a",dataname,lucname)
- end
- return true
- else
- if trace_locating then
- report_resolvers("compiling failed for %a, deleting file %a",dataname,lucname)
- end
- removefile(lucname)
- end
- elseif trace_locating then
- report_resolvers("unable to save %a in %a (access error)",dataname,luaname)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-met"] = package.loaded["data-met"] or true
-
--- original size: 5518, stripped down to: 3854
-
-if not modules then modules={} end modules ['data-met']={
- version=1.100,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type=type
-local find=string.find
-local addurlscheme,urlhashed=url.addscheme,url.hashed
-local collapsepath,joinfile=file.collapsepath,file.join
-local report_methods=logs.reporter("resolvers","methods")
-local trace_locating=false
-local trace_methods=false
-trackers.register("resolvers.locating",function(v) trace_methods=v end)
-trackers.register("resolvers.methods",function(v) trace_methods=v end)
-local allocate=utilities.storage.allocate
-local resolvers=resolvers
-local registered={}
-local function splitmethod(filename)
- if not filename then
- return {
- scheme="unknown",
- original=filename,
- }
- end
- if type(filename)=="table" then
- return filename
- end
- filename=collapsepath(filename,".")
- if not find(filename,"://",1,true) then
- return {
- scheme="file",
- path=filename,
- original=filename,
- filename=filename,
- }
- end
- local specification=urlhashed(filename)
- if not specification.scheme or specification.scheme=="" then
- return {
- scheme="file",
- path=filename,
- original=filename,
- filename=filename,
- }
- else
- return specification
- end
-end
-resolvers.splitmethod=splitmethod
-local function methodhandler(what,first,...)
- local method=registered[what]
- if method then
- local how=method.how
- local namespace=method.namespace
- if how=="uri" or how=="url" then
- local specification=splitmethod(first)
- local scheme=specification.scheme
- local resolver=namespace and namespace[scheme]
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, handler %a, argument %a",what,how,scheme,first)
- end
- return resolver(specification,...)
- else
- resolver=namespace.default or namespace.file
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, handler %a, argument %a",what,how,"default",first)
- end
- return resolver(specification,...)
- elseif trace_methods then
- report_methods("resolving, method %a, how %a, handler %a, argument %a",what,how,"unset")
- end
- end
- elseif how=="tag" then
- local resolver=namespace and namespace[first]
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, tag %a",what,how,first)
- end
- return resolver(...)
- else
- resolver=namespace.default or namespace.file
- if resolver then
- if trace_methods then
- report_methods("resolving, method %a, how %a, tag %a",what,how,"default")
- end
- return resolver(...)
- elseif trace_methods then
- report_methods("resolving, method %a, how %a, tag %a",what,how,"unset")
- end
- end
- end
- else
- report_methods("resolving, invalid method %a")
- end
-end
-resolvers.methodhandler=methodhandler
-function resolvers.registermethod(name,namespace,how)
- registered[name]={
- how=how or "tag",
- namespace=namespace
- }
- namespace["byscheme"]=function(scheme,filename,...)
- if scheme=="file" then
- return methodhandler(name,filename,...)
- else
- return methodhandler(name,addurlscheme(filename,scheme),...)
- end
- end
-end
-local concatinators=allocate { notfound=joinfile }
-local locators=allocate { notfound=function() end }
-local hashers=allocate { notfound=function() end }
-local generators=allocate { notfound=function() end }
-resolvers.concatinators=concatinators
-resolvers.locators=locators
-resolvers.hashers=hashers
-resolvers.generators=generators
-local registermethod=resolvers.registermethod
-registermethod("concatinators",concatinators,"tag")
-registermethod("locators",locators,"uri")
-registermethod("hashers",hashers,"uri")
-registermethod("generators",generators,"uri")
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-res"] = package.loaded["data-res"] or true
-
--- original size: 69576, stripped down to: 44470
-
-if not modules then modules={} end modules ['data-res']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files",
-}
-local gsub,find,lower,upper,match,gmatch=string.gsub,string.find,string.lower,string.upper,string.match,string.gmatch
-local concat,insert,remove=table.concat,table.insert,table.remove
-local next,type,rawget,loadfile=next,type,rawget,loadfile
-local mergedtable=table.merged
-local os=os
-local P,S,R,C,Cc,Cs,Ct,Carg=lpeg.P,lpeg.S,lpeg.R,lpeg.C,lpeg.Cc,lpeg.Cs,lpeg.Ct,lpeg.Carg
-local lpegmatch,lpegpatterns=lpeg.match,lpeg.patterns
-local formatters=string.formatters
-local filedirname=file.dirname
-local filebasename=file.basename
-local suffixonly=file.suffixonly
-local addsuffix=file.addsuffix
-local removesuffix=file.removesuffix
-local filejoin=file.join
-local collapsepath=file.collapsepath
-local joinpath=file.joinpath
-local is_qualified_path=file.is_qualified_path
-local allocate=utilities.storage.allocate
-local settings_to_array=utilities.parsers.settings_to_array
-local urlhasscheme=url.hasscheme
-local getcurrentdir=lfs.currentdir
-local isfile=lfs.isfile
-local isdir=lfs.isdir
-local setmetatableindex=table.setmetatableindex
-local luasuffixes=utilities.lua.suffixes
-local trace_locating=false trackers .register("resolvers.locating",function(v) trace_locating=v end)
-local trace_details=false trackers .register("resolvers.details",function(v) trace_details=v end)
-local trace_expansions=false trackers .register("resolvers.expansions",function(v) trace_expansions=v end)
-local trace_paths=false trackers .register("resolvers.paths",function(v) trace_paths=v end)
-local resolve_otherwise=true directives.register("resolvers.otherwise",function(v) resolve_otherwise=v end)
-local report_resolving=logs.reporter("resolvers","resolving")
-local resolvers=resolvers
-local expandedpathfromlist=resolvers.expandedpathfromlist
-local checkedvariable=resolvers.checkedvariable
-local splitconfigurationpath=resolvers.splitconfigurationpath
-local methodhandler=resolvers.methodhandler
-local filtered=resolvers.filtered_from_content
-local lookup=resolvers.get_from_content
-local cleanpath=resolvers.cleanpath
-local resolveprefix=resolvers.resolve
-local initializesetter=utilities.setters.initialize
-local ostype,osname,osenv,ossetenv,osgetenv=os.type,os.name,os.env,os.setenv,os.getenv
-resolvers.cacheversion="1.100"
-resolvers.configbanner=""
-resolvers.homedir=environment.homedir
-resolvers.luacnfname="texmfcnf.lua"
-resolvers.luacnffallback="contextcnf.lua"
-resolvers.luacnfstate="unknown"
-local criticalvars={
- "SELFAUTOLOC",
- "SELFAUTODIR",
- "SELFAUTOPARENT",
- "TEXMFCNF",
- "TEXMF",
- "TEXOS",
-}
-if environment.default_texmfcnf then
- resolvers.luacnfspec="home:texmf/web2c;"..environment.default_texmfcnf
-else
- resolvers.luacnfspec=concat ({
- "home:texmf/web2c",
- "selfautoparent:/texmf-local/web2c",
- "selfautoparent:/texmf-context/web2c",
- "selfautoparent:/texmf-dist/web2c",
- "selfautoparent:/texmf/web2c",
- },";")
-end
-local unset_variable="unset"
-local formats=resolvers.formats
-local suffixes=resolvers.suffixes
-local usertypes=resolvers.usertypes
-local dangerous=resolvers.dangerous
-local suffixmap=resolvers.suffixmap
-resolvers.defaultsuffixes={ "tex" }
-local instance=nil
-local variable
-local expansion
-local setenv
-local getenv
-local formatofsuffix=resolvers.formatofsuffix
-local splitpath=resolvers.splitpath
-local splitmethod=resolvers.splitmethod
-setenv=function(key,value,raw)
- if instance then
- instance.environment[key]=value
- ossetenv(key,raw and value or resolveprefix(value))
- end
-end
-getenv=function(key)
- local value=rawget(instance.environment,key)
- if value and value~="" then
- return value
- else
- local e=osgetenv(key)
- return e~=nil and e~="" and checkedvariable(e) or ""
- end
-end
-resolvers.getenv=getenv
-resolvers.setenv=setenv
-local dollarstripper=lpeg.stripper("$")
-local inhibitstripper=P("!")^0*Cs(P(1)^0)
-local expandedvariable,resolvedvariable do
- local function resolveinstancevariable(k)
- return instance.expansions[k]
- end
- local p_variable=P("$")/""
- local p_key=C(R("az","AZ","09","__","--")^1)
- local p_whatever=P(";")*((1-S("!{}/\\"))^1*P(";")/"")+P(";")*(P(";")/"")+P(1)
- local variableexpander=Cs((p_variable*(p_key/resolveinstancevariable)+p_whatever)^1 )
- local p_cleaner=P("\\")/"/"+P(";")*S("!{}/\\")^0*P(";")^1/";"
- local variablecleaner=Cs((p_cleaner+P(1))^0)
- local p_variable=R("az","AZ","09","__","--")^1/resolveinstancevariable
- local p_variable=(P("$")/"")*(p_variable+(P("{")/"")*p_variable*(P("}")/""))
- local variableresolver=Cs((p_variable+P(1))^0)
- expandedvariable=function(var)
- return lpegmatch(variableexpander,var) or var
- end
- function resolvers.reset()
- if trace_locating then
- report_resolving("creating instance")
- end
- local environment={}
- local variables={}
- local expansions={}
- local order={}
- instance={
- environment=environment,
- variables=variables,
- expansions=expansions,
- order=order,
- files={},
- setups={},
- found={},
- foundintrees={},
- hashes={},
- hashed={},
- pathlists=false,
- specification={},
- lists={},
- data={},
- fakepaths={},
- remember=true,
- diskcache=true,
- renewcache=false,
- renewtree=false,
- loaderror=false,
- savelists=true,
- pattern=nil,
- force_suffixes=true,
- pathstack={},
- }
- setmetatableindex(variables,function(t,k)
- local v
- for i=1,#order do
- v=order[i][k]
- if v~=nil then
- t[k]=v
- return v
- end
- end
- if v==nil then
- v=""
- end
- t[k]=v
- return v
- end)
- local repath=resolvers.repath
- setmetatableindex(environment,function(t,k)
- local v=osgetenv(k)
- if v==nil then
- v=variables[k]
- end
- if v~=nil then
- v=checkedvariable(v) or ""
- end
- v=repath(v)
- t[k]=v
- return v
- end)
- setmetatableindex(expansions,function(t,k)
- local v=environment[k]
- if type(v)=="string" then
- v=lpegmatch(variableresolver,v)
- v=lpegmatch(variablecleaner,v)
- end
- t[k]=v
- return v
- end)
- end
-end
-function resolvers.initialized()
- return instance~=nil
-end
-local function reset_hashes()
- instance.lists={}
- instance.pathlists=false
- instance.found={}
-end
-local function reset_caches()
- instance.lists={}
- instance.pathlists=false
-end
-local makepathexpression do
- local slash=P("/")
- local pathexpressionpattern=Cs (
- Cc("^")*(
- Cc("%")*S(".-")+slash^2*P(-1)/"/.*"
-+slash^2/"/"+(1-slash)*P(-1)*Cc("/")+P(1)
- )^1*Cc("$")
- )
- local cache={}
- makepathexpression=function(str)
- if str=="." then
- return "^%./$"
- else
- local c=cache[str]
- if not c then
- c=lpegmatch(pathexpressionpattern,str)
- cache[str]=c
- end
- return c
- end
- end
-end
-local function reportcriticalvariables(cnfspec)
- if trace_locating then
- for i=1,#criticalvars do
- local k=criticalvars[i]
- local v=getenv(k) or "unknown"
- report_resolving("variable %a set to %a",k,v)
- end
- report_resolving()
- if cnfspec then
- report_resolving("using configuration specification %a",type(cnfspec)=="table" and concat(cnfspec,",") or cnfspec)
- end
- report_resolving()
- end
- reportcriticalvariables=function() end
-end
-local function identify_configuration_files()
- local specification=instance.specification
- if #specification==0 then
- local cnfspec=getenv("TEXMFCNF")
- if cnfspec=="" then
- cnfspec=resolvers.luacnfspec
- resolvers.luacnfstate="default"
- else
- resolvers.luacnfstate="environment"
- end
- reportcriticalvariables(cnfspec)
- local cnfpaths=expandedpathfromlist(splitpath(cnfspec))
- local function locatecnf(luacnfname,kind)
- for i=1,#cnfpaths do
- local filepath=cnfpaths[i]
- local filename=collapsepath(filejoin(filepath,luacnfname))
- local realname=resolveprefix(filename)
- if trace_locating then
- local fullpath=gsub(resolveprefix(collapsepath(filepath)),"//","/")
- local weirdpath=find(fullpath,"/texmf.+/texmf") or not find(fullpath,"/web2c",1,true)
- report_resolving("looking for %s %a on %s path %a from specification %a",
- kind,luacnfname,weirdpath and "weird" or "given",fullpath,filepath)
- end
- if isfile(realname) then
- specification[#specification+1]=filename
- if trace_locating then
- report_resolving("found %s configuration file %a",kind,realname)
- end
- end
- end
- end
- locatecnf(resolvers.luacnfname,"regular")
- if #specification==0 then
- locatecnf(resolvers.luacnffallback,"fallback")
- end
- if trace_locating then
- report_resolving()
- end
- elseif trace_locating then
- report_resolving("configuration files already identified")
- end
-end
-local function load_configuration_files()
- local specification=instance.specification
- local setups=instance.setups
- local order=instance.order
- if #specification>0 then
- local luacnfname=resolvers.luacnfname
- for i=1,#specification do
- local filename=specification[i]
- local pathname=filedirname(filename)
- local filename=filejoin(pathname,luacnfname)
- local realname=resolveprefix(filename)
- local blob=loadfile(realname)
- if blob then
- local data=blob()
- local parent=data and data.parent
- if parent then
- local filename=filejoin(pathname,parent)
- local realname=resolveprefix(filename)
- local blob=loadfile(realname)
- if blob then
- local parentdata=blob()
- if parentdata then
- report_resolving("loading configuration file %a",filename)
- data=mergedtable(parentdata,data)
- end
- end
- end
- data=data and data.content
- if data then
- if trace_locating then
- report_resolving("loading configuration file %a",filename)
- report_resolving()
- end
- local variables=data.variables or {}
- local warning=false
- for k,v in next,data do
- local variant=type(v)
- if variant=="table" then
- initializesetter(filename,k,v)
- elseif variables[k]==nil then
- if trace_locating and not warning then
- report_resolving("variables like %a in configuration file %a should move to the 'variables' subtable",
- k,resolveprefix(filename))
- warning=true
- end
- variables[k]=v
- end
- end
- setups[pathname]=variables
- if resolvers.luacnfstate=="default" then
- local cnfspec=variables["TEXMFCNF"]
- if cnfspec then
- if trace_locating then
- report_resolving("reloading configuration due to TEXMF redefinition")
- end
- setenv("TEXMFCNF",cnfspec)
- instance.specification={}
- identify_configuration_files()
- load_configuration_files()
- resolvers.luacnfstate="configuration"
- break
- end
- end
- else
- if trace_locating then
- report_resolving("skipping configuration file %a (no content)",filename)
- end
- setups[pathname]={}
- instance.loaderror=true
- end
- elseif trace_locating then
- report_resolving("skipping configuration file %a (no valid format)",filename)
- end
- order[#order+1]=setups[pathname]
- if instance.loaderror then
- break
- end
- end
- elseif trace_locating then
- report_resolving("warning: no lua configuration files found")
- end
-end
-local expandedpathlist
-local unexpandedpathlist
-function resolvers.configurationfiles()
- return instance.specification or {}
-end
-local function load_file_databases()
- instance.loaderror=false
- instance.files={}
- if not instance.renewcache then
- local hashes=instance.hashes
- for k=1,#hashes do
- local hash=hashes[k]
- resolvers.hashers.byscheme(hash.type,hash.name)
- if instance.loaderror then break end
- end
- end
-end
-local function locate_file_databases()
- local texmfpaths=expandedpathlist("TEXMF")
- if #texmfpaths>0 then
- for i=1,#texmfpaths do
- local path=collapsepath(texmfpaths[i])
- path=gsub(path,"/+$","")
- local stripped=lpegmatch(inhibitstripper,path)
- if stripped~="" then
- local runtime=stripped==path
- path=cleanpath(path)
- local spec=splitmethod(stripped)
- if runtime and (spec.noscheme or spec.scheme=="file") then
- stripped="tree:///"..stripped
- elseif spec.scheme=="cache" or spec.scheme=="file" then
- stripped=spec.path
- end
- if trace_locating then
- if runtime then
- report_resolving("locating list of %a (runtime) (%s)",path,stripped)
- else
- report_resolving("locating list of %a (cached)",path)
- end
- end
- methodhandler('locators',stripped)
- end
- end
- if trace_locating then
- report_resolving()
- end
- elseif trace_locating then
- report_resolving("no texmf paths are defined (using TEXMF)")
- end
-end
-local function generate_file_databases()
- local hashes=instance.hashes
- for k=1,#hashes do
- local hash=hashes[k]
- methodhandler('generators',hash.name)
- end
- if trace_locating then
- report_resolving()
- end
-end
-local function save_file_databases()
- local hashes=instance.hashes
- local files=instance.files
- for i=1,#hashes do
- local hash=hashes[i]
- local cachename=hash.name
- if hash.cache then
- local content=files[cachename]
- caches.collapsecontent(content)
- if trace_locating then
- report_resolving("saving tree %a",cachename)
- end
- caches.savecontent(cachename,"files",content)
- elseif trace_locating then
- report_resolving("not saving runtime tree %a",cachename)
- end
- end
-end
-function resolvers.renew(hashname)
- local files=instance.files
- if hashname and hashname~="" then
- local expanded=expansion(hashname) or ""
- if expanded~="" then
- if trace_locating then
- report_resolving("identifying tree %a from %a",expanded,hashname)
- end
- hashname=expanded
- else
- if trace_locating then
- report_resolving("identifying tree %a",hashname)
- end
- end
- local realpath=resolveprefix(hashname)
- if isdir(realpath) then
- if trace_locating then
- report_resolving("using path %a",realpath)
- end
- methodhandler('generators',hashname)
- local content=files[hashname]
- caches.collapsecontent(content)
- if trace_locating then
- report_resolving("saving tree %a",hashname)
- end
- caches.savecontent(hashname,"files",content)
- else
- report_resolving("invalid path %a",realpath)
- end
- end
-end
-local function load_databases()
- locate_file_databases()
- if instance.diskcache and not instance.renewcache then
- load_file_databases()
- if instance.loaderror then
- generate_file_databases()
- save_file_databases()
- end
- else
- generate_file_databases()
- if instance.renewcache then
- save_file_databases()
- end
- end
-end
-function resolvers.appendhash(type,name,cache)
- local hashed=instance.hashed
- local hashes=instance.hashes
- if hashed[name] then
- else
- if trace_locating then
- report_resolving("hash %a appended",name)
- end
- insert(hashes,{ type=type,name=name,cache=cache } )
- hashed[name]=cache
- end
-end
-function resolvers.prependhash(type,name,cache)
- local hashed=instance.hashed
- local hashes=instance.hashes
- if hashed[name] then
- else
- if trace_locating then
- report_resolving("hash %a prepended",name)
- end
- insert(hashes,1,{ type=type,name=name,cache=cache } )
- hashed[name]=cache
- end
-end
-function resolvers.extendtexmfvariable(specification)
- local environment=instance.environment
- local variables=instance.variables
- local texmftrees=splitpath(getenv("TEXMF"))
- insert(texmftrees,1,specification)
- texmftrees=concat(texmftrees,",")
- if environment["TEXMF"] then
- environment["TEXMF"]=texmftrees
- elseif variables["TEXMF"] then
- variables["TEXMF"]=texmftrees
- else
- end
- reset_hashes()
-end
-function resolvers.splitexpansions()
- local expansions=instance.expansions
- for k,v in next,expansions do
- local t,tn,h,p={},0,{},splitconfigurationpath(v)
- for kk=1,#p do
- local vv=p[kk]
- if vv~="" and not h[vv] then
- tn=tn+1
- t[tn]=vv
- h[vv]=true
- end
- end
- if tn>1 then
- expansions[k]=t
- else
- expansions[k]=t[1]
- end
- end
-end
-function resolvers.datastate()
- return caches.contentstate()
-end
-variable=function(name)
- local variables=instance.variables
- local name=name and lpegmatch(dollarstripper,name)
- local result=name and variables[name]
- return result~=nil and result or ""
-end
-expansion=function(name)
- local expansions=instance.expansions
- local name=name and lpegmatch(dollarstripper,name)
- local result=name and expansions[name]
- return result~=nil and result or ""
-end
-resolvers.variable=variable
-resolvers.expansion=expansion
-unexpandedpathlist=function(str)
- local pth=variable(str)
- local lst=splitpath(pth)
- return expandedpathfromlist(lst)
-end
-function resolvers.unexpandedpath(str)
- return joinpath(unexpandedpathlist(str))
-end
-function resolvers.pushpath(name)
- local pathstack=instance.pathstack
- local lastpath=pathstack[#pathstack]
- local pluspath=filedirname(name)
- if lastpath then
- lastpath=collapsepath(filejoin(lastpath,pluspath))
- else
- lastpath=collapsepath(pluspath)
- end
- insert(pathstack,lastpath)
- if trace_paths then
- report_resolving("pushing path %a",lastpath)
- end
-end
-function resolvers.poppath()
- local pathstack=instance.pathstack
- if trace_paths and #pathstack>0 then
- report_resolving("popping path %a",pathstack[#pathstack])
- end
- remove(pathstack)
-end
-function resolvers.stackpath()
- local pathstack=instance.pathstack
- local currentpath=pathstack[#pathstack]
- return currentpath~="" and currentpath or nil
-end
-local done={}
-function resolvers.resetextrapaths()
- local extra_paths=instance.extra_paths
- if not extra_paths then
- done={}
- instance.extra_paths={}
- elseif #ep>0 then
- done={}
- reset_caches()
- end
-end
-function resolvers.getextrapaths()
- return instance.extra_paths or {}
-end
-function resolvers.registerextrapath(paths,subpaths)
- if not subpaths or subpaths=="" then
- if not paths or path=="" then
- return
- elseif done[paths] then
- return
- end
- end
- local paths=settings_to_array(paths)
- local subpaths=settings_to_array(subpaths)
- local extra_paths=instance.extra_paths or {}
- local oldn=#extra_paths
- local newn=oldn
- local nofpaths=#paths
- local nofsubpaths=#subpaths
- if nofpaths>0 then
- if nofsubpaths>0 then
- for i=1,nofpaths do
- local p=paths[i]
- for j=1,nofsubpaths do
- local s=subpaths[j]
- local ps=p.."/"..s
- if not done[ps] then
- newn=newn+1
- extra_paths[newn]=cleanpath(ps)
- done[ps]=true
- end
- end
- end
- else
- for i=1,nofpaths do
- local p=paths[i]
- if not done[p] then
- newn=newn+1
- extra_paths[newn]=cleanpath(p)
- done[p]=true
- end
- end
- end
- elseif nofsubpaths>0 then
- for i=1,oldn do
- for j=1,nofsubpaths do
- local s=subpaths[j]
- local ps=extra_paths[i].."/"..s
- if not done[ps] then
- newn=newn+1
- extra_paths[newn]=cleanpath(ps)
- done[ps]=true
- end
- end
- end
- end
- if newn>0 then
- instance.extra_paths=extra_paths
- end
- if newn~=oldn then
- reset_caches()
- end
-end
-function resolvers.pushextrapath(path)
- local paths=settings_to_array(path)
- local extra_stack=instance.extra_stack
- if extra_stack then
- insert(extra_stack,1,paths)
- else
- instance.extra_stack={ paths }
- end
- reset_caches()
-end
-function resolvers.popextrapath()
- local extra_stack=instance.extra_stack
- if extra_stack then
- reset_caches()
- return remove(extra_stack,1)
- end
-end
-local function made_list(instance,list,extra_too)
- local done={}
- local new={}
- local newn=0
- local function add(p)
- for k=1,#p do
- local v=p[k]
- if not done[v] then
- done[v]=true
- newn=newn+1
- new[newn]=v
- end
- end
- end
- for k=1,#list do
- local v=list[k]
- if done[v] then
- elseif find(v,"^[%.%/]$") then
- done[v]=true
- newn=newn+1
- new[newn]=v
- else
- break
- end
- end
- if extra_too then
- local extra_stack=instance.extra_stack
- local extra_paths=instance.extra_paths
- if extra_stack and #extra_stack>0 then
- for k=1,#extra_stack do
- add(extra_stack[k])
- end
- end
- if extra_paths and #extra_paths>0 then
- add(extra_paths)
- end
- end
- add(list)
- return new
-end
-expandedpathlist=function(str,extra_too)
- if not str then
- return {}
- elseif instance.savelists then
- str=lpegmatch(dollarstripper,str)
- local lists=instance.lists
- local lst=lists[str]
- if not lst then
- local l=made_list(instance,splitpath(expansion(str)),extra_too)
- lst=expandedpathfromlist(l)
- lists[str]=lst
- end
- return lst
- else
- local lst=splitpath(expansion(str))
- return made_list(instance,expandedpathfromlist(lst),extra_too)
- end
-end
-resolvers.expandedpathlist=expandedpathlist
-resolvers.unexpandedpathlist=unexpandedpathlist
-function resolvers.cleanpathlist(str)
- local t=expandedpathlist(str)
- if t then
- for i=1,#t do
- t[i]=collapsepath(cleanpath(t[i]))
- end
- end
- return t
-end
-function resolvers.expandpath(str)
- return joinpath(expandedpathlist(str))
-end
-local function expandedpathlistfromvariable(str)
- str=lpegmatch(dollarstripper,str)
- local tmp=resolvers.variableofformatorsuffix(str)
- return expandedpathlist(tmp~="" and tmp or str)
-end
-function resolvers.expandpathfromvariable(str)
- return joinpath(expandedpathlistfromvariable(str))
-end
-resolvers.expandedpathlistfromvariable=expandedpathlistfromvariable
-function resolvers.cleanedpathlist(v)
- local t=expandedpathlist(v)
- for i=1,#t do
- t[i]=resolveprefix(cleanpath(t[i]))
- end
- return t
-end
-function resolvers.expandbraces(str)
- local pth=expandedpathfromlist(splitpath(str))
- return joinpath(pth)
-end
-function resolvers.registerfilehash(name,content,someerror)
- local files=instance.files
- if content then
- files[name]=content
- else
- files[name]={}
- if somerror==true then
- instance.loaderror=someerror
- end
- end
-end
-function resolvers.getfilehashes()
- return instance and instance.files or {}
-end
-function resolvers.gethashes()
- return instance and instance.hashes or {}
-end
-function resolvers.renewcache()
- if instance then
- instance.renewcache=true
- end
-end
-local function isreadable(name)
- local readable=isfile(name)
- if trace_details then
- if readable then
- report_resolving("file %a is readable",name)
- else
- report_resolving("file %a is not readable",name)
- end
- end
- return readable
-end
-local function collect_files(names)
- local filelist={}
- local noffiles=0
- local function check(hash,root,pathname,path,basename,name)
- if not pathname or find(path,pathname) then
- local variant=hash.type
- local search=filejoin(root,path,name)
- local result=methodhandler('concatinators',variant,root,path,name)
- if trace_details then
- report_resolving("match: variant %a, search %a, result %a",variant,search,result)
- end
- noffiles=noffiles+1
- filelist[noffiles]={ variant,search,result }
- end
- end
- for k=1,#names do
- local filename=names[k]
- if trace_details then
- report_resolving("checking name %a",filename)
- end
- local basename=filebasename(filename)
- local pathname=filedirname(filename)
- if pathname=="" or find(pathname,"^%.") then
- pathname=false
- else
- pathname=gsub(pathname,"%*",".*")
- pathname="/"..pathname.."$"
- end
- local hashes=instance.hashes
- local files=instance.files
- for h=1,#hashes do
- local hash=hashes[h]
- local hashname=hash.name
- local content=hashname and files[hashname]
- if content then
- if trace_details then
- report_resolving("deep checking %a, base %a, pattern %a",hashname,basename,pathname)
- end
- local path,name=lookup(content,basename)
- if path then
- local metadata=content.metadata
- local realroot=metadata and metadata.path or hashname
- if type(path)=="string" then
- check(hash,realroot,pathname,path,basename,name)
- else
- for i=1,#path do
- check(hash,realroot,pathname,path[i],basename,name)
- end
- end
- end
- elseif trace_locating then
- report_resolving("no match in %a (%s)",hashname,basename)
- end
- end
- end
- return noffiles>0 and filelist or nil
-end
-local fit={}
-function resolvers.registerintrees(filename,format,filetype,usedmethod,foundname)
- local foundintrees=instance.foundintrees
- if usedmethod=="direct" and filename==foundname and fit[foundname] then
- else
- local collapsed=collapsepath(foundname,true)
- local t={
- filename=filename,
- format=format~="" and format or nil,
- filetype=filetype~="" and filetype or nil,
- usedmethod=usedmethod,
- foundname=foundname,
- fullname=collapsed,
- }
- fit[foundname]=t
- foundintrees[#foundintrees+1]=t
- end
-end
-function resolvers.foundintrees()
- return instance.foundintrees or {}
-end
-function resolvers.foundintree(fullname)
- local f=fit[fullname]
- return f and f.usedmethod=="database"
-end
-local function can_be_dir(name)
- local fakepaths=instance.fakepaths
- if not fakepaths[name] then
- if isdir(name) then
- fakepaths[name]=1
- else
- fakepaths[name]=2
- end
- end
- return fakepaths[name]==1
-end
-local preparetreepattern=Cs((P(".")/"%%."+P("-")/"%%-"+P(1))^0*Cc("$"))
-local collect_instance_files
-local function find_analyze(filename,askedformat,allresults)
- local filetype=''
- local filesuffix=suffixonly(filename)
- local wantedfiles={}
- wantedfiles[#wantedfiles+1]=filename
- if askedformat=="" then
- if filesuffix=="" or not suffixmap[filesuffix] then
- local defaultsuffixes=resolvers.defaultsuffixes
- for i=1,#defaultsuffixes do
- local forcedname=filename..'.'..defaultsuffixes[i]
- wantedfiles[#wantedfiles+1]=forcedname
- filetype=formatofsuffix(forcedname)
- if trace_locating then
- report_resolving("forcing filetype %a",filetype)
- end
- end
- else
- filetype=formatofsuffix(filename)
- if trace_locating then
- report_resolving("using suffix based filetype %a",filetype)
- end
- end
- else
- if filesuffix=="" or not suffixmap[filesuffix] then
- local format_suffixes=suffixes[askedformat]
- if format_suffixes then
- for i=1,#format_suffixes do
- wantedfiles[#wantedfiles+1]=filename.."."..format_suffixes[i]
- end
- end
- end
- filetype=askedformat
- if trace_locating then
- report_resolving("using given filetype %a",filetype)
- end
- end
- return filetype,wantedfiles
-end
-local function find_direct(filename,allresults)
- if not dangerous[askedformat] and isreadable(filename) then
- if trace_details then
- report_resolving("file %a found directly",filename)
- end
- return "direct",{ filename }
- end
-end
-local function find_wildcard(filename,allresults)
- if find(filename,'*',1,true) then
- if trace_locating then
- report_resolving("checking wildcard %a",filename)
- end
- local result=resolvers.findwildcardfiles(filename)
- if result then
- return "wildcard",result
- end
- end
-end
-local function find_qualified(filename,allresults,askedformat,alsostripped)
- if not is_qualified_path(filename) then
- return
- end
- if trace_locating then
- report_resolving("checking qualified name %a",filename)
- end
- if isreadable(filename) then
- if trace_details then
- report_resolving("qualified file %a found",filename)
- end
- return "qualified",{ filename }
- end
- if trace_details then
- report_resolving("locating qualified file %a",filename)
- end
- local forcedname,suffix="",suffixonly(filename)
- if suffix=="" then
- local format_suffixes=askedformat=="" and resolvers.defaultsuffixes or suffixes[askedformat]
- if format_suffixes then
- for i=1,#format_suffixes do
- local suffix=format_suffixes[i]
- forcedname=filename.."."..suffix
- if isreadable(forcedname) then
- if trace_locating then
- report_resolving("no suffix, forcing format filetype %a",suffix)
- end
- return "qualified",{ forcedname }
- end
- end
- end
- end
- if alsostripped and suffix and suffix~="" then
- local basename=filebasename(filename)
- local pattern=lpegmatch(preparetreepattern,filename)
- local savedformat=askedformat
- local format=savedformat or ""
- if format=="" then
- askedformat=formatofsuffix(suffix)
- end
- if not format then
- askedformat="othertextfiles"
- end
- if basename~=filename then
- local resolved=collect_instance_files(basename,askedformat,allresults)
- if #resolved==0 then
- local lowered=lower(basename)
- if filename~=lowered then
- resolved=collect_instance_files(lowered,askedformat,allresults)
- end
- end
- resolvers.format=savedformat
- if #resolved>0 then
- local result={}
- for r=1,#resolved do
- local rr=resolved[r]
- if find(rr,pattern) then
- result[#result+1]=rr
- end
- end
- if #result>0 then
- return "qualified",result
- end
- end
- end
- end
-end
-local function check_subpath(fname)
- if isreadable(fname) then
- if trace_details then
- report_resolving("found %a by deep scanning",fname)
- end
- return fname
- end
-end
-local function makepathlist(list,filetype)
- local typespec=resolvers.variableofformat(filetype)
- local pathlist=expandedpathlist(typespec,filetype and usertypes[filetype])
- local entry={}
- if pathlist and #pathlist>0 then
- for k=1,#pathlist do
- local path=pathlist[k]
- local prescanned=find(path,'^!!')
- local resursive=find(path,'//$')
- local pathname=lpegmatch(inhibitstripper,path)
- local expression=makepathexpression(pathname)
- local barename=gsub(pathname,"/+$","")
- barename=resolveprefix(barename)
- local scheme=urlhasscheme(barename)
- local schemename=gsub(barename,"%.%*$",'')
- entry[k]={
- path=path,
- pathname=pathname,
- prescanned=prescanned,
- recursive=recursive,
- expression=expression,
- barename=barename,
- scheme=scheme,
- schemename=schemename,
- }
- end
- entry.typespec=typespec
- list[filetype]=entry
- else
- list[filetype]=false
- end
- return entry
-end
-local function find_intree(filename,filetype,wantedfiles,allresults)
- local pathlists=instance.pathlists
- if not pathlists then
- pathlists=setmetatableindex({},makepathlist)
- instance.pathlists=pathlists
- end
- local pathlist=pathlists[filetype]
- if pathlist then
- local method="intree"
- local filelist=collect_files(wantedfiles)
- local dirlist={}
- local result={}
- if filelist then
- for i=1,#filelist do
- dirlist[i]=filedirname(filelist[i][3]).."/"
- end
- end
- if trace_details then
- report_resolving("checking filename %a in tree",filename)
- end
- for k=1,#pathlist do
- local entry=pathlist[k]
- local path=entry.path
- local pathname=entry.pathname
- local done=false
- if filelist then
- local expression=entry.expression
- if trace_details then
- report_resolving("using pattern %a for path %a",expression,pathname)
- end
- for k=1,#filelist do
- local fl=filelist[k]
- local f=fl[2]
- local d=dirlist[k]
- if find(d,expression) or find(resolveprefix(d),expression) then
- result[#result+1]=resolveprefix(fl[3])
- done=true
- if allresults then
- if trace_details then
- report_resolving("match to %a in hash for file %a and path %a, continue scanning",expression,f,d)
- end
- else
- if trace_details then
- report_resolving("match to %a in hash for file %a and path %a, quit scanning",expression,f,d)
- end
- break
- end
- elseif trace_details then
- report_resolving("no match to %a in hash for file %a and path %a",expression,f,d)
- end
- end
- end
- if done then
- method="database"
- else
- method="filesystem"
- local scheme=entry.scheme
- if not scheme or scheme=="file" then
- local pname=entry.schemename
- if not find(pname,"*",1,true) then
- if can_be_dir(pname) then
- if not done and not entry.prescanned then
- if trace_details then
- report_resolving("quick root scan for %a",pname)
- end
- for k=1,#wantedfiles do
- local w=wantedfiles[k]
- local fname=check_subpath(filejoin(pname,w))
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- end
- if not done and entry.recursive then
- if trace_details then
- report_resolving("scanning filesystem for %a",pname)
- end
- local files=resolvers.simplescanfiles(pname,false,true)
- for k=1,#wantedfiles do
- local w=wantedfiles[k]
- local subpath=files[w]
- if not subpath or subpath=="" then
- elseif type(subpath)=="string" then
- local fname=check_subpath(filejoin(pname,subpath,w))
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- else
- for i=1,#subpath do
- local sp=subpath[i]
- if sp=="" then
- else
- local fname=check_subpath(filejoin(pname,sp,w))
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- end
- end
- if done and not allresults then
- break
- end
- end
- end
- end
- end
- end
- else
- end
- else
- for k=1,#wantedfiles do
- local pname=entry.barename
- local fname=methodhandler('finders',pname.."/"..wantedfiles[k])
- if fname then
- result[#result+1]=fname
- done=true
- if not allresults then
- break
- end
- end
- end
- end
- end
- if done and not allresults then
- break
- end
- end
- if #result>0 then
- return method,result
- end
- end
-end
-local function find_onpath(filename,filetype,wantedfiles,allresults)
- if trace_details then
- report_resolving("checking filename %a, filetype %a, wanted files %a",filename,filetype,concat(wantedfiles," | "))
- end
- local result={}
- for k=1,#wantedfiles do
- local fname=wantedfiles[k]
- if fname and isreadable(fname) then
- filename=fname
- result[#result+1]=filejoin('.',fname)
- if not allresults then
- break
- end
- end
- end
- if #result>0 then
- return "onpath",result
- end
-end
-local function find_otherwise(filename,filetype,wantedfiles,allresults)
- local filelist=collect_files(wantedfiles)
- local fl=filelist and filelist[1]
- if fl then
- return "otherwise",{ resolveprefix(fl[3]) }
- end
-end
-collect_instance_files=function(filename,askedformat,allresults)
- if not filename or filename=="" then
- return {}
- end
- askedformat=askedformat or ""
- filename=collapsepath(filename,".")
- filename=gsub(filename,"^%./",getcurrentdir().."/")
- if allresults then
- local filetype,wantedfiles=find_analyze(filename,askedformat)
- local results={
- { find_direct (filename,true) },
- { find_wildcard (filename,true) },
- { find_qualified(filename,true,askedformat) },
- { find_intree (filename,filetype,wantedfiles,true) },
- { find_onpath (filename,filetype,wantedfiles,true) },
- { find_otherwise(filename,filetype,wantedfiles,true) },
- }
- local result={}
- local status={}
- local done={}
- for k,r in next,results do
- local method,list=r[1],r[2]
- if method and list then
- for i=1,#list do
- local c=collapsepath(list[i])
- if not done[c] then
- result[#result+1]=c
- done[c]=true
- end
- status[#status+1]=formatters["%-10s: %s"](method,c)
- end
- end
- end
- if trace_details then
- report_resolving("lookup status: %s",table.serialize(status,filename))
- end
- return result,status
- else
- local method,result,stamp,filetype,wantedfiles
- if instance.remember then
- if askedformat=="" then
- stamp=formatters["%s::%s"](suffixonly(filename),filename)
- else
- stamp=formatters["%s::%s"](askedformat,filename)
- end
- result=stamp and instance.found[stamp]
- if result then
- if trace_locating then
- report_resolving("remembered file %a",filename)
- end
- return result
- end
- end
- method,result=find_direct(filename)
- if not result then
- method,result=find_wildcard(filename)
- if not result then
- method,result=find_qualified(filename,false,askedformat)
- if not result then
- filetype,wantedfiles=find_analyze(filename,askedformat)
- method,result=find_intree(filename,filetype,wantedfiles)
- if not result then
- method,result=find_onpath(filename,filetype,wantedfiles)
- if resolve_otherwise and not result then
- method,result=find_otherwise(filename,filetype,wantedfiles)
- end
- end
- end
- end
- end
- if result and #result>0 then
- local foundname=collapsepath(result[1])
- resolvers.registerintrees(filename,askedformat,filetype,method,foundname)
- result={ foundname }
- else
- result={}
- end
- if stamp then
- if trace_locating then
- report_resolving("remembering file %a using hash %a",filename,stamp)
- end
- instance.found[stamp]=result
- end
- return result
- end
-end
-local function findfiles(filename,filetype,allresults)
- if not filename or filename=="" then
- return {}
- end
- if allresults==nil then
- allresults=true
- end
- local result,status=collect_instance_files(filename,filetype or "",allresults)
- if not result or #result==0 then
- local lowered=lower(filename)
- if filename~=lowered then
- result,status=collect_instance_files(lowered,filetype or "",allresults)
- end
- end
- return result or {},status
-end
-local function findfile(filename,filetype)
- if not filename or filename=="" then
- return ""
- else
- return findfiles(filename,filetype,false)[1] or ""
- end
-end
-resolvers.findfiles=findfiles
-resolvers.findfile=findfile
-resolvers.find_file=findfile
-resolvers.find_files=findfiles
-function resolvers.findpath(filename,filetype)
- return filedirname(findfiles(filename,filetype,false)[1] or "")
-end
-local function findgivenfiles(filename,allresults)
- local hashes=instance.hashes
- local files=instance.files
- local base=filebasename(filename)
- local result={}
- local function okay(hash,path,name)
- local found=methodhandler('concatinators',hash.type,hash.name,path,name)
- if found and found~="" then
- result[#result+1]=resolveprefix(found)
- return not allresults
- end
- end
- for k=1,#hashes do
- local hash=hashes[k]
- local content=files[hash.name]
- if content then
- local path,name=lookup(content,base)
- if not path then
- elseif type(path)=="string" then
- if okay(hash,path,name) then
- return result
- end
- else
- for i=1,#path do
- if okay(hash,path[i],name) then
- return result
- end
- end
- end
- end
- end
- return result
-end
-function resolvers.findgivenfiles(filename)
- return findgivenfiles(filename,true)
-end
-function resolvers.findgivenfile(filename)
- return findgivenfiles(filename,false)[1] or ""
-end
-local makewildcard=Cs(
- (P("^")^0*P("/")*P(-1)+P(-1))/".*"+(P("^")^0*P("/")/"")^0*(P("*")/".*"+P("-")/"%%-"+P(".")/"%%."+P("?")/"."+P("\\")/"/"+P(1))^0
-)
-function resolvers.wildcardpattern(pattern)
- return lpegmatch(makewildcard,pattern) or pattern
-end
-local function findwildcardfiles(filename,allresults,result)
- local files=instance.files
- local hashes=instance.hashes
- local result=result or {}
- local base=filebasename(filename)
- local dirn=filedirname(filename)
- local path=lower(lpegmatch(makewildcard,dirn) or dirn)
- local name=lower(lpegmatch(makewildcard,base) or base)
- if find(name,"*",1,true) then
- local function okay(found,path,base,hashname,hashtype)
- if find(found,path) then
- local full=methodhandler('concatinators',hashtype,hashname,found,base)
- if full and full~="" then
- result[#result+1]=resolveprefix(full)
- return not allresults
- end
- end
- end
- for k=1,#hashes do
- local hash=hashes[k]
- local hashname=hash.name
- local hashtype=hash.type
- if hashname and hashtype then
- for found,base in filtered(files[hashname],name) do
- if type(found)=='string' then
- if okay(found,path,base,hashname,hashtype) then
- break
- end
- else
- for i=1,#found do
- if okay(found[i],path,base,hashname,hashtype) then
- break
- end
- end
- end
- end
- end
- end
- else
- local function okayokay(found,path,base,hashname,hashtype)
- if find(found,path) then
- local full=methodhandler('concatinators',hashtype,hashname,found,base)
- if full and full~="" then
- result[#result+1]=resolveprefix(full)
- return not allresults
- end
- end
- end
- for k=1,#hashes do
- local hash=hashes[k]
- local hashname=hash.name
- local hashtype=hash.type
- if hashname and hashtype then
- local found,base=lookup(content,base)
- if not found then
- elseif type(found)=='string' then
- if okay(found,path,base,hashname,hashtype) then
- break
- end
- else
- for i=1,#found do
- if okay(found[i],path,base,hashname,hashtype) then
- break
- end
- end
- end
- end
- end
- end
- return result
-end
-function resolvers.findwildcardfiles(filename,result)
- return findwildcardfiles(filename,true,result)
-end
-function resolvers.findwildcardfile(filename)
- return findwildcardfiles(filename,false)[1] or ""
-end
-do
- local starttiming=statistics.starttiming
- local stoptiming=statistics.stoptiming
- local elapsedtime=statistics.elapsedtime
- function resolvers.starttiming()
- starttiming(instance)
- end
- function resolvers.stoptiming()
- stoptiming(instance)
- end
- function resolvers.loadtime()
- return elapsedtime(instance)
- end
-end
-function resolvers.automount()
-end
-function resolvers.load(option)
- resolvers.starttiming()
- identify_configuration_files()
- load_configuration_files()
- if option~="nofiles" then
- load_databases()
- resolvers.automount()
- end
- resolvers.stoptiming()
- local files=instance.files
- return files and next(files) and true
-end
-local function report(str)
- if trace_locating then
- report_resolving(str)
- else
- print(str)
- end
-end
-function resolvers.dowithfilesandreport(command,files,...)
- if files and #files>0 then
- if trace_locating then
- report('')
- end
- if type(files)=="string" then
- files={ files }
- end
- for f=1,#files do
- local file=files[f]
- local result=command(file,...)
- if type(result)=='string' then
- report(result)
- else
- for i=1,#result do
- report(result[i])
- end
- end
- end
- end
-end
-function resolvers.showpath(str)
- return joinpath(expandedpathlist(resolvers.formatofvariable(str)))
-end
-function resolvers.registerfile(files,name,path)
- if files[name] then
- if type(files[name])=='string' then
- files[name]={ files[name],path }
- else
- files[name]=path
- end
- else
- files[name]=path
- end
-end
-function resolvers.dowithpath(name,func)
- local pathlist=expandedpathlist(name)
- for i=1,#pathlist do
- func("^"..cleanpath(pathlist[i]))
- end
-end
-function resolvers.dowithvariable(name,func)
- func(expandedvariable(name))
-end
-function resolvers.locateformat(name)
- local engine=environment.ownmain or "luatex"
- local barename=removesuffix(file.basename(name))
- local fullname=addsuffix(barename,"fmt")
- local fmtname=caches.getfirstreadablefile(fullname,"formats",engine) or ""
- if fmtname=="" then
- fmtname=findfile(fullname)
- fmtname=cleanpath(fmtname)
- end
- if fmtname~="" then
- local barename=removesuffix(fmtname)
- local luaname=addsuffix(barename,luasuffixes.lua)
- local lucname=addsuffix(barename,luasuffixes.luc)
- local luiname=addsuffix(barename,luasuffixes.lui)
- if isfile(luiname) then
- return fmtname,luiname
- elseif isfile(lucname) then
- return fmtname,lucname
- elseif isfile(luaname) then
- return fmtname,luaname
- end
- end
- return nil,nil
-end
-function resolvers.booleanvariable(str,default)
- local b=expansion(str)
- if b=="" then
- return default
- else
- b=toboolean(b)
- return (b==nil and default) or b
- end
-end
-function resolvers.dowithfilesintree(pattern,handle,before,after)
- local hashes=instance.hashes
- local files=instance.files
- for i=1,#hashes do
- local hash=hashes[i]
- local blobtype=hash.type
- local blobpath=hash.name
- if blobtype and blobpath then
- local total=0
- local checked=0
- local done=0
- if before then
- before(blobtype,blobpath,pattern)
- end
- for path,name in filtered(files[blobpath],pattern) do
- if type(path)=="string" then
- checked=checked+1
- if handle(blobtype,blobpath,path,name) then
- done=done+1
- end
- else
- checked=checked+#path
- for i=1,#path do
- if handle(blobtype,blobpath,path[i],name) then
- done=done+1
- end
- end
- end
- end
- if after then
- after(blobtype,blobpath,pattern,checked,done)
- end
- end
- end
-end
-function resolvers.knownvariables(pattern)
- if instance then
- local environment=instance.environment
- local variables=instance.variables
- local expansions=instance.expansions
- local order=instance.order
- local pattern=upper(pattern or "")
- local result={}
- for i=1,#order do
- for key in next,order[i] do
- if result[key]==nil and key~="" and (pattern=="" or find(upper(key),pattern)) then
- result[key]={
- environment=rawget(environment,key),
- variable=key,
- expansion=expansions[key],
- resolved=resolveprefix(expansions[key]),
- }
- end
- end
- end
- return result
- else
- return {}
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-pre"] = package.loaded["data-pre"] or true
-
--- original size: 5088, stripped down to: 3144
-
-if not modules then modules={} end modules ['data-pre']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local insert,remove=table.insert,table.remove
-local resolvers=resolvers
-local prefixes=resolvers.prefixes
-local cleanpath=resolvers.cleanpath
-local findgivenfile=resolvers.findgivenfile
-local expansion=resolvers.expansion
-local getenv=resolvers.getenv
-local basename=file.basename
-local dirname=file.dirname
-local joinpath=file.join
-local isfile=lfs.isfile
-prefixes.environment=function(str)
- return cleanpath(expansion(str))
-end
-local function relative(str,n)
- if not isfile(str) then
- local pstr="./"..str
- if isfile(pstr) then
- str=pstr
- else
- local p="../"
- for i=1,n or 2 do
- local pstr=p..str
- if isfile(pstr) then
- str=pstr
- break
- else
- p=p.."../"
- end
- end
- end
- end
- return cleanpath(str)
-end
-local function locate(str)
- local fullname=findgivenfile(str) or ""
- return cleanpath(fullname~="" and fullname or str)
-end
-prefixes.relative=relative
-prefixes.locate=locate
-prefixes.auto=function(str)
- local fullname=relative(str)
- if not isfile(fullname) then
- fullname=locate(str)
- end
- return fullname
-end
-prefixes.filename=function(str)
- local fullname=findgivenfile(str) or ""
- return cleanpath(basename((fullname~="" and fullname) or str))
-end
-prefixes.pathname=function(str)
- local fullname=findgivenfile(str) or ""
- return cleanpath(dirname((fullname~="" and fullname) or str))
-end
-prefixes.selfautoloc=function(str)
- local pth=getenv('SELFAUTOLOC')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.selfautoparent=function(str)
- local pth=getenv('SELFAUTOPARENT')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.selfautodir=function(str)
- local pth=getenv('SELFAUTODIR')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.home=function(str)
- local pth=getenv('HOME')
- return cleanpath(str and joinpath(pth,str) or pth)
-end
-prefixes.env=prefixes.environment
-prefixes.rel=prefixes.relative
-prefixes.loc=prefixes.locate
-prefixes.kpse=prefixes.locate
-prefixes.full=prefixes.locate
-prefixes.file=prefixes.filename
-prefixes.path=prefixes.pathname
-local inputstack={}
-local stackpath=resolvers.stackpath
-local function toppath()
- if not inputstack then
- return "."
- end
- local pathname=dirname(inputstack[#inputstack] or "")
- if pathname=="" then
- return "."
- else
- return pathname
- end
-end
-local function jobpath()
- local path=stackpath()
- if not path or path=="" then
- return "."
- else
- return path
- end
-end
-local function pushinputname(name)
- insert(inputstack,name)
-end
-local function popinputname(name)
- return remove(inputstack)
-end
-resolvers.toppath=toppath
-resolvers.jobpath=jobpath
-resolvers.pushinputname=pushinputname
-resolvers.popinputname=popinputname
-prefixes.toppath=function(str) return cleanpath(joinpath(toppath(),str)) end
-prefixes.jobpath=function(str) return cleanpath(joinpath(jobpath(),str)) end
-resolvers.setdynamic("toppath")
-resolvers.setdynamic("jobpath")
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-inp"] = package.loaded["data-inp"] or true
-
--- original size: 910, stripped down to: 818
-
-if not modules then modules={} end modules ['data-inp']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local allocate=utilities.storage.allocate
-local resolvers=resolvers
-local methodhandler=resolvers.methodhandler
-local registermethod=resolvers.registermethod
-local finders=allocate { helpers={},notfound=function() end }
-local openers=allocate { helpers={},notfound=function() end }
-local loaders=allocate { helpers={},notfound=function() return false,nil,0 end }
-registermethod("finders",finders,"uri")
-registermethod("openers",openers,"uri")
-registermethod("loaders",loaders,"uri")
-resolvers.finders=finders
-resolvers.openers=openers
-resolvers.loaders=loaders
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-out"] = package.loaded["data-out"] or true
-
--- original size: 551, stripped down to: 470
-
-if not modules then modules={} end modules ['data-out']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local allocate=utilities.storage.allocate
-local resolvers=resolvers
-local registermethod=resolvers.registermethod
-local savers=allocate { helpers={} }
-resolvers.savers=savers
-registermethod("savers",savers,"uri")
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-fil"] = package.loaded["data-fil"] or true
-
--- original size: 4365, stripped down to: 3452
-
-if not modules then modules={} end modules ['data-fil']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local ioopen=io.open
-local isdir=lfs.isdir
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_files=logs.reporter("resolvers","files")
-local resolvers=resolvers
-local resolveprefix=resolvers.resolve
-local findfile=resolvers.findfile
-local scanfiles=resolvers.scanfiles
-local registerfilehash=resolvers.registerfilehash
-local appendhash=resolvers.appendhash
-local loadcachecontent=caches.loadcontent
-function resolvers.locators.file(specification)
- local filename=specification.filename
- local realname=resolveprefix(filename)
- if realname and realname~='' and isdir(realname) then
- if trace_locating then
- report_files("file locator %a found as %a",filename,realname)
- end
- appendhash('file',filename,true)
- elseif trace_locating then
- report_files("file locator %a not found",filename)
- end
-end
-function resolvers.hashers.file(specification)
- local pathname=specification.filename
- local content=loadcachecontent(pathname,'files')
- registerfilehash(pathname,content,content==nil)
-end
-function resolvers.generators.file(specification)
- local pathname=specification.filename
- local content=scanfiles(pathname,false,true)
- registerfilehash(pathname,content,true)
-end
-resolvers.concatinators.file=file.join
-local finders=resolvers.finders
-local notfound=finders.notfound
-function finders.file(specification,filetype)
- local filename=specification.filename
- local foundname=findfile(filename,filetype)
- if foundname and foundname~="" then
- if trace_locating then
- report_files("file finder: %a found",filename)
- end
- return foundname
- else
- if trace_locating then
- report_files("file finder: %a not found",filename)
- end
- return notfound()
- end
-end
-local openers=resolvers.openers
-local notfound=openers.notfound
-local overloaded=false
-local function textopener(tag,filename,f)
- return {
- reader=function() return f:read () end,
- close=function() return f:close() end,
- }
-end
-function openers.helpers.textopener(...)
- return textopener(...)
-end
-function openers.helpers.settextopener(opener)
- if overloaded then
- report_files("file opener: %s overloaded","already")
- else
- if trace_locating then
- report_files("file opener: %s overloaded","once")
- end
- overloaded=true
- textopener=opener
- end
-end
-function openers.file(specification,filetype)
- local filename=specification.filename
- if filename and filename~="" then
- local f=ioopen(filename,"r")
- if f then
- if trace_locating then
- report_files("file opener: %a opened",filename)
- end
- return textopener("file",filename,f)
- end
- end
- if trace_locating then
- report_files("file opener: %a not found",filename)
- end
- return notfound()
-end
-local loaders=resolvers.loaders
-local notfound=loaders.notfound
-function loaders.file(specification,filetype)
- local filename=specification.filename
- if filename and filename~="" then
- local f=ioopen(filename,"rb")
- if f then
- if trace_locating then
- report_files("file loader: %a loaded",filename)
- end
- local s=f:read("*a")
- f:close()
- if s then
- return true,s,#s
- end
- end
- end
- if trace_locating then
- report_files("file loader: %a not found",filename)
- end
- return notfound()
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-con"] = package.loaded["data-con"] or true
-
--- original size: 5388, stripped down to: 3685
-
-if not modules then modules={} end modules ['data-con']={
- version=1.100,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local setmetatable=setmetatable
-local format,lower,gsub=string.format,string.lower,string.gsub
-local trace_cache=false trackers.register("resolvers.cache",function(v) trace_cache=v end)
-local trace_containers=false trackers.register("resolvers.containers",function(v) trace_containers=v end)
-local trace_storage=false trackers.register("resolvers.storage",function(v) trace_storage=v end)
-containers=containers or {}
-local containers=containers
-containers.usecache=true
-local getwritablepath=caches.getwritablepath
-local getreadablepaths=caches.getreadablepaths
-local cacheiswritable=caches.is_writable
-local loaddatafromcache=caches.loaddata
-local savedataincache=caches.savedata
-local report_containers=logs.reporter("resolvers","containers")
-local allocated={}
-local mt={
- __index=function(t,k)
- if k=="writable" then
- local writable=getwritablepath(t.category,t.subcategory) or { "." }
- t.writable=writable
- return writable
- elseif k=="readables" then
- local readables=getreadablepaths(t.category,t.subcategory) or { "." }
- t.readables=readables
- return readables
- end
- end,
- __storage__=true
-}
-function containers.define(category,subcategory,version,enabled)
- if category and subcategory then
- local c=allocated[category]
- if not c then
- c={}
- allocated[category]=c
- end
- local s=c[subcategory]
- if not s then
- s={
- category=category,
- subcategory=subcategory,
- storage={},
- enabled=enabled,
- version=version or math.pi,
- trace=false,
- }
- setmetatable(s,mt)
- c[subcategory]=s
- end
- return s
- end
-end
-function containers.is_usable(container,name)
- return container.enabled and caches and cacheiswritable(container.writable,name)
-end
-function containers.is_valid(container,name)
- if name and name~="" then
- local storage=container.storage[name]
- return storage and storage.cache_version==container.version
- else
- return false
- end
-end
-function containers.read(container,name)
- local storage=container.storage
- local stored=storage[name]
- if not stored and container.enabled and caches and containers.usecache then
- stored=loaddatafromcache(container.readables,name,container.writable)
- if stored and stored.cache_version==container.version then
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","load",container.subcategory,name)
- end
- else
- stored=nil
- end
- storage[name]=stored
- elseif stored then
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","reuse",container.subcategory,name)
- end
- end
- return stored
-end
-function containers.write(container,name,data,fast)
- if data then
- data.cache_version=container.version
- if container.enabled and caches then
- local unique=data.unique
- local shared=data.shared
- data.unique=nil
- data.shared=nil
- savedataincache(container.writable,name,data,fast)
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","save",container.subcategory,name)
- end
- data.unique=unique
- data.shared=shared
- end
- if trace_cache or trace_containers then
- report_containers("action %a, category %a, name %a","store",container.subcategory,name)
- end
- container.storage[name]=data
- end
- return data
-end
-function containers.content(container,name)
- return container.storage[name]
-end
-function containers.cleanname(name)
- return (gsub(lower(name),"[^%w\128-\255]+","-"))
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-use"] = package.loaded["data-use"] or true
-
--- original size: 5785, stripped down to: 2905
-
-if not modules then modules={} end modules ['data-use']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local format=string.format
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_mounts=logs.reporter("resolvers","mounts")
-local resolvers=resolvers
-local findfile=resolvers.findfile
-statistics.register("used config file",function() return caches.configfiles() end)
-statistics.register("used cache path",function() return caches.usedpaths() end)
-function statistics.savefmtstatus(texname,formatbanner,sourcefile,banner)
- local enginebanner=status.banner
- if formatbanner and enginebanner and sourcefile then
- local luvname=file.replacesuffix(texname,"luv")
- local luvdata={
- enginebanner=enginebanner,
- formatbanner=formatbanner,
- sourcehash=md5.hex(io.loaddata(findfile(sourcefile)) or "unknown"),
- sourcefile=sourcefile,
- luaversion=LUAVERSION,
- formatid=LUATEXFORMATID,
- functionality=LUATEXFUNCTIONALITY,
- }
- io.savedata(luvname,table.serialize(luvdata,true))
- lua.registerfinalizer(function()
- if jit then
- logs.report("format banner","%s lua: %s jit",banner,LUAVERSION)
- else
- logs.report("format banner","%s lua: %s",banner,LUAVERSION)
- end
- logs.newline()
- end)
- end
-end
-function statistics.checkfmtstatus(texname)
- local enginebanner=status.banner
- if enginebanner and texname then
- local luvname=file.replacesuffix(texname,"luv")
- if lfs.isfile(luvname) then
- local luv=dofile(luvname)
- if luv and luv.sourcefile then
- local sourcehash=md5.hex(io.loaddata(findfile(luv.sourcefile)) or "unknown")
- local luvbanner=luv.enginebanner or "?"
- if luvbanner~=enginebanner then
- return format("engine mismatch (luv: %s <> bin: %s)",luvbanner,enginebanner)
- end
- local luvhash=luv.sourcehash or "?"
- if luvhash~=sourcehash then
- return format("source mismatch (luv: %s <> bin: %s)",luvhash,sourcehash)
- end
- local luvluaversion=luv.luaversion or 0
- local engluaversion=LUAVERSION or 0
- if luvluaversion~=engluaversion then
- return format("lua mismatch (luv: %s <> bin: %s)",luvluaversion,engluaversion)
- end
- local luvfunctionality=luv.functionality or 0
- local engfunctionality=status.development_id or 0
- if luvfunctionality~=engfunctionality then
- return format("functionality mismatch (luv: %s <> bin: %s)",luvfunctionality,engfunctionality)
- end
- local luvformatid=luv.formatid or 0
- local engformatid=status.format_id or 0
- if luvformatid~=engformatid then
- return format("formatid mismatch (luv: %s <> bin: %s)",luvformatid,engformatid)
- end
- else
- return "invalid status file"
- end
- else
- return "missing status file"
- end
- end
- return true
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-zip"] = package.loaded["data-zip"] or true
-
--- original size: 10725, stripped down to: 7949
-
-if not modules then modules={} end modules ['data-zip']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local format,find,match=string.format,string.find,string.match
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_zip=logs.reporter("resolvers","zip")
-local resolvers=resolvers
-local findfile=resolvers.findfile
-local registerfile=resolvers.registerfile
-local splitmethod=resolvers.splitmethod
-local prependhash=resolvers.prependhash
-local starttiming=resolvers.starttiming
-local extendtexmf=resolvers.extendtexmfvariable
-local stoptiming=resolvers.stoptiming
-local urlquery=url.query
-zip=zip or {}
-local zip=zip
-local archives=zip.archives or {}
-zip.archives=archives
-local registeredfiles=zip.registeredfiles or {}
-zip.registeredfiles=registeredfiles
-local zipfiles=utilities.zipfiles
-local openzip,closezip,validfile,wholefile,filehandle,traversezip
-if zipfiles then
- local ipairs=ipairs
- openzip=zipfiles.open
- closezip=zipfiles.close
- validfile=zipfiles.found
- wholefile=zipfiles.unzip
- local listzip=zipfiles.list
- traversezip=function(zfile)
- return ipairs(listzip(zfile))
- end
- local streams=utilities.streams
- local openstream=streams.open
- local readstring=streams.readstring
- local streamsize=streams.size
- local metatable={
- close=streams.close,
- read=function(stream,n)
- readstring(stream,n=="*a" and streamsize(stream) or n)
- end
- }
- filehandle=function(zfile,queryname)
- local data=wholefile(zfile,queryname)
- if data then
- local stream=openstream(data)
- if stream then
- return setmetatableindex(stream,metatable)
- end
- end
- end
-else
- openzip=zip.open
- closezip=zip.close
- validfile=function(zfile,queryname)
- local dfile=zfile:open(queryname)
- if dfile then
- dfile:close()
- return true
- end
- return false
- end
- traversezip=function(zfile)
- return z:files()
- end
- wholefile=function(zfile,queryname)
- local dfile=zfile:open(queryname)
- if dfile then
- local s=dfile:read("*all")
- dfile:close()
- return s
- end
- end
- filehandle=function(zfile,queryname)
- local dfile=zfile:open(queryname)
- if dfile then
- return dfile
- end
- end
-end
-local function validzip(str)
- if not find(str,"^zip://") then
- return "zip:///"..str
- else
- return str
- end
-end
-local function openarchive(name)
- if not name or name=="" then
- return nil
- else
- local arch=archives[name]
- if not arch then
- local full=findfile(name) or ""
- arch=full~="" and openzip(full) or false
- archives[name]=arch
- end
- return arch
- end
-end
-local function closearchive(name)
- if not name or (name=="" and archives[name]) then
- closezip(archives[name])
- archives[name]=nil
- end
-end
-zip.openarchive=openarchive
-zip.closearchive=closearchive
-function resolvers.locators.zip(specification)
- local archive=specification.filename
- local zipfile=archive and archive~="" and openarchive(archive)
- if trace_locating then
- if zipfile then
- report_zip("locator: archive %a found",archive)
- else
- report_zip("locator: archive %a not found",archive)
- end
- end
-end
-function resolvers.concatinators.zip(zipfile,path,name)
- if not path or path=="" then
- return format('%s?name=%s',zipfile,name)
- else
- return format('%s?name=%s/%s',zipfile,path,name)
- end
-end
-local finders=resolvers.finders
-local notfound=finders.notfound
-function finders.zip(specification)
- local original=specification.original
- local archive=specification.filename
- if archive then
- local query=urlquery(specification.query)
- local queryname=query.name
- if queryname then
- local zfile=openarchive(archive)
- if zfile then
- if trace_locating then
- report_zip("finder: archive %a found",archive)
- end
- if validfile(zfile,queryname) then
- if trace_locating then
- report_zip("finder: file %a found",queryname)
- end
- return specification.original
- elseif trace_locating then
- report_zip("finder: file %a not found",queryname)
- end
- elseif trace_locating then
- report_zip("finder: unknown archive %a",archive)
- end
- end
- end
- if trace_locating then
- report_zip("finder: %a not found",original)
- end
- return notfound()
-end
-local openers=resolvers.openers
-local notfound=openers.notfound
-local textopener=openers.helpers.textopener
-function openers.zip(specification)
- local original=specification.original
- local archive=specification.filename
- if archive then
- local query=urlquery(specification.query)
- local queryname=query.name
- if queryname then
- local zfile=openarchive(archive)
- if zfile then
- if trace_locating then
- report_zip("opener; archive %a opened",archive)
- end
- local handle=filehandle(zfile,queryname)
- if handle then
- if trace_locating then
- report_zip("opener: file %a found",queryname)
- end
- return textopener('zip',original,handle)
- elseif trace_locating then
- report_zip("opener: file %a not found",queryname)
- end
- elseif trace_locating then
- report_zip("opener: unknown archive %a",archive)
- end
- end
- end
- if trace_locating then
- report_zip("opener: %a not found",original)
- end
- return notfound()
-end
-local loaders=resolvers.loaders
-local notfound=loaders.notfound
-function loaders.zip(specification)
- local original=specification.original
- local archive=specification.filename
- if archive then
- local query=urlquery(specification.query)
- local queryname=query.name
- if queryname then
- local zfile=openarchive(archive)
- if zfile then
- if trace_locating then
- report_zip("loader: archive %a opened",archive)
- end
- local data=wholefile(zfile,queryname)
- if data then
- if trace_locating then
- report_zip("loader; file %a loaded",original)
- end
- return true,data,#data
- elseif trace_locating then
- report_zip("loader: file %a not found",queryname)
- end
- elseif trace_locating then
- report_zip("loader; unknown archive %a",archive)
- end
- end
- end
- if trace_locating then
- report_zip("loader: %a not found",original)
- end
- return notfound()
-end
-local function registerzipfile(z,tree)
- local names={}
- local files={}
- local remap={}
- local n=0
- local filter=tree=="" and "^(.+)/(.-)$" or format("^%s/(.+)/(.-)$",tree)
- if trace_locating then
- report_zip("registering: using filter %a",filter)
- end
- starttiming()
- for i in traversezip(z) do
- local filename=i.filename
- local path,name=match(filename,filter)
- if not path then
- n=n+1
- registerfile(names,filename,"")
- local usedname=lower(filename)
- files[usedname]=""
- if usedname~=filename then
- remap[usedname]=filename
- end
- elseif name and name~="" then
- n=n+1
- register(names,name,path)
- local usedname=lower(name)
- files[usedname]=path
- if usedname~=name then
- remap[usedname]=name
- end
- else
- end
- end
- stoptiming()
- report_zip("registering: %s files registered",n)
- return {
- files=files,
- remap=remap,
- }
-end
-local function usezipfile(archive)
- local specification=splitmethod(archive)
- local archive=specification.filename
- if archive and not registeredfiles[archive] then
- local z=openarchive(archive)
- if z then
- local tree=urlquery(specification.query).tree or ""
- if trace_locating then
- report_zip("registering: archive %a",archive)
- end
- prependhash('zip',archive)
- extendtexmf(archive)
- registeredfiles[archive]=z
- registerfilehash(archive,registerzipfile(z,tree))
- elseif trace_locating then
- report_zip("registering: unknown archive %a",archive)
- end
- elseif trace_locating then
- report_zip("registering: archive %a not found",archive)
- end
-end
-resolvers.usezipfile=usezipfile
-resolvers.registerzipfile=registerzipfile
-function resolvers.hashers.zip(specification)
- local archive=specification.filename
- if trace_locating then
- report_zip("loading file %a",archive)
- end
- usezipfile(specification.original)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-tre"] = package.loaded["data-tre"] or true
-
--- original size: 10802, stripped down to: 6619
-
-if not modules then modules={} end modules ['data-tre']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type=type
-local find,gsub,lower=string.find,string.gsub,string.lower
-local basename,dirname,joinname=file.basename,file.dirname,file.join
-local globdir,isdir,isfile=dir.glob,lfs.isdir,lfs.isfile
-local P,lpegmatch=lpeg.P,lpeg.match
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local report_trees=logs.reporter("resolvers","trees")
-local resolvers=resolvers
-local finders=resolvers.finders
-local openers=resolvers.openers
-local loaders=resolvers.loaders
-local locators=resolvers.locators
-local hashers=resolvers.hashers
-local generators=resolvers.generators
-do
- local collectors={}
- local found={}
- local notfound=finders.notfound
- function finders.tree(specification)
- local spec=specification.filename
- local okay=found[spec]
- if okay==nil then
- if spec~="" then
- local path=dirname(spec)
- local name=basename(spec)
- if path=="" then
- path="."
- end
- local names=collectors[path]
- if not names then
- local pattern=find(path,"/%*+$") and path or (path.."/*")
- names=globdir(pattern)
- collectors[path]=names
- end
- local pattern="/"..gsub(name,"([%.%-%+])","%%%1").."$"
- for i=1,#names do
- local fullname=names[i]
- if find(fullname,pattern) then
- found[spec]=fullname
- return fullname
- end
- end
- local pattern=lower(pattern)
- for i=1,#names do
- local fullname=lower(names[i])
- if find(fullname,pattern) then
- if isfile(fullname) then
- found[spec]=fullname
- return fullname
- else
- break
- end
- end
- end
- end
- okay=notfound()
- found[spec]=okay
- end
- return okay
- end
-end
-do
- local resolveprefix=resolvers.resolve
- local appendhash=resolvers.appendhash
- local function dolocate(specification)
- local name=specification.filename
- local realname=resolveprefix(name)
- if realname and realname~='' and isdir(realname) then
- if trace_locating then
- report_trees("locator %a found",realname)
- end
- appendhash('tree',name,false)
- elseif trace_locating then
- report_trees("locator %a not found",name)
- end
- end
- locators.tree=dolocate
- locators.dirlist=dolocate
- locators.dirfile=dolocate
-end
-do
- local filegenerator=generators.file
- generators.dirlist=filegenerator
- generators.dirfile=filegenerator
-end
-do
- local filegenerator=generators.file
- local methodhandler=resolvers.methodhandler
- local function dohash(specification)
- local name=specification.filename
- if trace_locating then
- report_trees("analyzing %a",name)
- end
- methodhandler("hashers",name)
- filegenerator(specification)
- end
- hashers.tree=dohash
- hashers.dirlist=dohash
- hashers.dirfile=dohash
-end
-local resolve do
- local collectors={}
- local splitter=lpeg.splitat("/**/")
- local stripper=lpeg.replacer { [P("/")*P("*")^1*P(-1)]="" }
- local loadcontent=caches.loadcontent
- local savecontent=caches.savecontent
- local notfound=finders.notfound
- local scanfiles=resolvers.scanfiles
- local lookup=resolvers.get_from_content
- table.setmetatableindex(collectors,function(t,k)
- local rootname=lpegmatch(stripper,k)
- local dataname=joinname(rootname,"dirlist")
- local content=loadcontent(dataname,"files",dataname)
- if not content then
- content=scanfiles(rootname,nil,nil,false,true)
- savecontent(dataname,"files",content,dataname)
- end
- t[k]=content
- return content
- end)
- local function checked(root,p,n)
- if p then
- if type(p)=="table" then
- for i=1,#p do
- local fullname=joinname(root,p[i],n)
- if isfile(fullname) then
- return fullname
- end
- end
- else
- local fullname=joinname(root,p,n)
- if isfile(fullname) then
- return fullname
- end
- end
- end
- return notfound()
- end
- resolve=function(specification)
- local filename=specification.filename
- if filename~="" then
- local root,rest=lpegmatch(splitter,filename)
- if root and rest then
- local path,name=dirname(rest),basename(rest)
- if name~=rest then
- local content=collectors[root]
- local p,n=lookup(content,name)
- if not p then
- return notfound()
- end
- local pattern=".*/"..path.."$"
- local istable=type(p)=="table"
- if istable then
- for i=1,#p do
- local pi=p[i]
- if pi==path or find(pi,pattern) then
- local fullname=joinname(root,pi,n)
- if isfile(fullname) then
- return fullname
- end
- end
- end
- elseif p==path or find(p,pattern) then
- local fullname=joinname(root,p,n)
- if isfile(fullname) then
- return fullname
- end
- end
- local queries=specification.queries
- if queries and queries.option=="fileonly" then
- return checked(root,p,n)
- else
- return notfound()
- end
- end
- end
- local path=dirname(filename)
- local name=basename(filename)
- local root=lpegmatch(stripper,path)
- local content=collectors[path]
- local p,n=lookup(content,name)
- if p then
- return checked(root,p,n)
- end
- end
- return notfound()
- end
- finders.dirlist=resolve
- function finders.dirfile(specification)
- local queries=specification.queries
- if queries then
- queries.option="fileonly"
- else
- specification.queries={ option="fileonly" }
- end
- return resolve(specification)
- end
-end
-do
- local fileopener=openers.file
- local fileloader=loaders.file
- openers.dirlist=fileopener
- loaders.dirlist=fileloader
- openers.dirfile=fileopener
- loaders.dirfile=fileloader
-end
-do
- local hashfile="dirhash.lua"
- local kind="HASH256"
- local version=1.0
- local loadtable=table.load
- local savetable=table.save
- local loaddata=io.loaddata
- function resolvers.dirstatus(patterns)
- local t=type(patterns)
- if t=="string" then
- patterns={ patterns }
- elseif t~="table" then
- return false
- end
- local status=loadtable(hashfile)
- if not status or status.version~=version or status.kind~=kind then
- status={
- version=1.0,
- kind=kind,
- hashes={},
- }
- end
- local hashes=status.hashes
- local changed={}
- local action=sha2[kind]
- local update={}
- for i=1,#patterns do
- local pattern=patterns[i]
- local files=globdir(pattern)
- for i=1,#files do
- local name=files[i]
- local hash=action(loaddata(name))
- if hashes[name]~=hash then
- changed[#changed+1]=name
- end
- update[name]=hash
- end
- end
- status.hashes=update
- savetable(hashfile,status)
- return #changed>0 and changed or false
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-sch"] = package.loaded["data-sch"] or true
-
--- original size: 6945, stripped down to: 5408
-
-if not modules then modules={} end modules ['data-sch']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local load,tonumber=load,tonumber
-local gsub,format=string.gsub,string.format
-local sortedhash,concat=table.sortedhash,table.concat
-local finders,openers,loaders=resolvers.finders,resolvers.openers,resolvers.loaders
-local addsuffix,suffix,splitbase=file.addsuffix,file.suffix,file.splitbase
-local md5hex=md5.hex
-local trace_schemes=false trackers.register("resolvers.schemes",function(v) trace_schemes=v end)
-local report_schemes=logs.reporter("resolvers","schemes")
-local http=require("socket.http")
-local ltn12=require("ltn12")
-if mbox then mbox=nil end
-local resolvers=resolvers
-local schemes=resolvers.schemes or {}
-resolvers.schemes=schemes
-local cleaners={}
-schemes.cleaners=cleaners
-local threshold=24*60*60
-directives.register("schemes.threshold",function(v) threshold=tonumber(v) or threshold end)
-function cleaners.none(specification)
- return specification.original
-end
-function cleaners.strip(specification)
- local path,name=splitbase(specification.original)
- if path=="" then
- return (gsub(name,"[^%a%d%.]+","-"))
- else
- return (gsub((gsub(path,"%.","-").."-"..name),"[^%a%d%.]+","-"))
- end
-end
-function cleaners.md5(specification)
- return addsuffix(md5hex(specification.original),suffix(specification.path))
-end
-local cleaner=cleaners.strip
-directives.register("schemes.cleanmethod",function(v) cleaner=cleaners[v] or cleaners.strip end)
-function resolvers.schemes.cleanname(specification)
- local hash=cleaner(specification)
- if trace_schemes then
- report_schemes("hashing %a to %a",specification.original,hash)
- end
- return hash
-end
-local cached={}
-local loaded={}
-local reused={}
-local thresholds={}
-local handlers={}
-local runner=sandbox.registerrunner {
- name="curl resolver",
- method="execute",
- program="curl",
- template='--silent --insecure --create-dirs --output "%cachename%" "%original%"',
- checkers={
- cachename="cache",
- original="url",
- }
-}
-local function fetch(specification)
- local original=specification.original
- local scheme=specification.scheme
- local cleanname=schemes.cleanname(specification)
- local cachename=caches.setfirstwritablefile(cleanname,"schemes")
- if not cached[original] then
- statistics.starttiming(schemes)
- if not io.exists(cachename) or (os.difftime(os.time(),lfs.attributes(cachename).modification)>(thresholds[protocol] or threshold)) then
- cached[original]=cachename
- local handler=handlers[scheme]
- if handler then
- if trace_schemes then
- report_schemes("fetching %a, protocol %a, method %a",original,scheme,"built-in")
- end
- logs.flush()
- handler(specification,cachename)
- else
- if trace_schemes then
- report_schemes("fetching %a, protocol %a, method %a",original,scheme,"curl")
- end
- logs.flush()
- runner {
- original=original,
- cachename=cachename,
- }
- end
- end
- if io.exists(cachename) then
- cached[original]=cachename
- if trace_schemes then
- report_schemes("using cached %a, protocol %a, cachename %a",original,scheme,cachename)
- end
- else
- cached[original]=""
- if trace_schemes then
- report_schemes("using missing %a, protocol %a",original,scheme)
- end
- end
- loaded[scheme]=loaded[scheme]+1
- statistics.stoptiming(schemes)
- else
- if trace_schemes then
- report_schemes("reusing %a, protocol %a",original,scheme)
- end
- reused[scheme]=reused[scheme]+1
- end
- return cached[original]
-end
-local function finder(specification,filetype)
- return resolvers.methodhandler("finders",fetch(specification),filetype)
-end
-local opener=openers.file
-local loader=loaders.file
-local function install(scheme,handler,newthreshold)
- handlers [scheme]=handler
- loaded [scheme]=0
- reused [scheme]=0
- finders [scheme]=finder
- openers [scheme]=opener
- loaders [scheme]=loader
- thresholds[scheme]=newthreshold or threshold
-end
-schemes.install=install
-local function http_handler(specification,cachename)
- local tempname=cachename..".tmp"
- local handle=io.open(tempname,"wb")
- local status,message=http.request {
- url=specification.original,
- sink=ltn12.sink.file(handle)
- }
- if not status then
- os.remove(tempname)
- else
- os.remove(cachename)
- os.rename(tempname,cachename)
- end
- return cachename
-end
-install('http',http_handler)
-install('https')
-install('ftp')
-statistics.register("scheme handling time",function()
- local l,r,nl,nr={},{},0,0
- for k,v in sortedhash(loaded) do
- if v>0 then
- nl=nl+1
- l[nl]=k..":"..v
- end
- end
- for k,v in sortedhash(reused) do
- if v>0 then
- nr=nr+1
- r[nr]=k..":"..v
- end
- end
- local n=nl+nr
- if n>0 then
- if nl==0 then l={ "none" } end
- if nr==0 then r={ "none" } end
- return format("%s seconds, %s processed, threshold %s seconds, loaded: %s, reused: %s",
- statistics.elapsedtime(schemes),n,threshold,concat(l," "),concat(l," "))
- else
- return nil
- end
-end)
-local httprequest=http.request
-local toquery=url.toquery
-local function fetchstring(url,data)
- local q=data and toquery(data)
- if q then
- url=url.."?"..q
- end
- local reply=httprequest(url)
- return reply
-end
-schemes.fetchstring=fetchstring
-function schemes.fetchtable(url,data)
- local reply=fetchstring(url,data)
- if reply then
- local s=load("return "..reply)
- if s then
- return s()
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-lua"] = package.loaded["data-lua"] or true
-
--- original size: 4227, stripped down to: 3049
-
-if not modules then modules={} end modules ['data-lua']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local package,lpeg=package,lpeg
-local loadfile=loadfile
-local addsuffix=file.addsuffix
-local P,S,Cs,lpegmatch=lpeg.P,lpeg.S,lpeg.Cs,lpeg.match
-local luasuffixes={ 'tex','lua' }
-local libsuffixes={ 'lib' }
-local luaformats={ 'TEXINPUTS','LUAINPUTS' }
-local libformats={ 'CLUAINPUTS' }
-local helpers=package.helpers or {}
-local methods=helpers.methods or {}
-local resolvers=resolvers
-local resolveprefix=resolvers.resolve
-local expandedpaths=resolvers.expandedpathlistfromvariable
-local findfile=resolvers.findfile
-helpers.report=logs.reporter("resolvers","libraries")
-trackers.register("resolvers.libraries",function(v) helpers.trace=v end)
-trackers.register("resolvers.locating",function(v) helpers.trace=v end)
-helpers.sequence={
- "already loaded",
- "preload table",
- "lua variable format",
- "lib variable format",
- "lua extra list",
- "lib extra list",
- "path specification",
- "cpath specification",
- "all in one fallback",
- "not loaded",
-}
-local pattern=Cs(P("!")^0/""*(P("/")*P(-1)/"/"+P("/")^1/"/"+1)^0)
-function helpers.cleanpath(path)
- return resolveprefix(lpegmatch(pattern,path))
-end
-local loadedaslib=helpers.loadedaslib
-local registerpath=helpers.registerpath
-local lualibfile=helpers.lualibfile
-local luaformatpaths
-local libformatpaths
-local function getluaformatpaths()
- if not luaformatpaths then
- luaformatpaths={}
- for i=1,#luaformats do
- registerpath("lua format","lua",luaformatpaths,expandedpaths(luaformats[i]))
- end
- end
- return luaformatpaths
-end
-local function getlibformatpaths()
- if not libformatpaths then
- libformatpaths={}
- for i=1,#libformats do
- registerpath("lib format","lib",libformatpaths,expandedpaths(libformats[i]))
- end
- end
- return libformatpaths
-end
-local function loadedbyformat(name,rawname,suffixes,islib,what)
- local trace=helpers.trace
- local report=helpers.report
- for i=1,#suffixes do
- local format=suffixes[i]
- local resolved=findfile(name,format) or ""
- if trace then
- report("%s format, identifying %a using format %a",what,name,format)
- end
- if resolved~="" then
- if trace then
- report("%s format, %a found on %a",what,name,resolved)
- end
- if islib then
- return loadedaslib(resolved,rawname)
- else
- return loadfile(resolved)
- end
- end
- end
-end
-helpers.loadedbyformat=loadedbyformat
-methods["lua variable format"]=function(name)
- if helpers.trace then
- helpers.report("%s format, checking %s paths","lua",#getluaformatpaths())
- end
- return loadedbyformat(addsuffix(lualibfile(name),"lua"),name,luasuffixes,false,"lua")
-end
-methods["lib variable format"]=function(name)
- if helpers.trace then
- helpers.report("%s format, checking %s paths","lib",#getlibformatpaths())
- end
- return loadedbyformat(addsuffix(lualibfile(name),os.libsuffix),name,libsuffixes,true,"lib")
-end
-resolvers.loadlualib=require
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-aux"] = package.loaded["data-aux"] or true
-
--- original size: 2610, stripped down to: 2019
-
-if not modules then modules={} end modules ['data-aux']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local find=string.find
-local type,next=type,next
-local addsuffix,removesuffix=file.addsuffix,file.removesuffix
-local loaddata,savedata=io.loaddata,io.savedata
-local trace_locating=false trackers.register("resolvers.locating",function(v) trace_locating=v end)
-local resolvers=resolvers
-local cleanpath=resolvers.cleanpath
-local findfiles=resolvers.findfiles
-local report_scripts=logs.reporter("resolvers","scripts")
-function resolvers.updatescript(oldname,newname)
- local scriptpath="context/lua"
- local oldscript=cleanpath(oldname)
- local newname=addsuffix(newname,"lua")
- local newscripts=findfiles(newname) or {}
- if trace_locating then
- report_scripts("to be replaced old script %a",oldscript)
- end
- if #newscripts==0 then
- if trace_locating then
- report_scripts("unable to locate new script")
- end
- else
- for i=1,#newscripts do
- local newscript=cleanpath(newscripts[i])
- if trace_locating then
- report_scripts("checking new script %a",newscript)
- end
- if oldscript==newscript then
- if trace_locating then
- report_scripts("old and new script are the same")
- end
- elseif not find(newscript,scriptpath,1,true) then
- if trace_locating then
- report_scripts("new script should come from %a",scriptpath)
- end
- elseif not (find(oldscript,removesuffix(newname).."$") or find(oldscript,newname.."$")) then
- if trace_locating then
- report_scripts("invalid new script name")
- end
- else
- local newdata=loaddata(newscript)
- if newdata then
- if trace_locating then
- report_scripts("old script content replaced by new content: %s",oldscript)
- end
- savedata(oldscript,newdata)
- break
- elseif trace_locating then
- report_scripts("unable to load new script")
- end
- end
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-tmf"] = package.loaded["data-tmf"] or true
-
--- original size: 2601, stripped down to: 1549
-
-if not modules then modules={} end modules ['data-tmf']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local resolvers=resolvers
-local report_tds=logs.reporter("resolvers","tds")
-function resolvers.load_tree(tree,resolve)
- if type(tree)=="string" and tree~="" then
- local getenv,setenv=resolvers.getenv,resolvers.setenv
- local texos="texmf-"..os.platform
- local oldroot=environment.texroot
- local newroot=file.collapsepath(tree)
- local newtree=file.join(newroot,texos)
- local newpath=file.join(newtree,"bin")
- if not lfs.isdir(newtree) then
- report_tds("no %a under tree %a",texos,tree)
- os.exit()
- end
- if not lfs.isdir(newpath) then
- report_tds("no '%s/bin' under tree %a",texos,tree)
- os.exit()
- end
- local texmfos=newtree
- environment.texroot=newroot
- environment.texos=texos
- environment.texmfos=texmfos
- if resolve then
- resolvers.luacnfspec=resolvers.resolve(resolvers.luacnfspec)
- end
- setenv('SELFAUTOPARENT',newroot)
- setenv('SELFAUTODIR',newtree)
- setenv('SELFAUTOLOC',newpath)
- setenv('TEXROOT',newroot)
- setenv('TEXOS',texos)
- setenv('TEXMFOS',texmfos)
- setenv('TEXMFCNF',resolvers.luacnfspec,true)
- setenv('PATH',newpath..io.pathseparator..getenv('PATH'))
- report_tds("changing from root %a to %a",oldroot,newroot)
- report_tds("prepending %a to PATH",newpath)
- report_tds("setting TEXMFCNF to %a",resolvers.luacnfspec)
- report_tds()
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["data-lst"] = package.loaded["data-lst"] or true
-
--- original size: 2038, stripped down to: 1696
-
-if not modules then modules={} end modules ['data-lst']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type=type
-local sortedhash=table.sortedhash
-local isdir=lfs.isdir
-local resolvers=resolvers
-local listers=resolvers.listers or {}
-resolvers.listers=listers
-local resolveprefix=resolvers.resolve
-local configurationfiles=resolvers.configurationfiles
-local expandedpathfromlist=resolvers.expandedpathfromlist
-local splitpath=resolvers.splitpath
-local knownvariables=resolvers.knownvariables
-local report_lists=logs.reporter("resolvers","lists")
-local report_resolved=logs.reporter("system","resolved")
-local function tabstr(str)
- if not str then
- return "unset"
- elseif type(str)=='table' then
- return concat(str," | ")
- else
- return str
- end
-end
-function listers.variables(pattern)
- local result=resolvers.knownvariables(pattern)
- for key,value in sortedhash(result) do
- report_lists(key)
- report_lists(" env: %s",tabstr(value.environment))
- report_lists(" var: %s",tabstr(value.variable))
- report_lists(" exp: %s",tabstr(value.expansion))
- report_lists(" res: %s",tabstr(value.resolved))
- end
-end
-function listers.configurations()
- local configurations=configurationfiles()
- for i=1,#configurations do
- report_resolved("file : %s",resolveprefix(configurations[i]))
- end
- report_resolved("")
- local list=expandedpathfromlist(splitpath(resolvers.luacnfspec))
- for i=1,#list do
- local li=resolveprefix(list[i])
- if isdir(li) then
- report_resolved("path - %s",li)
- else
- report_resolved("path + %s",li)
- end
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["libs-ini"] = package.loaded["libs-ini"] or true
-
--- original size: 6459, stripped down to: 4006
-
-if not modules then modules={} end modules ['libs-ini']={
- version=1.001,
- comment="companion to luat-lib.mkiv",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local type,unpack=type,unpack
-local find=string.find
-local nameonly=file.nameonly
-local joinfile=file.join
-local addsuffix=file.addsuffix
-local qualifiedpath=file.is_qualified_path
-local isfile=lfs.isfile
-local findfile=resolvers.findfile
-local expandpaths=resolvers.expandedpathlistfromvariable
-local report=logs.reporter("resolvers","libraries")
-local trace=false
-local silent=false
-trackers.register("resolvers.lib",function(v) trace=v end)
-trackers.register("resolvers.lib.silent",function(v) silent=v end)
-local function findlib(required)
- local suffix=os.libsuffix or "so"
- if not qualifiedpath(required) then
- local list=directives.value("system.librarynames" )
- local only=nameonly(required)
- if type(list)=="table" then
- list=list[only]
- if type(list)~="table" then
- list={ only }
- end
- else
- list={ only }
- end
- if trace then
- report("using lookup list for library %a: % | t",only,list)
- end
- for i=1,#list do
- local name=list[i]
- local found=findfile(name,"lib")
- if not found then
- found=findfile(addsuffix(name,suffix),"lib")
- end
- if found then
- if trace then
- report("library %a resolved via %a path to %a",name,"tds lib",found)
- end
- return found
- end
- end
- if expandpaths then
- local list=expandpaths("PATH")
- local base=addsuffix(only,suffix)
- for i=1,#list do
- local full=joinfile(list[i],base)
- local found=isfile(full) and full
- if found then
- if trace then
- report("library %a resolved via %a path to %a",name,"system",found)
- end
- return found
- end
- end
- end
- elseif isfile(addsuffix(required,suffix)) then
- if trace then
- report("library with qualified name %a %sfound",required,"")
- end
- return required
- else
- if trace then
- report("library with qualified name %a %sfound",required,"not ")
- end
- end
- return false
-end
-local foundlibraries=table.setmetatableindex(function(t,k)
- local v=findlib(k)
- t[k]=v
- return v
-end)
-function resolvers.findlib(required)
- return foundlibraries[required]
-end
-local libraries={}
-resolvers.libraries=libraries
-local report=logs.reporter("optional")
-if optional then optional.loaded={} end
-function libraries.validoptional(name)
- local thelib=optional and optional[name]
- if not thelib then
- elseif thelib.initialize then
- return thelib
- else
- report("invalid optional library %a",libname)
- end
-end
-function libraries.optionalloaded(name,libnames)
- local thelib=optional and optional[name]
- if not thelib then
- report("no optional %a library found",name)
- else
- local thelib_initialize=thelib.initialize
- if not thelib_initialize then
- report("invalid optional library %a",name)
- else
- if type(libnames)=="string" then
- libnames={ libnames }
- end
- if type(libnames)=="table" then
- for i=1,#libnames do
- local libname=libnames[i]
- local filename=foundlibraries[libname]
- if filename then
- libnames[i]=filename
- else
- report("unable to locate library %a",libname)
- return
- end
- end
- local initialized=thelib_initialize(unpack(libnames))
- if not initialized then
- report("unable to initialize library '% + t'",libnames)
- elseif not silent then
- report("using library '% + t'",libnames)
- end
- return initialized
- end
- end
- end
-end
-if FFISUPPORTED and ffi and ffi.load then
- local ffiload=ffi.load
- function ffi.load(name)
- local full=name and foundlibraries[name]
- if full then
- return ffiload(full)
- else
- return ffiload(name)
- end
- end
-end
-local dofile=dofile
-local savedrequire=require
-function require(name,version)
- if find(name,"%.lua$") or find(name,"%.lmt$") then
- local m=dofile(findfile(name))
- if m then
- package.loaded[name]=m
- return m
- end
- else
- return savedrequire(name)
- end
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["luat-sta"] = package.loaded["luat-sta"] or true
-
--- original size: 5703, stripped down to: 2321
-
-if not modules then modules={} end modules ['luat-sta']={
- version=1.001,
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local gmatch,match=string.gmatch,string.match
-local type=type
-states=states or {}
-local states=states
-states.data=states.data or {}
-local data=states.data
-states.hash=states.hash or {}
-local hash=states.hash
-states.tag=states.tag or ""
-states.filename=states.filename or ""
-function states.save(filename,tag)
- tag=tag or states.tag
- filename=file.addsuffix(filename or states.filename,'lus')
- io.savedata(filename,
- "-- generator : luat-sta.lua\n".."-- state tag : "..tag.."\n\n"..table.serialize(data[tag or states.tag] or {},true)
- )
-end
-function states.load(filename,tag)
- states.filename=filename
- states.tag=tag or "whatever"
- states.filename=file.addsuffix(states.filename,'lus')
- data[states.tag],hash[states.tag]=(io.exists(filename) and dofile(filename)) or {},{}
-end
-local function set_by_tag(tag,key,value,default,persistent)
- local d,h=data[tag],hash[tag]
- if d then
- if type(d)=="table" then
- local dkey,hkey=key,key
- local pre,post=match(key,"(.+)%.([^%.]+)$")
- if pre and post then
- for k in gmatch(pre,"[^%.]+") do
- local dk=d[k]
- if not dk then
- dk={}
- d[k]=dk
- elseif type(dk)=="string" then
- break
- end
- d=dk
- end
- dkey,hkey=post,key
- end
- if value==nil then
- value=default
- elseif value==false then
- elseif persistent then
- value=value or d[dkey] or default
- else
- value=value or default
- end
- d[dkey],h[hkey]=value,value
- elseif type(d)=="string" then
- data[tag],hash[tag]=value,value
- end
- end
-end
-local function get_by_tag(tag,key,default)
- local h=hash[tag]
- if h and h[key] then
- return h[key]
- else
- local d=data[tag]
- if d then
- for k in gmatch(key,"[^%.]+") do
- local dk=d[k]
- if dk~=nil then
- d=dk
- else
- return default
- end
- end
- if d==false then
- return false
- else
- return d or default
- end
- end
- end
-end
-states.set_by_tag=set_by_tag
-states.get_by_tag=get_by_tag
-function states.set(key,value,default,persistent)
- set_by_tag(states.tag,key,value,default,persistent)
-end
-function states.get(key,default)
- return get_by_tag(states.tag,key,default)
-end
-
-
-end -- of closure
-
-do -- create closure to overcome 200 locals limit
-
-package.loaded["luat-fmt"] = package.loaded["luat-fmt"] or true
-
--- original size: 11691, stripped down to: 8350
-
-if not modules then modules={} end modules ['luat-fmt']={
- version=1.001,
- comment="companion to mtxrun",
- author="Hans Hagen, PRAGMA-ADE, Hasselt NL",
- copyright="PRAGMA ADE / ConTeXt Development Team",
- license="see context related readme files"
-}
-local format=string.format
-local concat=table.concat
-local quoted=string.quoted
-local luasuffixes=utilities.lua.suffixes
-local report_format=logs.reporter("resolvers","formats")
-local function primaryflags(arguments)
- local flags={}
- if arguments.silent then
- flags[#flags+1]="--interaction=batchmode"
- end
- return concat(flags," ")
-end
-local function secondaryflags(arguments)
- local trackers=arguments.trackers
- local directives=arguments.directives
- local flags={}
- if trackers and trackers~="" then
- flags[#flags+1]="--c:trackers="..quoted(trackers)
- end
- if directives and directives~="" then
- flags[#flags+1]="--c:directives="..quoted(directives)
- end
- if arguments.silent then
- flags[#flags+1]="--c:silent"
- end
- if arguments.errors then
- flags[#flags+1]="--c:errors"
- end
- if arguments.ansi then
- flags[#flags+1]="--c:ansi"
- end
- if arguments.ansilog then
- flags[#flags+1]="--c:ansilog"
- end
- if arguments.strip then
- flags[#flags+1]="--c:strip"
- end
- if arguments.lmtx then
- flags[#flags+1]="--c:lmtx"
- end
- return concat(flags," ")
-end
-local template=[[--ini %primaryflags% --lua=%luafile% %texfile% %secondaryflags% %redirect%]]
-local checkers={
- primaryflags="verbose",
- secondaryflags="verbose",
- luafile="readable",
- texfile="readable",
- redirect="string",
- binarypath="string",
-}
-local runners={
- luametatex=sandbox.registerrunner {
- name="make luametatex format",
- program="luametatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luatex=sandbox.registerrunner {
- name="make luatex format",
- program="luatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luajittex=sandbox.registerrunner {
- name="make luajittex format",
- program="luajittex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
-}
-local stubfiles={
- luametatex="luat-cod.lmt",
- luatex="luat-cod.lua",
- luajittex="luat-cod.lua",
-}
-local suffixes={
- luametatex="mkxl",
- luatex="mkiv",
- luajittex="mkiv",
-}
-local function validbinarypath()
- if not environment.arguments.nobinarypath then
- local path=environment.ownpath or file.dirname(environment.ownname)
- if path and path~="" then
- path=dir.expandname(path)
- if path~="" and lfs.isdir(path) then
- return path
- end
- end
- end
-end
-local function fatalerror(startupdir,...)
- report_format(...)
- lfs.chdir(startupdir)
-end
-function environment.make_format(formatname)
- local arguments=environment.arguments
- local engine=environment.ownmain or "luatex"
- local silent=arguments.silent
- local errors=arguments.errors
- local runner=runners[engine]
- local startupdir=dir.current()
- if not runner then
- return fatalerror(startupdir,"the format %a cannot be generated, no runner available for engine %a",name,engine)
- end
- local luasourcename=stubfiles[engine]
- if not luasourcename then
- return fatalerror(startupdir,"no lua stub file specified for %a",engine)
- end
- local texsourcename=file.addsuffix(formatname,suffixes[engine])
- local fulltexsourcename=resolvers.findfile(texsourcename,"tex") or ""
- if fulltexsourcename=="" then
- return fatalerror(startupdir,"no tex source file with name %a (mkiv or tex)",formatname)
- end
- local fulltexsourcename=dir.expandname(fulltexsourcename)
- local texsourcepath=file.dirname(fulltexsourcename)
- if lfs.isfile(fulltexsourcename) then
- report_format("using tex source file %a",fulltexsourcename)
- else
- return fatalerror(startupdir,"no accessible tex source file with name %a",fulltexsourcename)
- end
- local fullluasourcename=dir.expandname(file.join(texsourcepath,luasourcename) or "")
- if lfs.isfile(fullluasourcename) then
- report_format("using lua stub file %a",fullluasourcename)
- else
- return fatalerror(startupdir,"no accessible lua stub file with name %a",fulltexsourcename)
- end
- local validformatpath=caches.getwritablepath("formats",engine) or ""
- if validformatpath=="" then
- return fatalerror(startupdir,"invalid format path, insufficient write access")
- end
- local binarypath=validbinarypath()
- report_format("changing to format path %a",validformatpath)
- if not lfs.chdir(validformatpath) then
- return fatalerror(startupdir,"unable to change to format path %a",validformatpath)
- end
- local primaryflags=primaryflags(arguments)
- local secondaryflags=secondaryflags(arguments)
- local specification={
- binarypath=binarypath,
- primaryflags=primaryflags,
- secondaryflags=secondaryflags,
- luafile=quoted(fullluasourcename),
- texfile=quoted(fulltexsourcename),
- }
- if silent then
- specification.redirect="> temp.log"
- end
- statistics.starttiming("format")
- local result=runner(specification)
- statistics.stoptiming("format")
- if silent then
- os.remove("temp.log")
- end
- report_format()
- if binarypath and binarypath~="" then
- report_format("binary path : %s",binarypath or "?")
- end
- report_format("format path : %s",validformatpath)
- report_format("luatex engine : %s",engine)
- report_format("lua startup file : %s",fullluasourcename)
- if primaryflags~="" then
- report_format("primary flags : %s",primaryflags)
- end
- if secondaryflags~="" then
- report_format("secondary flags : %s",secondaryflags)
- end
- report_format("context file : %s",fulltexsourcename)
- report_format("run time : %.3f seconds",statistics.elapsed("format"))
- report_format("return value : %s",result==0 and "okay" or "error")
- report_format()
- lfs.chdir(startupdir)
-end
-local template=[[%primaryflags% --fmt=%fmtfile% --lua=%luafile% %texfile% %secondaryflags%]]
-local checkers={
- primaryflags="verbose",
- secondaryflags="verbose",
- fmtfile="readable",
- luafile="readable",
- texfile="readable",
-}
-local runners={
- luatex=sandbox.registerrunner {
- name="run luatex format",
- program="luatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luametatex=sandbox.registerrunner {
- name="run luametatex format",
- program="luametatex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
- luajittex=sandbox.registerrunner {
- name="run luajittex format",
- program="luajittex",
- template=template,
- checkers=checkers,
- reporter=report_format,
- },
-}
-function environment.run_format(formatname,scriptname,filename,primaryflags,secondaryflags,verbose)
- local engine=environment.ownmain or "luatex"
- if not formatname or formatname=="" then
- report_format("missing format name")
- return
- end
- if not scriptname or scriptname=="" then
- report_format("missing script name")
- return
- end
- if not lfs.isfile(formatname) or not lfs.isfile(scriptname) then
- formatname,scriptname=resolvers.locateformat(formatname)
- end
- if not formatname or formatname=="" then
- report_format("invalid format name")
- return
- end
- if not scriptname or scriptname=="" then
- report_format("invalid script name")
- return
- end
- local runner=runners[engine]
- if not runner then
- report_format("format %a cannot be run, no runner available for engine %a",file.nameonly(name),engine)
- return
- end
- if not filename then
- filename ""
- end
- local binarypath=validbinarypath()
- local specification={
- binarypath=binarypath,
- primaryflags=primaryflags or "",
- secondaryflags=secondaryflags or "",
- fmtfile=quoted(formatname),
- luafile=quoted(scriptname),
- texfile=filename~="" and quoted(filename) or "",
- }
- statistics.starttiming("make format")
- local result=runner(specification)
- statistics.stoptiming("make format")
- if verbose then
- report_format()
- if binarypath and binarypath~="" then
- report_format("binary path : %s",binarypath)
- end
- report_format("luatex engine : %s",engine)
- report_format("lua startup file : %s",scriptname)
- report_format("tex format file : %s",formatname)
- if filename~="" then
- report_format("tex input file : %s",filename)
- end
- if primaryflags~="" then
- report_format("primary flags : %s",primaryflags)
- end
- if secondaryflags~="" then
- report_format("secondary flags : %s",secondaryflags)
- end
- report_format("run time : %0.3f seconds",statistics.elapsed("make format"))
- report_format("return value : %s",result==0 and "okay" or "error")
- report_format()
- end
- return result
-end
-
-
-end -- of closure
-
--- used libraries : l-bit32.lua l-lua.lua l-macro.lua l-sandbox.lua l-package.lua l-lpeg.lua l-function.lua l-string.lua l-table.lua l-io.lua l-number.lua l-set.lua l-os.lua l-file.lua l-gzip.lua l-md5.lua l-sha.lua l-url.lua l-dir.lua l-boolean.lua l-unicode.lua l-math.lua util-str.lua util-tab.lua util-fil.lua util-sac.lua util-sto.lua util-prs.lua util-fmt.lua util-soc-imp-reset.lua util-soc-imp-socket.lua util-soc-imp-copas.lua util-soc-imp-ltn12.lua util-soc-imp-mime.lua util-soc-imp-url.lua util-soc-imp-headers.lua util-soc-imp-tp.lua util-soc-imp-http.lua util-soc-imp-ftp.lua util-soc-imp-smtp.lua trac-set.lua trac-log.lua trac-inf.lua trac-pro.lua util-lua.lua util-deb.lua util-tpl.lua util-sbx.lua util-mrg.lua util-env.lua luat-env.lua util-zip.lua lxml-tab.lua lxml-lpt.lua lxml-mis.lua lxml-aux.lua lxml-xml.lua trac-xml.lua data-ini.lua data-exp.lua data-env.lua data-tmp.lua data-met.lua data-res.lua data-pre.lua data-inp.lua data-out.lua data-fil.lua data-con.lua data-use.lua data-zip.lua data-tre.lua data-sch.lua data-lua.lua data-aux.lua data-tmf.lua data-lst.lua libs-ini.lua luat-sta.lua luat-fmt.lua
--- skipped libraries : -
--- original bytes : 1025947
--- stripped bytes : 405652
-
--- end library merge
-
--- We need this hack till luatex is fixed.
---
--- for k,v in pairs(arg) do print(k,v) end
-
-if arg and (arg[0] == 'luatex' or arg[0] == 'luatex.exe') and arg[1] == "--luaonly" then
- arg[-1]=arg[0] arg[0]=arg[2] for k=3,#arg do arg[k-2]=arg[k] end arg[#arg]=nil arg[#arg]=nil
-end
-
--- End of hack.
-
-local format, gsub, gmatch, match, find = string.format, string.gsub, string.gmatch, string.match, string.find
-local concat = table.concat
-
-local ownname = environment and environment.ownname or arg[0] or 'mtxrun.lua'
-local ownpath = gsub(match(ownname,"^(.+)[\\/].-$") or ".","\\","/")
-local owntree = environment and environment.ownpath or ownpath
-
-local ownlibs = { -- order can be made better
-
- 'l-bit32.lua',
- 'l-lua.lua',
- 'l-macro.lua',
- 'l-sandbox.lua',
- 'l-package.lua',
- 'l-lpeg.lua',
- 'l-function.lua',
- 'l-string.lua',
- 'l-table.lua',
- 'l-io.lua',
- 'l-number.lua',
- 'l-set.lua',
- 'l-os.lua',
- 'l-file.lua',
- 'l-gzip.lua',
- 'l-md5.lua',
- 'l-sha.lua',
- 'l-url.lua',
- 'l-dir.lua',
- 'l-boolean.lua',
- 'l-unicode.lua',
- 'l-math.lua',
-
- 'util-str.lua', -- code might move to l-string
- 'util-tab.lua',
- 'util-fil.lua',
- 'util-sac.lua',
- 'util-sto.lua',
- 'util-prs.lua',
- 'util-fmt.lua',
-
- 'util-soc-imp-reset.lua',
- 'util-soc-imp-socket.lua',
- 'util-soc-imp-copas.lua',
- 'util-soc-imp-ltn12.lua',
- -- 'util-soc-imp-mbox.lua',
- 'util-soc-imp-mime.lua',
- 'util-soc-imp-url.lua',
- 'util-soc-imp-headers.lua',
- 'util-soc-imp-tp.lua',
- 'util-soc-imp-http.lua',
- 'util-soc-imp-ftp.lua',
- 'util-soc-imp-smtp.lua',
-
- 'trac-set.lua',
- 'trac-log.lua',
- 'trac-inf.lua', -- was before trac-set
- 'trac-pro.lua', -- not really needed
- 'util-lua.lua', -- indeed here?
- 'util-deb.lua',
-
- 'util-tpl.lua',
- 'util-sbx.lua',
- 'util-mrg.lua',
-
- 'util-env.lua',
- 'luat-env.lua', -- can come before inf (as in mkiv)
-
- 'util-zip.lua',
-
- 'lxml-tab.lua',
- 'lxml-lpt.lua',
- -- 'lxml-ent.lua',
- 'lxml-mis.lua',
- 'lxml-aux.lua',
- 'lxml-xml.lua',
-
- 'trac-xml.lua',
-
- 'data-ini.lua',
- 'data-exp.lua',
- 'data-env.lua',
- 'data-tmp.lua',
- 'data-met.lua',
- 'data-res.lua',
- 'data-pre.lua',
- 'data-inp.lua',
- 'data-out.lua',
- 'data-fil.lua',
- 'data-con.lua',
- 'data-use.lua',
--- 'data-tex.lua',
--- 'data-bin.lua',
- 'data-zip.lua',
- 'data-tre.lua',
- 'data-sch.lua',
- 'data-lua.lua',
- 'data-aux.lua', -- updater
- 'data-tmf.lua',
- 'data-lst.lua',
-
- 'libs-ini.lua',
-
- 'luat-sta.lua',
- 'luat-fmt.lua',
-
-}
-
--- c:/data/develop/tex-context/tex/texmf-win64/bin/../../texmf-context/tex/context/base/mkiv/data-tmf.lua
--- c:/data/develop/context/sources/data-tmf.lua
-
-local ownlist = {
- -- '.',
- -- ownpath ,
- owntree .. "/../../../../context/sources", -- HH's development path
- --
- owntree .. "/../../texmf-local/tex/context/base/mkiv",
- owntree .. "/../../texmf-context/tex/context/base/mkiv",
- owntree .. "/../../texmf/tex/context/base/mkiv",
- owntree .. "/../../../texmf-local/tex/context/base/mkiv",
- owntree .. "/../../../texmf-context/tex/context/base/mkiv",
- owntree .. "/../../../texmf/tex/context/base/mkiv",
- --
- owntree .. "/../../texmf-local/tex/context/base",
- owntree .. "/../../texmf-context/tex/context/base",
- owntree .. "/../../texmf/tex/context/base",
- owntree .. "/../../../texmf-local/tex/context/base",
- owntree .. "/../../../texmf-context/tex/context/base",
- owntree .. "/../../../texmf/tex/context/base",
-}
-
-if ownpath == "." then table.remove(ownlist,1) end
-
-own = {
- name = ownname,
- path = ownpath,
- tree = owntree,
- list = ownlist,
- libs = ownlibs,
-}
-
-local function locate_libs()
- for l=1,#ownlibs do
- local lib = ownlibs[l]
- for p =1,#ownlist do
- local pth = ownlist[p]
- local filename = pth .. "/" .. lib
- local found = lfs.isfile(filename)
- if found then
- package.path = package.path .. ";" .. pth .. "/?.lua" -- in case l-* does a require
- return pth
- end
- end
- end
-end
-
-local function load_libs()
- local found = locate_libs()
- if found then
- for l=1,#ownlibs do
- local filename = found .. "/" .. ownlibs[l]
- local codeblob = loadfile(filename)
- if codeblob then
- codeblob()
- end
- end
- else
- resolvers = nil
- end
-end
-
-if not resolvers then
- load_libs()
-end
-
-if not resolvers then
- print("")
- print("Mtxrun is unable to start up due to lack of libraries. You may")
- print("try to run 'lua mtxrun.lua --selfmerge' in the path where this")
- print("script is located (normally under ..../scripts/context/lua) which")
- print("will make this script library independent.")
- os.exit()
-end
-
--- verbosity
-
------ e_verbose = environment.arguments["verbose"]
-
-local e_verbose = false
-
--- some common flags (also passed through environment)
-
-local e_silent = environment.argument("silent")
-local e_errors = environment.argument("errors")
-local e_noconsole = environment.argument("noconsole")
-
-local e_trackers = environment.argument("trackers")
-local e_directives = environment.argument("directives")
-local e_experiments = environment.argument("experiments")
-
-local t = { }
-
-if type(e_directives) == "string" then
- t[#t+1] = e_directives
-end
-
-if type(e_silent) == "string" then
- t[#t+1] = format("logs.blocked={%s}",e_silent)
-elseif e_silent == true then
- t[#t+1] = "logs.blocked"
-end
-
-if type(e_errors) == "string" then
- t[#t+1] = format("logs.errors={%s}",e_errors)
-elseif e_errors == true then
- t[#t+1] = "logs.errors"
-end
-
-if e_noconsole then
- t[#t+1] = format("logs.target=file")
-end
-
-if #t > 0 then
- e_directives = concat(t,",")
-end
-
-if e_trackers then trackers .enable(e_trackers) end
-if e_directives then directives .enable(e_directives) end
-if e_experiments then experiments.enable(e_experiments) end
-
-if not environment.trackers then environment.trackers = e_trackers end
-if not environment.directives then environment.directives = e_directives end
-if not environment.experiments then environment.experiments = e_experiments end
-
---
-
-resolvers.reset()
-
-local helpinfo = [[
-<?xml version="1.0" ?>
-<application>
- <metadata>
- <entry name="name">mtxrun</entry>
- <entry name="detail">ConTeXt TDS Runner Tool</entry>
- <entry name="version">1.33</entry>
- </metadata>
- <flags>
- <category name="basic">
- <subcategory>
- <flag name="script"><short>run an mtx script (lua prefered method) (<ref name="noquotes"/>), no script gives list</short></flag>
- <flag name="evaluate"><short>run code passed on the commandline (between quotes) (=loop) (exit|quit aborts)</short></flag>
- <flag name="execute"><short>run a script or program (texmfstart method) (<ref name="noquotes"/>)</short></flag>
- <flag name="resolve"><short>resolve prefixed arguments</short></flag>
- <flag name="ctxlua"><short>run internally (using preloaded libs)</short></flag>
- <flag name="internal"><short>run script using built in libraries (same as <ref name="ctxlua"/>)</short></flag>
- <flag name="locate"><short>locate given filename in database (default) or system (<ref name="first"/> <ref name="all"/> <ref name="detail"/>)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="tree" value="pathtotree"><short>use given texmf tree (default file: setuptex.tmf)</short></flag>
- <flag name="path" value="runpath"><short>go to given path before execution</short></flag>
- <flag name="ifchanged" value="filename"><short>only execute when given file has changed (md checksum)</short></flag>
- <flag name="iftouched" value="old,new"><short>only execute when given file has changed (time stamp)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="makestubs"><short>create stubs for (context related) scripts</short></flag>
- <flag name="removestubs"><short>remove stubs (context related) scripts</short></flag>
- <flag name="stubpath" value="binpath"><short>paths where stubs wil be written</short></flag>
- <flag name="windows"><short>create windows (mswin) stubs</short></flag>
- <flag name="unix"><short>create unix (linux) stubs</short></flag>
- <flag name="addbinarypath"><short>prepend the (found) binarypath to runners</short></flag>
- </subcategory>
- <subcategory>
- <flag name="verbose"><short>give a bit more info</short></flag>
- <flag name="trackers" value="list"><short>enable given trackers</short></flag>
- <flag name="progname" value="str"><short>format or backend</short></flag>
- <flag name="systeminfo" value="str"><short>show current operating system, processor, etc</short></flag>
- </subcategory>
- <subcategory>
- <flag name="edit"><short>launch editor with found file</short></flag>
- <flag name="launch"><short>launch files like manuals, assumes os support (<ref name="all"/>,<ref name="list"/>)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="timedrun"><short>run a script and time its run</short></flag>
- <flag name="autogenerate"><short>regenerate databases if needed (handy when used to run context in an editor)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="usekpse"><short>use kpse as fallback (when no mkiv and cache installed, often slower)</short></flag>
- <flag name="forcekpse"><short>force using kpse (handy when no mkiv and cache installed but less functionality)</short></flag>
- </subcategory>
- <subcategory>
- <flag name="prefixes"><short>show supported prefixes</short></flag>
- </subcategory>
- <subcategory>
- <flag name="generate"><short>generate file database</short></flag>
- </subcategory>
- <subcategory>
- <flag name="variables"><short>show configuration variables</short></flag>
- <flag name="configurations"><short>show configuration order</short></flag>
- </subcategory>
- <subcategory>
- <flag name="directives"><short>show (known) directives</short></flag>
- <flag name="trackers"><short>show (known) trackers</short></flag>
- <flag name="experiments"><short>show (known) experiments</short></flag>
- </subcategory>
- <subcategory>
- <flag name="expand-braces"><short>expand complex variable</short></flag>
- <flag name="resolve-path"><short>expand variable (completely resolve paths)</short></flag>
- <flag name="expand-path"><short>expand variable (resolve paths)</short></flag>
- <flag name="expand-var"><short>expand variable (resolve references)</short></flag>
- <flag name="show-path"><short>show path expansion of ...</short></flag>
- <flag name="var-value"><short>report value of variable</short></flag>
- <flag name="find-file"><short>report file location</short></flag>
- <flag name="find-path"><short>report path of file</short></flag>
- </subcategory>
- <subcategory>
- <flag name="pattern" value="string"><short>filter variables</short></flag>
- </subcategory>
- </category>
- </flags>
-</application>
-]]
-
-local application = logs.application {
- name = "mtxrun",
- banner = "ConTeXt TDS Runner Tool 1.32",
- helpinfo = helpinfo,
-}
-
-local report = application.report
-
-messages = messages or { } -- for the moment
-
-runners = runners or { } -- global (might become local)
-
-runners.applications = {
- ["lua"] = "luatex --luaonly",
- ["luc"] = "luatex --luaonly",
- ["pl"] = "perl",
- ["py"] = "python",
- ["rb"] = "ruby",
-}
-
-runners.suffixes = {
- 'rb', 'lua', 'py', 'pl'
-}
-
-runners.registered = {
- texexec = { 'texexec.rb', false }, -- context mkii runner (only tool not to be luafied)
- texutil = { 'texutil.rb', true }, -- old perl based index sorter for mkii (old versions need it)
- texfont = { 'texfont.pl', true }, -- perl script that makes mkii font metric files
- texfind = { 'texfind.pl', false }, -- perltk based tex searching tool, mostly used at pragma
- texshow = { 'texshow.pl', false }, -- perltk based context help system, will be luafied
- -- texwork = { 'texwork.pl', false }, -- perltk based editing environment, only used at pragma
- makempy = { 'makempy.pl', true },
- mptopdf = { 'mptopdf.pl', true },
- pstopdf = { 'pstopdf.rb', true }, -- converts ps (and some more) images, does some cleaning (replaced)
- -- examplex = { 'examplex.rb', false },
- concheck = { 'concheck.rb', false },
- runtools = { 'runtools.rb', true },
- textools = { 'textools.rb', true },
- tmftools = { 'tmftools.rb', true },
- ctxtools = { 'ctxtools.rb', true },
- rlxtools = { 'rlxtools.rb', true },
- pdftools = { 'pdftools.rb', true },
- mpstools = { 'mpstools.rb', true },
- -- exatools = { 'exatools.rb', true },
- xmltools = { 'xmltools.rb', true },
- -- luatools = { 'luatools.lua', true },
- mtxtools = { 'mtxtools.rb', true },
- pdftrimwhite = { 'pdftrimwhite.pl', false },
-}
-
-runners.launchers = {
- windows = { },
- unix = { },
-}
-
--- like runners.libpath("framework"): looks on script's subpath
-
-function runners.libpath(...)
- package.prepend_libpath(file.dirname(environment.ownscript),...)
- package.prepend_libpath(file.dirname(environment.ownname) ,...)
-end
-
-function runners.prepare()
- local checkname = environment.argument("ifchanged")
- if type(checkname) == "string" and checkname ~= "" then
- local oldchecksum = file.loadchecksum(checkname)
- local newchecksum = file.checksum(checkname)
- if oldchecksum == newchecksum then
- if e_verbose then
- report("file '%s' is unchanged",checkname)
- end
- return "skip"
- elseif e_verbose then
- report("file '%s' is changed, processing started",checkname)
- end
- file.savechecksum(checkname)
- end
- local touchname = environment.argument("iftouched")
- if type(touchname) == "string" and touchname ~= "" then
- local oldname, newname = string.splitup(touchname, ",")
- if oldname and newname and oldname ~= "" and newname ~= "" then
- if not file.needs_updating(oldname,newname) then
- if e_verbose then
- report("file '%s' and '%s' have same age",oldname,newname)
- end
- return "skip"
- elseif e_verbose then
- report("file '%s' is older than '%s'",oldname,newname)
- end
- end
- end
- local runpath = environment.argument("path")
- if type(runpath) == "string" and not lfs.chdir(runpath) then
- report("unable to change to path '%s'",runpath)
- return "error"
- end
- runners.prepare = function() end
- return "run"
-end
-
-function runners.execute_script(fullname,internal,nosplit)
- local noquote = environment.argument("noquotes")
- if fullname and fullname ~= "" then
- local state = runners.prepare()
- if state == 'error' then
- return false
- elseif state == 'skip' then
- return true
- elseif state == "run" then
- local path, name, suffix = file.splitname(fullname)
- local result = ""
- if path ~= "" then
- result = fullname
- elseif name then
- name = gsub(name,"^int[%a]*:",function()
- internal = true
- return ""
- end )
- name = gsub(name,"^script:","")
- if suffix == "" and runners.registered[name] and runners.registered[name][1] then
- name = runners.registered[name][1]
- suffix = file.suffix(name)
- end
- if suffix == "" then
- -- loop over known suffixes
- for _,s in pairs(runners.suffixes) do
- result = resolvers.findfile(name .. "." .. s, 'texmfscripts')
- if result ~= "" then
- break
- end
- end
- elseif runners.applications[suffix] then
- result = resolvers.findfile(name, 'texmfscripts')
- else
- -- maybe look on path
- result = resolvers.findfile(name, 'other text files')
- end
- end
- if result and result ~= "" then
- if not no_split then
- local before, after = environment.splitarguments(fullname) -- already done
- environment.arguments_before, environment.arguments_after = before, after
- end
- if internal then
- arg = { } for _,v in pairs(environment.arguments_after) do arg[#arg+1] = v end
- environment.ownscript = result
- dofile(result)
- else
-local texmfcnf = resolvers.getenv("TEXMFCNF")
-if not texmfcnf or texmfcnf == "" then
- texmfcnf = resolvers.expandedpathfromlist(resolvers.splitpath(resolvers.resolve(resolvers.luacnfspec)))
- resolvers.setenv("TEXMFCNF",table.concat(texmfcnf,";")) -- for running texexec etc (after tl change to texmf-dist)
-end
- local binary = runners.applications[file.suffix(result)]
- result = string.quoted(string.unquoted(result))
- -- if string.match(result,' ') and not string.match(result,"^\".*\"$") then
- -- result = '"' .. result .. '"'
- -- end
- if binary and binary ~= "" then
- result = binary .. " " .. result
- end
- local command = result .. " " .. environment.reconstructcommandline(environment.arguments_after,noquote)
- if e_verbose then
- report()
- report("executing: %s",command)
- report()
- report()
- io.flush()
- end
- local code = os.execute(command)
- if code == 0 then
- return true
- else
- if binary then
- binary = file.addsuffix(binary,os.binsuffix)
- for p in gmatch(os.getenv("PATH"),"[^"..io.pathseparator.."]+") do
- if lfs.isfile(file.join(p,binary)) then
- return false
- end
- end
- report()
- report("This script needs '%s' which seems not to be installed.",binary)
- report()
- end
- return false
- end
- end
- end
- end
- end
- return false
-end
-
-function runners.execute_program(fullname)
- local noquote = environment.argument("noquotes")
- if fullname and fullname ~= "" then
- local state = runners.prepare()
- if state == 'error' then
- return false
- elseif state == 'skip' then
- return true
- elseif state == "run" then
- local before, after = environment.splitarguments(fullname)
- for k=1,#after do after[k] = resolvers.resolve(after[k]) end
- environment.initializearguments(after)
- fullname = gsub(fullname,"^bin:","")
- local command = fullname .. " " .. (environment.reconstructcommandline(after or "",noquote) or "")
- report()
- report("executing: %s",command)
- report()
- report()
- io.flush()
- local code = os.execute(command)
- return code == 0
- end
- end
- return false
-end
-
--- the --usekpse flag will fallback (not default) on kpse (hm, we can better update mtx-stubs)
-
-local windows_stub = '@echo off\013\010setlocal\013\010set ownpath=%%~dp0%%\013\010texlua "%%ownpath%%mtxrun.lua" --usekpse --execute %s %%*\013\010endlocal\013\010'
-local unix_stub = '#!/bin/sh\010mtxrun --usekpse --execute %s \"$@\"\010'
-
-function runners.handle_stubs(create)
- local stubpath = environment.argument('stubpath') or '.' -- 'auto' no longer subpathssupported
- local windows = environment.argument('windows') or environment.argument('mswin') or false
- local unix = environment.argument('unix') or environment.argument('linux') or false
- if not windows and not unix then
- if os.platform == "unix" then
- unix = true
- else
- windows = true
- end
- end
- for _,v in pairs(runners.registered) do
- local name, doit = v[1], v[2]
- if doit then
- local base = gsub(file.basename(name), "%.(.-)$", "")
- if create then
- if windows then
- io.savedata(file.join(stubpath,base..".bat"),format(windows_stub,name))
- report("windows stub for '%s' created",base)
- end
- if unix then
- io.savedata(file.join(stubpath,base),format(unix_stub,name))
- report("unix stub for '%s' created",base)
- end
- else
- if windows and (os.remove(file.join(stubpath,base..'.bat')) or os.remove(file.join(stubpath,base..'.cmd'))) then
- report("windows stub for '%s' removed", base)
- end
- if unix and (os.remove(file.join(stubpath,base)) or os.remove(file.join(stubpath,base..'.sh'))) then
- report("unix stub for '%s' removed",base)
- end
- end
- end
- end
-end
-
-function runners.resolve_string(filename)
- if filename and filename ~= "" then
- runners.report_location(resolvers.resolve(filename))
- end
-end
-
--- differs from texmfstart where locate appends .com .exe .bat ... todo
-
-function runners.locate_file(filename) -- was given file but only searches in tree
- if filename and filename ~= "" then
- if environment.argument("first") then
- runners.report_location(resolvers.findfile(filename))
- -- resolvers.dowithfilesandreport(resolvers.findfile,filename)
- elseif environment.argument("all") then
- local result, status = resolvers.findfiles(filename)
- if status and environment.argument("detail") then
- runners.report_location(status)
- else
- runners.report_location(result)
- end
- else
- runners.report_location(resolvers.findgivenfile(filename))
- -- resolvers.dowithfilesandreport(resolvers.findgivenfile,filename)
- end
- end
-end
-
-function runners.locate_platform()
- runners.report_location(os.platform)
-end
-
-function runners.report_location(result)
- if type(result) == "table" then
- for i=1,#result do
- if i > 1 then
- io.write("\n")
- end
- io.write(result[i])
- end
- else
- io.write(result)
- end
-end
-
-function runners.edit_script(filename) -- we assume that gvim is present on most systems (todo: also in cnf file)
- local editor = os.getenv("MTXRUN_EDITOR") or os.getenv("TEXMFSTART_EDITOR") or os.getenv("EDITOR") or 'gvim'
- local rest = resolvers.resolve(filename)
- if rest ~= "" then
- local command = editor .. " " .. rest
- if e_verbose then
- report()
- report("starting editor: %s",command)
- report()
- report()
- end
- os.launch(command)
- end
-end
-
-function runners.save_script_session(filename, list)
- if type(list) == "table" then
- local t = { }
- for i=1,#list do
- local key = list[i]
- t[key] = environment.arguments[key]
- end
- io.savedata(filename,table.serialize(t,true))
- end
-end
-
-function runners.load_script_session(filename)
- if lfs.isfile(filename) then
- local t = io.loaddata(filename)
- if t then
- t = loadstring(t)
- if t then t = t() end
- for key, value in pairs(t) do
- environment.arguments[key] = value
- end
- end
- end
-end
-
-function resolvers.launch(str)
- -- maybe we also need to test on mtxrun.launcher.suffix environment
- -- variable or on windows consult the assoc and ftype vars and such
- local launchers = runners.launchers[os.platform] if launchers then
- local suffix = file.suffix(str) if suffix then
- local runner = launchers[suffix] if runner then
- str = runner .. " " .. str
- end
- end
- end
- os.launch(str)
-end
-
-function runners.launch_file(filename)
- local allresults = environment.arguments["all"]
- local pattern = environment.arguments["pattern"]
- local listonly = environment.arguments["list"]
- if not pattern or pattern == "" then
- pattern = filename
- end
- if not pattern or pattern == "" then
- report("provide name or --pattern=")
- else
- local t = resolvers.findfiles(pattern,nil,allresults)
- if not t or #t == 0 then
- t = resolvers.findfiles("*/" .. pattern,nil,allresults)
- end
- if not t or #t == 0 then
- t = resolvers.findfiles("*/" .. pattern .. "*",nil,allresults)
- end
- if t and #t > 0 then
- for i=1,#t do
- local name = t[i]
- if listonly then
- report("% 3i: %-30s %s",i,file.basename(name),file.dirname(name))
- else
- report("launching: %s",name)
- resolvers.launch(name)
- if not allresults then
- break
- end
- end
- end
- if listonly then
- io.write("\n")
- io.write("\n[select number]\n\n>> ")
- local answer = tonumber(io.read())
- if answer then
- io.write("\n")
- local name = t[answer]
- if name then
- report("launching: %s",name)
- resolvers.launch(name)
- else
- report("invalid number")
- end
- end
- end
- else
- report("no match for %s", pattern)
- end
- end
-end
-
-local mtxprefixes = {
- { "^mtx%-", "mtx-" },
- { "^mtx%-t%-", "mtx-t-" },
-}
-
-function runners.find_mtx_script(filename)
- local function found(name)
- local path = file.dirname(name)
- if path and path ~= "" then
- return false
- else
- local fullname = own and own.path and file.join(own.path,name)
- return io.exists(fullname) and fullname
- end
- end
- filename = file.addsuffix(filename,"lua")
- local basename = file.removesuffix(file.basename(filename))
- local suffix = file.suffix(filename)
- -- qualified path, raw name
- local fullname = file.is_qualified_path(filename) and io.exists(filename) and filename
- if fullname and fullname ~= "" then
- return fullname
- end
- -- current path, raw name
- fullname = "./" .. filename
- fullname = io.exists(fullname) and fullname
- if fullname and fullname ~= "" then
- return fullname
- end
- -- mtx- prefix checking
- for i=1,#mtxprefixes do
- local mtxprefix = mtxprefixes[i]
- mtxprefix = find(filename,mtxprefix[1]) and "" or mtxprefix[2]
- -- context namespace, mtx-<filename>
- fullname = mtxprefix .. filename
- fullname = found(fullname) or resolvers.findfile(fullname)
- if fullname and fullname ~= "" then
- return fullname
- end
- -- context namespace, mtx-<filename>s
- fullname = mtxprefix .. basename .. "s" .. "." .. suffix
- fullname = found(fullname) or resolvers.findfile(fullname)
- if fullname and fullname ~= "" then
- return fullname
- end
- -- context namespace, mtx-<filename minus trailing s>
- fullname = mtxprefix .. gsub(basename,"s$","") .. "." .. suffix
- fullname = found(fullname) or resolvers.findfile(fullname)
- if fullname and fullname ~= "" then
- return fullname
- end
- end
- -- context namespace, just <filename>
- fullname = resolvers.findfile(filename)
- return fullname
-end
-
-function runners.register_arguments(...)
- local arguments = environment.arguments_after
- local passedon = { ... }
- for i=#passedon,1,-1 do
- local pi = passedon[i]
- if pi then
- table.insert(arguments,1,pi)
- end
- end
-end
-
-function runners.execute_ctx_script(filename,...)
- runners.register_arguments(...)
- local arguments = environment.arguments_after
- local fullname = runners.find_mtx_script(filename) or ""
- if file.suffix(fullname) == "cld" then
- -- handy in editors where we force --autopdf
- report("running cld script: %s",filename)
- table.insert(arguments,1,fullname)
- table.insert(arguments,"--autopdf")
- fullname = runners.find_mtx_script("context") or ""
- end
- -- retry after generate but only if --autogenerate
- if fullname == "" and environment.argument("autogenerate") then -- might become the default
- resolvers.renewcache()
- trackers.enable("resolvers.locating")
- resolvers.load()
- --
- fullname = runners.find_mtx_script(filename) or ""
- end
- -- that should do it
- if fullname ~= "" then
- local state = runners.prepare()
- if state == 'error' then
- return false
- elseif state == 'skip' then
- return true
- elseif state == "run" then
- -- load and save ... kind of undocumented
- arg = { } for _,v in pairs(arguments) do arg[#arg+1] = resolvers.resolve(v) end
- environment.initializearguments(arg)
- local loadname = environment.arguments['load']
- if loadname then
- if type(loadname) ~= "string" then loadname = file.basename(fullname) end
- loadname = file.replacesuffix(loadname,"cfg")
- runners.load_script_session(loadname)
- end
- filename = environment.files[1]
- if e_verbose then
- report("using script: %s (if --path is used don't run on path where mtxrun lives)\n",fullname)
- end
- environment.ownscript = fullname
- dofile(fullname)
- local savename = environment.arguments['save']
- if savename then
- if type(savename) ~= "string" then savename = file.basename(fullname) end
- savename = file.replacesuffix(savename,"cfg")
- runners.save_script_session(savename,save_list)
- end
- return true
- end
- else
- if filename == "" or filename == "help" then
- local context = resolvers.findfile("mtx-context.lua")
- trackers.enable("resolvers.locating")
- if context ~= "" then
- local result = dir.glob((gsub(context,"mtx%-context","mtx-*"))) -- () needed
- local valid = { }
- table.sort(result)
- for i=1,#result do
- local scriptname = result[i]
- local scriptbase = match(scriptname,".*mtx%-([^%-]-)%.lua")
- if scriptbase then
- local data = io.loaddata(scriptname)
- local application = match(data,"local application.-=.-(%{.-%})")
- if application then
- application = loadstring("return " .. application)
- if application then
- application = application()
- local banner = application.banner
- if banner then
- local description, version = match(banner,"^(.-) ([%d.]+)$")
- if description then
- valid[#valid+1] = { scriptbase, version, description }
- else
- valid[#valid+1] = { scriptbase, "", banner }
- end
- end
- end
- end
- end
- end
- if #valid > 0 then
- application.identify()
- report("no script name given, known scripts:")
- report()
- for k=1,#valid do
- local v = valid[k]
- report("%-12s %4s %s",v[1],v[2],v[3])
- end
- end
- else
- report("no script name given")
- end
- else
- filename = file.addsuffix(filename,"lua")
- if file.is_qualified_path(filename) then
- report("unknown script '%s'",filename)
- else
- report("unknown script '%s' or 'mtx-%s'",filename,filename)
- end
- end
- return false
- end
-end
-
-function runners.prefixes()
- application.identify()
- report()
- report(concat(resolvers.allprefixes(true)," "))
-end
-
-function runners.timedrun(filename) -- just for me
- if filename and filename ~= "" then
- runners.timed(function() os.execute(filename) end)
- end
-end
-
-function runners.timed(action)
- statistics.timed(action,true)
-end
-
-function runners.associate(filename)
- os.launch(filename)
-end
-
-function runners.evaluate(code,filename) -- for Luigi
- local environment = table.setmetatableindex(_G)
- if code == "loop" then
- while true do
- io.write("lua > ")
- local code = io.read()
- if code == "quit" or code == "exit" then
- break
- elseif code ~= "" then
- local temp = string.match(code,"^= (.*)$")
- if temp then
- code = "inspect("..temp..")"
- end
- local compiled, message = load(code,"console","t",environment)
- if type(compiled) ~= "function" then
- compiled = load("inspect("..code..")","console","t",environment)
- end
- if type(compiled) ~= "function" then
- io.write("! " .. (message or code).."\n")
- else
- io.write(compiled())
- end
- end
- end
- else
- if type(code) ~= "string" or code == "" then
- code = filename
- end
- if code ~= "" then
- local compiled, message = load(code,"console","t",environment)
- if type(compiled) ~= "function" then
- compiled = load("inspect("..code..")","console","t",environment)
- end
- if type(compiled) ~= "function" then
- io.write("invalid lua code: " .. (message or code))
- return
- end
- io.write(compiled())
- end
- end
-end
-
-function runners.gethelp(filename)
- local url = environment.argument("url")
- if url and url ~= "" then
- local command = string.gsub(environment.argument("command") or "unknown","^%s*\\*(.-)%s*$","%1")
- url = utilities.templates.replace(url,{ command = command })
- os.launch(url)
- else
- report("no --url given")
- end
-end
-
-function runners.systeminfo()
- report("architecture : %s",os.platform or "<unset>")
- report("operating system : %s",os.name or "<unset>")
- report("file architecture : %s",os.type or "<unset>")
- report("binary path : %s",os.selfdir or "<unset>")
- report("binary suffix : %s",os.binsuffix or "<unset>")
- report("library suffix : %s",os.libsuffix or "<unset>")
-end
-
--- this is a bit dirty ... first we store the first filename and next we
--- split the arguments so that we only see the ones meant for this script
--- ... later we will use the second half
-
-local filename = environment.files[1] or ""
-local ok = true
-
-local before, after = environment.splitarguments(filename)
-environment.arguments_before, environment.arguments_after = before, after
-environment.initializearguments(before)
-
-e_verbose = environment.arguments["verbose"] -- delayed till here (we need the ones before script)
-
-if e_verbose then
- trackers.enable("resolvers.locating")
-end
-
--- maybe the unset has to go to this level
-
-local is_mkii_stub = runners.registered[file.removesuffix(file.basename(filename))]
-
-local e_argument = environment.argument
-
-if e_argument("timedlog") then
- logs.settimedlog()
-end
-
-if e_argument("usekpse") or e_argument("forcekpse") or is_mkii_stub then
-
- resolvers.load_tree(e_argument('tree'),true) -- force resolve of TEXMFCNF
-
- os.setenv("engine","")
- os.setenv("progname","")
-
- local remapper = {
- otf = "opentype fonts",
- ttf = "truetype fonts",
- ttc = "truetype fonts",
- pfb = "type1 fonts",
- other = "other text files",
- }
-
- local progname = e_argument("progname") or 'context'
-
- local function kpse_initialized()
- texconfig.kpse_init = true
- local t = os.clock()
- local k = kpse.original.new("luatex",progname)
- local dummy = k:find_file("mtxrun.lua") -- so that we're initialized
- report("kpse fallback with progname '%s' initialized in %s seconds",progname,os.clock()-t)
- kpse_initialized = function() return k end
- return k
- end
-
- local findfile = resolvers.findfile
- local showpath = resolvers.showpath
-
- if e_argument("forcekpse") then
-
- function resolvers.findfile(name,kind)
- return (kpse_initialized():find_file(resolvers.cleanpath(name),(kind ~= "" and (remapper[kind] or kind)) or "tex") or "") or ""
- end
- function resolvers.showpath(name)
- return (kpse_initialized():show_path(name)) or ""
- end
-
- elseif e_argument("usekpse") or is_mkii_stub then
-
- resolvers.load()
-
- function resolvers.findfile(name,kind)
- local found = findfile(name,kind) or ""
- if found ~= "" then
- return found
- else
- return (kpse_initialized():find_file(resolvers.cleanpath(name),(kind ~= "" and (remapper[kind] or kind)) or "tex") or "") or ""
- end
- end
- function resolvers.showpath(name)
- local found = showpath(name) or ""
- if found ~= "" then
- return found
- else
- return (kpse_initialized():show_path(name)) or ""
- end
- end
-
- end
-
- function runners.loadbase()
- end
-
-else
-
- function runners.loadbase(...)
- if not resolvers.load(...) then
- report("forcing cache reload")
- resolvers.renewcache()
- trackers.enable("resolvers.locating")
- if not resolvers.load(...) then
- report("the resolver databases are not present or outdated")
- end
- end
- end
-
- resolvers.load_tree(e_argument('tree'),e_argument("resolve"))
-
-end
-
--- joke .. reminds me of messing with gigi terminals
-
-do
-
- local a_locale = e_argument("locale")
-
- if a_locale then
-
- -- I really hate this crap but am too tired of discussing it over and over
- -- again so for the sake of usiage outside context we will provide ways to
- -- use locales in an otherwise supposed to be locale agnostic system. And
- -- forget about support in case of interferences.
-
- report()
- report(what == "force" and "forcing locale:" or "original locale:")
- report()
- report(" collate : %s",status.lc_collate or "<unset>")
- report(" ctype : %s",status.lc_ctype or "<unset>")
- report(" monetary : %s",status.lc_monetary or "<unset>")
- report(" numeric : %s",status.lc_numeric or "<unset>")
- report(" time : %s",status.lc_time or "<unset>")
- report()
-
- end
-
- if a_locale == "force" then
- os.setlocale(status.lc_collate ,"collate")
- os.setlocale(status.lc_ctype ,"ctype")
- os.setlocale(status.lc_monetary,"monetary")
- os.setlocale(status.lc_numeric ,"numeric")
- os.setlocale(status.lc_time ,"time")
- else
- function os.setlocale()
- end
- end
-
-end
-
--- if e_argument("ansi") or e_argument("ansilog") then
-
--- logs.setformatters(e_argument("ansi") and "ansi" or "ansilog")
-
--- -- local script = e_argument("script") or e_argument("scripts")
--- --
--- -- if type(script) == "string" then
--- -- logs.writer("]0;"..script.."") -- for Alan to test
--- -- end
-
--- end
-
-if e_argument("script") or e_argument("scripts") then
-
- -- run a script by loading it (using libs), pass args
-
- if e_argument("nofiledatabase") then
- -- handy for mtx-update
- else
- runners.loadbase()
- end
- if is_mkii_stub then
- ok = runners.execute_script(filename,false,true)
- else
- ok = runners.execute_ctx_script(filename)
- end
-
-elseif e_argument("evaluate") then
-
- runners.evaluate(e_argument("evaluate"),filename)
-
-elseif e_argument("selfmerge") then
-
- -- embed used libraries
-
- runners.loadbase()
- local found = locate_libs()
-
- if found then
- local mtxrun = resolvers.findfile("mtxrun.lua") -- includes local name
- if lfs.isfile(mtxrun) then
- utilities.merger.selfmerge(mtxrun,own.libs,{ found })
- application.report("runner updated on resolved path: %s",mtxrun)
- else
- utilities.merger.selfmerge(own.name,own.libs,{ found })
- application.report("runner updated on relative path: %s",own.name)
- end
- end
-
-elseif e_argument("selfclean") then
-
- -- remove embedded libraries
-
- runners.loadbase()
-
- local mtxrun = resolvers.findfile("mtxrun.lua") -- includes local name
- if lfs.isfile(mtxrun) then
- utilities.merger.selfclean(mtxrun)
- application.report("runner cleaned on resolved path: %s",mtxrun)
- else
- utilities.merger.selfclean(own.name)
- application.report("runner cleaned on relative path: %s",own.name)
- end
-
-elseif e_argument("selfupdate") then
-
- runners.loadbase()
- trackers.enable("resolvers.locating")
- resolvers.updatescript(own.name,"mtxrun")
-
-elseif e_argument("ctxlua") or e_argument("internal") then
-
- -- run a script by loading it (using libs)
-
- runners.loadbase()
- ok = runners.execute_script(filename,true)
-
-elseif e_argument("execute") then
-
- -- execute script
-
- runners.loadbase()
- ok = runners.execute_script(filename)
-
-elseif e_argument("direct") then
-
- -- equals bin:
-
- runners.loadbase()
- ok = runners.execute_program(filename)
-
-elseif e_argument("edit") then
-
- -- edit file
-
- runners.loadbase()
- runners.edit_script(filename)
-
-elseif e_argument("launch") then
-
- runners.loadbase()
- runners.launch_file(filename)
-
-elseif e_argument("associate") then
-
- runners.associate(filename)
-
-elseif e_argument("gethelp") then
-
- runners.gethelp()
-
-elseif e_argument("makestubs") then
-
- -- make stubs (depricated)
-
- runners.handle_stubs(true)
-
-elseif e_argument("removestubs") then
-
- -- remove stub (depricated)
-
- runners.loadbase()
- runners.handle_stubs(false)
-
-elseif e_argument("resolve") then
-
- -- resolve string
-
- runners.loadbase()
- runners.resolve_string(filename)
-
-elseif e_argument("locate") then
-
- -- locate file (only database)
-
- runners.loadbase()
- runners.locate_file(filename)
-
-elseif e_argument("platform") or e_argument("show-platform") then
-
- -- locate platform
-
- runners.loadbase()
- runners.locate_platform()
-
-elseif e_argument("prefixes") then
-
- runners.loadbase()
- runners.prefixes()
-
-elseif e_argument("timedrun") then
-
- -- locate platform
-
- runners.loadbase()
- runners.timedrun(filename)
-
-elseif e_argument("variables") or e_argument("show-variables") or e_argument("expansions") or e_argument("show-expansions") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expansions",filename)
-
- resolvers.load("nofiles")
- resolvers.listers.variables(e_argument("pattern"))
-
-elseif e_argument("configurations") or e_argument("show-configurations") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--configurations",filename)
-
- resolvers.load("nofiles")
- resolvers.listers.configurations()
-
-elseif e_argument("find-file") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--find-file",filename)
-
- resolvers.load()
- local e_all = e_argument("all")
- local e_pattern = e_argument("pattern")
- local e_format = e_argument("format")
- local finder = e_all and resolvers.findfiles or resolvers.findfile
- if not e_pattern then
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(finder,environment.files,e_format)
- elseif type(e_pattern) == "string" then
- resolvers.dowithfilesandreport(finder,{ e_pattern },e_format)
- end
-
-elseif e_argument("find-path") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--find-path",filename)
-
- resolvers.load()
- local path = resolvers.findpath(filename)
- if e_verbose then
- report(path)
- else
- print(path)
- end
-
-elseif e_argument("expand-braces") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expand-braces",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.expandbraces, environment.files)
-
-elseif e_argument("expand-path") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expand-path",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.expandpath, environment.files)
-
-elseif e_argument("resolve-path") then
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.cleanedpathlist, environment.files)
-
-elseif e_argument("expand-var") or e_argument("expand-variable") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--expand-var",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.expansion, environment.files)
-
-elseif e_argument("show-path") or e_argument("path-value") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--show-path",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.showpath, environment.files)
-
-elseif e_argument("var-value") or e_argument("show-value") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--show-value",filename)
-
- resolvers.load("nofiles")
- runners.register_arguments(filename)
- environment.initializearguments(environment.arguments_after)
- resolvers.dowithfilesandreport(resolvers.variable,environment.files)
-
-elseif e_argument("format-path") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--format-path",filename)
-
- resolvers.load()
- report(caches.getwritablepath("format"))
-
--- elseif e_argument("pattern") then
---
--- -- luatools
---
--- runners.execute_ctx_script("mtx-base","--pattern='" .. e_argument("pattern") .. "'",filename)
-
-elseif e_argument("generate") then
-
- -- luatools
-
- if filename and filename ~= "" then
- resolvers.load("nofiles")
- trackers.enable("resolvers.locating")
- resolvers.renew(filename)
- else
- resolvers.renewcache()
- trackers.enable("resolvers.locating")
- resolvers.load()
- end
-
- e_verbose = true
-
-elseif e_argument("make") or e_argument("ini") or e_argument("compile") then
-
- -- luatools: runners.execute_ctx_script("mtx-base","--make",filename)
-
- resolvers.load()
- trackers.enable("resolvers.locating")
- environment.make_format(filename)
-
-elseif e_argument("run") then
-
- -- luatools
-
- runners.execute_ctx_script("mtx-base","--run",filename)
-
-elseif e_argument("fmt") then
-
- -- luatools
-
- runners.execute_ctx_script("mtx-base","--fmt",filename)
-
-elseif e_argument("help") and filename=='base' then
-
- -- luatools
-
- runners.execute_ctx_script("mtx-base","--help")
-
-elseif e_argument("version") then
-
- application.version()
-
- application.report("source path",environment.ownbin)
-
-elseif e_argument("directives") then
-
- directives.show()
-
-elseif e_argument("trackers") then
-
- trackers.show()
-
-elseif e_argument("experiments") then
-
- experiments.show()
-
-elseif e_argument("exporthelp") then
-
- runners.loadbase()
- application.export(e_argument("exporthelp"),filename)
-
-elseif e_argument("systeminfo") then
-
- runners.systeminfo()
-
-elseif e_argument("locale") then
-
- -- already done
-
-elseif e_argument("help") or filename=='help' or filename == "" then
-
- application.help()
-
-elseif find(filename,"^bin:") then
-
- runners.loadbase()
- ok = runners.execute_program(filename)
-
-elseif is_mkii_stub then
-
- -- execute mkii script
-
- runners.loadbase()
- ok = runners.execute_script(filename,false,true)
-
-elseif false then
-
- runners.loadbase()
- ok = runners.execute_ctx_script(filename)
- if not ok then
- ok = runners.execute_script(filename)
- end
-
-elseif environment.files[1] == 'texmfcnf.lua' then -- so that we don't need to load mtx-base
-
- resolvers.load("nofiles")
- resolvers.listers.configurations()
-
-else
- runners.loadbase()
- runners.execute_ctx_script("mtx-base",filename)
-
-end
-
-if e_verbose then
- report()
- report("elapsed lua time: %0.3f seconds",os.runtime())
-end
-
-if os.type ~= "windows" then
- texio.write("\n") -- is this still valid?
-end
-
-if ok == false then ok = 1 elseif ok == true or ok == nil then ok = 0 end
-
--- os.exit(ok,true) -- true forces a cleanup in 5.2+
-
-os.exit(ok) -- true forces a cleanup in 5.2+ but reports a wrong number then
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/mtxrunjit.exe b/Master/texmf-dist/scripts/context/stubs/win64/mtxrunjit.exe
deleted file mode 100755
index 93290a6e0a8..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/mtxrunjit.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/pstopdf.exe b/Master/texmf-dist/scripts/context/stubs/win64/pstopdf.exe
deleted file mode 100755
index 93290a6e0a8..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/pstopdf.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/texexec.exe b/Master/texmf-dist/scripts/context/stubs/win64/texexec.exe
deleted file mode 100755
index 93290a6e0a8..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/texexec.exe
+++ /dev/null
Binary files differ
diff --git a/Master/texmf-dist/scripts/context/stubs/win64/texmfstart.exe b/Master/texmf-dist/scripts/context/stubs/win64/texmfstart.exe
deleted file mode 100755
index 93290a6e0a8..00000000000
--- a/Master/texmf-dist/scripts/context/stubs/win64/texmfstart.exe
+++ /dev/null
Binary files differ