Debian Codegraph @

texmf-dist/tex/luatex/interpreter/interpreter.lua

raw
1 -- This is the main Lua file for the Interpreter package.
2 -- Further information in interpreter-doc.pdf or interpreter-doc.txt.
3 -- Paul Isambert - zappathustra AT free DOT fr - June 2012
4 --
5 -- Beware, this is written with Gates. Please read the Gates doc if
6 -- you want to understand something.
7
8 local find, gsub, match, sub = string.find, string.gsub, string.match, string.sub
9 local insert, sort, remove = table.insert, table.sort, table.remove
10 local io_open = io.open
11 local ipairs, pairs, type = ipairs, pairs, type
12 require("gates.lua")
13 if not gates.iterator then
14 tex.error("Interpreter error: Your version of Gates should be at least v.0.2. I quit. Expect chaos")
15 return
16 end
17
18 interpreter = gates.new("interpreter")
19
20 -- *** interpreter.active ***
21 -- Following paragraphs (as defined by interpreter.paragraph) are interpreted
22 -- iff this is not set to false.
23 interpreter.active = true
24 -- *** interpreter.default_class ***
25 -- Sets the default class for patterns which are added without specifying the
26 -- class. Default 1.
27 interpreter.default_class = 1
28
29 interpreter.core = {
30 classes = {}, -- The classes of patterns.
31 lines = {}, -- The lines of the paragraph.
32 reader = gates.new("interpreter_reader"), -- The main processing functions.
33 tools = gates.new("interpreter_tools")} -- Auxiliary functions.
34
35 -- Utility function sorting patterns by length (alphabetically if they are of
36 -- equal length).
37 function interpreter.core.tools.sort (a, b)
38 local a, b = a.pattern, b.pattern
39 return #a == #b and a < b or #a > #b
40 end
41
42 -- *** interpreter.add_pattern (table) ***
43 -- Creates pattern <table>, which can contain the following entries:
44 -- pattern [string] = The pattern to match. Magic characters are obeyed!
45 -- replace [string] = The replacement for <pattern>. Can be a string, a
46 -- table or a function. A simple string.gsub() is
47 -- applied.
48 -- call [function] = The function applied to <pattern>; <replace> is applied
49 -- iff there is no <call>.
50 -- offset [number] = If <pattern> is used at index n, then the search on the
51 -- same line for the same pattern starts again at index n
52 -- + offset. Applied only when no <call> (in this case,
53 -- search starts again at the beginning of the line). By
54 -- default, offset = 0. This is needed to avoid infinite
55 -- loops with replacements which contain the pattern;
56 -- e.g. replacing "TeX" with "\TeX" will produce an
57 -- infinite loop, unless offset = 2.
58 -- nomagic [boolean] = Sets whether <replace> should be transformed with interpreter.nomagic.
59 -- class [number] = The pattern's <class> (classes of patterns are applied in
60 -- order, e.g. all patterns in class 1 are applied, then
61 -- all patterns in class 2, etc; class 0, however, is
62 -- always applied last). If <class> is not given, the
63 -- default_class number is used. Classes must be numbered
64 -- consecutively.
65 interpreter.list{"add_pattern",
66 {"ensure_class",
67 function (tb)
68 local class = tb.class or interpreter.default_class
69 interpreter.set_class(class, {})
70 setmetatable(tb, interpreter.core.classes[class].meta)
71 return tb, class
72 end},
73 {"apply_nomagic", conditional = function (tb) return tb.nomagic end,
74 autoreturn = true,
75 function (tb, class)
76 tb.pattern = interpreter.nomagic(tb.pattern)
77 end},
78 {"insert_pattern", autoreturn = true,
79 {"do_insert", autoreturn = true,
80 function (tb, class)
81 insert(interpreter.core.classes[class], tb)
82 end},
83 {"sort_class", autoreturn = true,
84 function (tb, class)
85 sort(interpreter.core.classes[class], interpreter.core.tools.sort)
86 end}}}
87
88 -- *** interpreter.set_class (number, table) ***
89 -- Sets default values (of the table normally specified in add_pattern) for
90 -- patterns of class <number>; patterns added to this class can still specify
91 -- different values, which will override defaults. In other words, this is a
92 -- metatable for patterns (which are tables) of that class.
93 function interpreter.set_class (num, tb)
94 interpreter.core.classes[num] = interpreter.core.classes[num] or
95 { meta = { __index = function (_, k) return interpreter.core.classes[num].meta[k] end } }
96 for a, b in pairs(tb) do
97 interpreter.core.classes[num].meta[a] = b
98 end
99 return interpreter.core.classes[num]
100 end
101
102 -- Class 0 must exist since it is always used at the end of the paragraph.
103 interpreter.set_class(0, {})
104
105 -- *** interpreter.nomagic (string) ***
106 -- Turns a normal string into a string with magic characters escaped, so it
107 -- can be used as a pattern.
108 interpreter.core.tools.magic_characters = {
109 ["^"] = "%^",
110 ["$"] = "%$",
111 ["("] = "%(",
112 [")"] = "%)",
113 ["%"] = "%%",
114 ["."] = "%.",
115 ["["] = "%[",
116 ["]"] = "%]",
117 ["*"] = "%*",
118 ["+"] = "%+",
119 ["-"] = "%-",
120 ["?"] = "%?",
121 }
122 function interpreter.nomagic (str)
123 local i, s = 1, ""
124 local magic_characters = interpreter.core.tools.magic_characters
125 while i <= #str do
126 local c, c2, c3 = sub(str, i, i), sub(str, i + 1, i + 1), sub(str, i + 2, i + 2)
127 i = i + 1
128 if c == "%" and magic_characters[c2] then
129 s = s .. c2
130 i = i + 1
131 elseif c == "." and c2 == "." and c3 == "." then
132 s = s .. "(.-)"
133 i = i + 2
134 elseif magic_characters[c] then
135 s = s .. "%" .. c
136 else
137 s = s .. c
138 end
139 end
140 return s
141 end
142
143 -- *** interpreter.protect ([spec]) ***
144 -- Protects a set of lines in a paragraph; a protected line won't be
145 -- interpreted. If <spec> is a number, this protects line <spec> in the current
146 -- paragraph; if <spec> is true, this protects the entire current paragraph. Of
147 -- course, patterns that were applied to the line(s) or paragraph before
148 -- protection happened aren't undone.
149 function interpreter.protect (num)
150 if type(num) == "number" then
151 if type(interpreter.core.reader.protected) ~= "boolean" then
152 interpreter.core.reader.protected = interpreter.core.reader.protected or {}
153 interpreter.core.reader.protected[num] = true
154 end
155 else
156 interpreter.core.reader.protected = true
157 end
158 end
159
160 -- Utility function making a replacement in a string but only from a certain
161 -- position and only once. We can't let gsub unrestricted, because some
162 -- part(s) of the string might be protected.
163 function interpreter.core.tools.xsub (str, num, patt, rep)
164 return sub(str, 1, num-1) .. gsub(sub(str, num), patt, rep, 1)
165 end
166
167 -- *** interpreter.protector (left [, right]) ***
168 -- Sets <left> and <right> (set to <left> if missing) as protectors, i.e.
169 -- enclosed material won't be processed even if the line is processed
170 -- otherwise. For instance: after interpreter.protector ("|"), the word
171 -- "little" in
172 --
173 -- Hello, |little| world!
174 --
175 -- will be left untouched; Interpreter is terribly smart (thanks to lpeg), so
176 -- in "|a| b |c|", "b" isn't protected, as intended, because the "|" on its
177 -- left doesn't match the one on its right but with the one before "a". An
178 -- example with <right> specified: interpreter.protector("[", "]") and
179 -- then:
180 --
181 -- Hello, [little] world!
182 --
183 -- achieves the same as above. Protectors AREN'T removed when the line is
184 -- finally passed to TeX; and there can be several protectors. Compare with
185 -- interpreter.escape.
186 local P, Cf, Cg, Cp, Ct, V = lpeg.P, lpeg.Cf, lpeg.Cg, lpeg.Cp, lpeg.Ct, lpeg.V
187 local _grammar
188 function interpreter.core.tools.protector (str, index)
189 local protections = Cf(Ct("") * Cg{ _grammar + 1 * V(1) }^1, rawset)
190 protections = protections:match(str)
191 if protections then
192 for a, b in pairs(protections) do
193 if index > a and index < b then
194 return nil, b
195 end
196 end
197 end
198 return index
199 end
200 function interpreter.protector (left, right)
201 right = right or left
202 local gram = P(Cp() * P(left) * (1 - P(right))^0 * Cp() * P(right))
203 if _grammar then
204 _grammar = _grammar + gram
205 else
206 _grammar = gram
207 end
208 end
209
210 -- *** interpreter.escape ***
211 -- A string used as an escape character: if a pattern matches, it is processed
212 -- iff the character immediately to its left isn't <escape>. The escape
213 -- character IS removed once the lines have been processed, so TeX never sees
214 -- it; also, only one escape character is allowed, and itself can't be escaped
215 -- (i.e. it doesn't mean anything to try to escape it). E.g.:
216 --
217 -- interpreter.escape = "|"
218 -- ... this won't be |*processed*
219 --
220 -- Assuming you have a pattern with stars, here it won't be applied. Instead
221 -- "this won't be *processed*" will be passed to TeX (note that the escape
222 -- character has disappeared).
223
224 function interpreter.core.tools.get_index (str, patt, index)
225 index = find(str, patt, index)
226 if index then
227 if sub(str, index-1, index-1) == interpreter.escape then
228 return interpreter.core.tools.get_index(str, patt, index + 1)
229 elseif _grammar then
230 local right
231 index, right = interpreter.core.tools.protector(str, index, patt)
232 return index or interpreter.core.tools.get_index(str, patt, right + 1)
233 else
234 return index
235 end
236 end
237 end
238
239 -- *** interpreter.paragraph ***
240 -- The pattern that defines a line acting as a paragraph boundary,
241 -- prompting Interpreter to process the lines gathered up to now. Default is a
242 -- line composed of spaces at most.
243 interpreter.paragraph = "%s*"
244
245 -- *** interpreter.direct (pattern) ***
246 -- Sets the pattern defining a line as direct Lua code: if a line begins with
247 -- <pattern> (which itself shouldn't contain the beginning-of-string character "^")
248 -- the code that follows is processed as Lua code, and the line is turned to
249 -- an empty string; note that this empty string will be seen as a paragraph
250 -- boundary if the line happened in the middle of a paragraph and
251 -- interpreter.paragraph has set paragraph boundary to empty string. Default
252 -- is "%%I " (two "%" followed by one "I" followed by at least one space
253 -- character).
254 interpreter.direct = "%%%%I%s+"
255
256 -- At last, the function to be registered in open_read_file, defining the
257 -- function that reads a file.
258
259 interpreter.core.reader.current_line = 0
260 interpreter.core.reader.current_line = 0
261
262 interpreter.core.reader.list{"read_file",
263 {"make_paragraph", conditional = function () return #interpreter.core.lines == 0 end,
264 {"aggregate_lines", loopuntil = function (_, line) return not line or gsub(line, "^" .. interpreter.paragraph .. "$", "") == "" end,
265 {"read_line",
266 function (f)
267 return f, f:read()
268 end},
269 {"check_direct", conditional = function (_, line) return line and interpreter.direct end,
270 function (f, line)
271 if match(line, "^" .. interpreter.direct) then
272 loadstring(gsub(line, "^" .. interpreter.direct, ""))()
273 line = ""
274 end
275 return f, line
276 end},
277 {"insert_line", conditional = function (_, line) return line end,
278 autoreturn = true,
279 function (f, line)
280 insert(interpreter.core.lines, line)
281 end}},
282 {"apply_classes", conditional = function () return #interpreter.core.lines > 0 and interpreter.active end,
283 {"pass_class", iterator = function ()
284 local done_zero
285 local function f (t, i)
286 if type(interpreter.core.reader.protected) ~= "boolean" then
287 if not done_zero then
288 i = i+1
289 local v = t[i]
290 if v then
291 return i, v
292 else
293 done_zero = true
294 return 0, t[0]
295 end
296 end
297 end
298 end
299 return f, interpreter.core.classes, 0
300 end,
301 {"pass_pattern", iterator = function (_, class)
302 local function f (t, i)
303 if type(interpreter.core.reader.protected) ~= "boolean" then
304 i = i+1
305 local v = t[i]
306 if v then
307 return i, v
308 end
309 end
310 end
311 return f, class, 0
312 end,
313 {"process_lines", iterator = function (_, pattern)
314 interpreter.core.reader.current_line = 0
315 interpreter.core.reader.current_index = 0
316 return function ()
317 if type(interpreter.core.reader.protected) ~= "boolean" then
318 local l = interpreter.core.reader.current_line
319 local i = interpreter.core.reader.current_index
320 if i == 0 then
321 l, i = l + 1, 1
322 end
323 line = interpreter.core.lines[l]
324 -- When protected, a line is a table.
325 while type(line) == "table" do
326 l, i = l+1, 1
327 line = interpreter.core.lines[l]
328 end
329 if line then
330 interpreter.core.reader.current_line = l
331 interpreter.core.reader.current_index = i
332 return l, pattern, i
333 end
334 end
335 end
336 end,
337 {"switch", autoreturn = true,
338 function (_, pattern)
339 if pattern.call then
340 interpreter.core.reader.ajar("call", "process_lines")
341 elseif pattern.replace then
342 interpreter.core.reader.ajar("replace", "process_lines")
343 end
344 end},
345 {"call", status = "close",
346 function(i, pattern, ind)
347 local line = interpreter.core.lines[i]
348 local index = interpreter.core.tools.get_index(line, pattern.pattern, ind)
349 if index then
350 local L, O = pattern.call(interpreter.core.lines, i, index, pattern)
351 if O then
352 interpreter.core.reader.current_line = L
353 interpreter.core.reader.current_index = O
354 elseif L then
355 interpreter.core.reader.current_index = L
356 end
357 else
358 interpreter.core.reader.current_index = 0
359 end
360 end},
361 {"replace", status = "close",
362 function(i, pattern, ind)
363 local line = interpreter.core.lines[i]
364 local index = interpreter.core.tools.get_index(line, pattern.pattern, ind)
365 if index then
366 interpreter.core.lines[i] = interpreter.core.tools.xsub(line, index, pattern.pattern, pattern.replace)
367 interpreter.core.reader.current_index = index + (pattern.offset or 0)
368 else
369 interpreter.core.reader.current_index = 0
370 end
371 end},
372 {"protect", iterator = function ()
373 if type(interpreter.core.reader.protected) == "table" then
374 return pairs(interpreter.core.reader.protected)
375 end
376 end,
377 function (n)
378 if type(interpreter.core.lines[n]) == "string" then
379 interpreter.core.lines[n] = {interpreter.core.lines[n]}
380 end
381 end}}}},
382 {"unprotect",
383 {"undo_protected",
384 function ()
385 interpreter.core.reader.protected = nil
386 end},
387 {"unprotect_lines", iterator = function () return ipairs(interpreter.core.lines) end,
388 function (i, l)
389 if type(l) == "table" then
390 interpreter.core.lines[i] = l[1]
391 end
392 end}},
393 {"remove_escape", conditional = function () return interpreter.escape end,
394 function ()
395 for num, line in ipairs(interpreter.core.lines) do
396 interpreter.core.lines[num] = gsub(line, interpreter.escape, "")
397 end
398 end}}},
399 {"return_line",
400 function ()
401 return remove(interpreter.core.lines, 1)
402 end}}
403
404 interpreter.core.reader.list{"input",
405 -- *** interpreter.unregister () ***
406 -- The function used to remove read_file from the "open_read_file" callback.
407 -- Uses callback.register by default, or luatexbase.remove_from_callback if
408 -- detected.
409 {"unregister", autoreturn = true,
410 {"set_unregister", conditional = function () return interpreter.type"unregister" == 0 end,
411 function ()
412 if luatexbase and luatexbase.remove_from_callback then
413 function interpreter.unregister ()
414 luatexbase.remove_from_callback("open_read_file", "interpreter")
415 end
416 else
417 function interpreter.unregister ()
418 callback.register("open_read_file", nil)
419 end
420 end
421 end},
422 {"use_unregister",
423 function () -- You can't use the `unregister' gate directly, because it isn't created yet.
424 interpreter.unregister()
425 end}},
426 {"open_file",
427 function (fname)
428 return io_open(fname)
429 end},
430 {"set_reader",
431 function (f)
432 return {reader = function () return interpreter.core.reader.read_file(f) end}
433 end}}
434
435 function interpreter.reset ()
436 interpreter.active = true
437 interpreter.default_class = 1
438 interpreter.core.classes = {}
439 interpreter.set_class(0, {})
440 _grammar = nil
441 interpreter.escape = nil
442 interpreter.paragraph = "%s*"
443 interpreter.direct = "%%%%I%s+"
444 end
445
446 -- *** interpreter.register (function) ***
447 -- The function used to register the read_file function in the
448 -- "open_read_file" callback. If none is given, use callback.register, or
449 -- luatexbase.add_to_callback if detected (with "interpreter" as the name).
450 -- The function is defined in \interpretfile (see interpreter.tex).