Debian Codegraph @

texmf-dist/tex/lualatex/pyluatex/pyluatex.lua

raw
1 --[[
2 MIT License
3
4 Copyright (c) 2021-2026 Tobias Enderle
5
6 Permission is hereby granted, free of charge, to any person obtaining a
7 copy of this software and associated documentation files (the "Software"),
8 to deal in the Software without restriction, including without limitation
9 the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 and/or sell copies of the Software, and to permit persons to whom the
11 Software is furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included
14 in all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 IN THE SOFTWARE.
23 --]]
24
25 require("lualibs")
26 local socket = require("socket")
27 local pyluatex_parsers = require("pyluatex-parsers")
28
29 local cctab_latex = luatexbase.registernumber("catcodetable@latex")
30 local cctab_atletter = luatexbase.registernumber("catcodetable@atletter")
31
32 local pyluatex = {}
33
34 -- status.filename: path to pyluatex.sty
35 local folder = file.pathpart(file.collapsepath(status.filename, true))
36 local tcp
37
38 local env_end
39 local env_lines
40 local parent_env
41
42 local cmd_handlers = {}
43
44 local last_code
45 local last_output
46
47 local options = { {
48 executable = "python3",
49 localimports = true,
50 shutdown = "veryveryend",
51 quiet = false,
52 repl = false,
53 store = true,
54 session = "default",
55 ignoreerrors = false,
56 verbose = false,
57 } }
58 local bool_options = set.create({
59 "localimports", "quiet", "repl", "store", "ignoreerrors", "verbose"
60 })
61 local valid_cmd_keys = set.create({
62 "quiet", "repl", "store", "session", "ignoreerrors", "verbose"
63 })
64 local key_aliases = {
65 ["ignore errors"] = "ignoreerrors",
66 ["local imports"] = "localimports",
67 q = "quiet",
68 s = "session",
69 }
70
71 local function fmt(...)
72 return string.format(...)
73 end
74
75 local function show_err(message, ...)
76 tex.sprint(
77 cctab_latex,
78 "\\PackageError{PyLuaTeX}{" .. fmt(message, ...) .. "}{}"
79 )
80 end
81
82 local function not_empty(str)
83 return str ~= nil and str ~= ""
84 end
85
86 local function parse_option_value(key, value)
87 if bool_options[key] ~= nil then
88 if value == true then return true end
89 value = value:fullstrip()
90 if value == "true" then return true
91 elseif value == "false" then return false
92 else
93 return nil, fmt(
94 'Option "%s" must be "true" or "false" but is "%s"', key, value
95 )
96 end
97 elseif value ~= true then
98 return value
99 else
100 return nil, fmt('Value missing for option "%s"', key)
101 end
102 end
103
104 local function extract_options(str, valid_keys, presets)
105 local presets_keys = set.create(table.keys(presets))
106 local opts = presets
107 local parsed_opts = pyluatex_parsers.parse_options(str)
108 if parsed_opts == nil then
109 return nil, fmt('Invalid option string: "%s"', str)
110 end
111 for key, val in pairs(parsed_opts) do
112 if key_aliases[key] ~= nil then
113 key = key_aliases[key]
114 end
115 if valid_keys[key] == nil then
116 return nil, fmt('Invalid option: "%s"', key)
117 elseif presets_keys[key] ~= nil then
118 return nil, fmt('Option "%s" not allowed here', key)
119 else
120 local v, err = parse_option_value(key, val)
121 if v == nil then return nil, err end
122 opts[key] = v
123 end
124 end
125 return opts
126 end
127
128 function pyluatex.set_options(str, presets, global)
129 local opts, err = extract_options(str, valid_cmd_keys, presets)
130 if opts == nil then
131 show_err(err)
132 return
133 end
134 if global then
135 table.merge(options[1], opts)
136 else
137 for k in pairs(valid_cmd_keys) do
138 if opts[k] == nil then opts[k] = options[#options][k] end
139 end
140 table.insert(options, opts)
141 end
142 end
143
144 local function pop_options()
145 return table.remove(options)
146 end
147
148 local function split_lines(str)
149 local lines = str:splitlines()
150 if lines[#lines] == "" then
151 table.remove(lines)
152 end
153 return lines
154 end
155
156 function pyluatex.shutdown()
157 tcp:send("shutdown\n")
158 end
159
160 local function request(data)
161 tcp:send(utilities.json.tostring(data) .. "\n")
162 local output = tcp:receive("*l")
163 return utilities.json.tolua(output)
164 end
165
166 function pyluatex.execute(
167 code,
168 auto_print,
169 catcode_table,
170 write,
171 repl_mode,
172 store,
173 session,
174 ignore_errors,
175 verbose
176 )
177 local full_code
178 if auto_print then
179 full_code = "print(str(" .. code .. "), end='')"
180 else
181 full_code = code
182 end
183
184 local resp = request({
185 session = session,
186 code = full_code,
187 repl_mode = repl_mode,
188 ignore_errors = ignore_errors
189 })
190 local output_lines = split_lines(resp.output)
191 if store then
192 last_code = split_lines(code)
193 last_output = output_lines
194 end
195
196 if verbose or not resp.success then
197 texio.write_nl(
198 fmt('PyLuaTeX input for session "%s": %s', session, full_code)
199 )
200 texio.write_nl("PyLuaTeX output: " .. resp.output)
201 end
202
203 if not_empty(resp.log_msg) then texio.write(resp.log_msg) end
204
205 if resp.success or ignore_errors then
206 if write then tex.print(catcode_table, output_lines) end
207 else
208 show_err("Python error (see above)")
209 end
210 end
211
212 function pyluatex.execute_with_options(code, auto_print, catcode_table)
213 local opts = pop_options()
214 pyluatex.execute(
215 code,
216 auto_print,
217 catcode_table,
218 not opts.quiet,
219 opts.repl,
220 opts.store,
221 opts.session,
222 opts.ignoreerrors,
223 opts.verbose
224 )
225 end
226
227 function pyluatex.opt_arg()
228 local t = token.get_next()
229 if t.index ~= string.byte("[") then tex.sprint("[]") end
230 token.put_next(t)
231 end
232
233 function pyluatex.prepare_cmd_handler(presets, func, ...)
234 table.insert(cmd_handlers, {presets = presets, func = func, args = {...}})
235 end
236
237 -- The handler must remove the most recent options with pop_options()
238 function pyluatex.handle_cmd(opts, content)
239 local handler = table.remove(cmd_handlers)
240 pyluatex.set_options(opts, handler.presets)
241 handler.func(content, table.unpack(handler.args))
242 end
243
244 function pyluatex.execute_env()
245 pyluatex.execute_with_options(table.concat(env_lines, "\n"), false, -1)
246 end
247
248 local function record_line(line)
249 local s = line:find(env_end)
250 if s ~= nil then
251 luatexbase.remove_from_callback(
252 "process_input_buffer", "pyluatex_record_line"
253 )
254 local code = line:sub(1, s - 1)
255 if code:strip():len() > 0 then
256 -- only include this line if it contains non-whitespace characters
257 table.insert(env_lines, code)
258 end
259 return line:sub(s)
260 else
261 table.insert(env_lines, line)
262 return ""
263 end
264 end
265
266 function pyluatex.record_env(name)
267 if parent_env ~= nil then
268 name = parent_env
269 parent_env = nil
270 end
271 env_end = "\\end%s*{" .. name:escapedpattern() .. "}"
272 env_lines = {}
273 luatexbase.add_to_callback(
274 "process_input_buffer", record_line, "pyluatex_record_line"
275 )
276 end
277
278 function pyluatex.set_parent_env(name)
279 if parent_env == nil then
280 parent_env = name
281 end
282 end
283
284 function pyluatex.run_file(path)
285 local code = io.loaddata(path)
286 if code then
287 code = code:gsub("\r?\n$", "") -- ignore trailing new line if present
288 pyluatex.execute_with_options(code, false, -1)
289 else
290 show_err('File "%s" not found', path)
291 end
292 end
293
294 function pyluatex.py_if(code)
295 pyluatex.execute_with_options(
296 fmt([[r'\@firstoftwo' if (%s) else r'\@secondoftwo']], code),
297 true,
298 cctab_atletter
299 )
300 end
301
302 function pyluatex.get_last_code()
303 return last_code
304 end
305
306 function pyluatex.get_last_output()
307 return last_output
308 end
309
310 local function process_package_options()
311 local opts, err = extract_options(
312 token.get_macro("@raw@[email protected]"),
313 set.create(table.keys(options[1])),
314 {}
315 )
316 if opts == nil then
317 show_err(err)
318 return
319 end
320 table.merge(options[1], opts)
321
322 local function add_to_hook(hook)
323 tex.print(fmt([[\AddToHook{%s}{\directlua{pyluatex.shutdown()}}]], hook))
324 end
325
326 if options[1].shutdown == "veryveryend" then
327 add_to_hook("enddocument/end")
328 elseif options[1].shutdown == "veryenddocument" then
329 add_to_hook("enddocument/afteraux")
330 elseif options[1].shutdown ~= "off" then
331 show_err('Option "shutdown" must be "veryveryend", "veryenddocument", '
332 .. 'or "off" but is "%s"', options[1].shutdown)
333 end
334 end
335
336 local function get_tex_file_folder()
337 for _, v in ipairs(arg) do
338 if v:sub(1, 1) ~= "-" then
339 local path = file.collapsepath(v, true)
340 if lfs.isfile(path) then
341 return file.pathpart(path)
342 else
343 path = file.addsuffix(path, "tex")
344 if lfs.isfile(path) then
345 return file.pathpart(path)
346 end
347 end
348 end
349 end
350 return nil
351 end
352
353 function pyluatex.start()
354 process_package_options()
355
356 local script = file.join(folder, "pyluatex-interpreter.py")
357
358 local cmd = fmt('%s "%s"', options[1].executable, script)
359 if options[1].localimports then
360 local tex_file_folder = get_tex_file_folder()
361 if tex_file_folder then
362 cmd = cmd .. fmt(' "%s"', tex_file_folder)
363 end
364 end
365 if os.type == "windows" then
366 cmd = "start /B " .. cmd
367 else
368 cmd = cmd .. " &"
369 end
370
371 local f = io.popen(cmd, "r")
372 local port = f:read("*l")
373 f:close()
374
375 local function err(message)
376 show_err("Python backend could not be started (%s)", message)
377 end
378
379 if port == nil then
380 err("executable: " .. options[1].executable)
381 return
382 end
383 port = port:fullstrip()
384 if port:find("^%d+$") == nil then
385 err("invalid TCP port: " .. port)
386 return
387 end
388 tcp = socket.tcp()
389 if tcp:connect("127.0.0.1", port) == nil then
390 err("TCP connection failed")
391 end
392 end
393
394 return pyluatex