Debian Codegraph @

texmf-dist/tex/lualatex/kkluaverb/KKluaverb.lua

raw
1 -- KKluaverb.lua
2 -- Copyright (c) 2026 Kosei Kawaguchi
3 -- Released under the MIT License (see LICENSE.md for details)
4 --
5 -- This file is based on 'bxrawstr.lua' by Takayuki YATO (aka. "ZR").
6 -- Copyright (c) 2018 Takayuki YATO
7 --
8
9 luatexbase.provides_module{
10 name = 'KKluaverb',
11 date = '2026/01/27',
12 version = '2.1.2',
13 }
14
15 ----- for .sty interface -----
16 KKLuaVerb = KKLuaVerb or {}
17 ----------
18
19
20 ----- for .lua interface-----
21 local KKV = {}
22 local in_process = false
23
24 local CMD_INIT = "\\KKlvStart*"
25 local CMD_TERM = "\\KKlvEnd*"
26 local DEFAULT_STARTER = "\\KKverb"
27 local DEFAULT_STARTER_flag1 = "\\KKcodeS"
28 local DEFAULT_TERMINATOR_flag1 = "\\KKcodeE"
29
30 local ltjflg = utf8.char(0xFFFFF) .. "\n$"
31 ----------
32
33
34 ----- encode -----
35 function KKV.encode(str)
36 if not str then return "" end
37
38 local t = {}
39
40 for _, code in utf8.codes(str) do -- discard pos
41 if ((code >= 48 and code <= 57) -- 0-9
42 or (code >= 65 and code <= 90) -- A-Z
43 or (code >= 97 and code <= 122)) -- a-z
44 and code ~= 42 then -- except for '*'
45 table.insert(t, string.char(code))
46 else
47 -- Transform the input into hexadecimal.
48 local formatted
49 if code < 0x100 then
50 formatted = string.format("*%02X", code)
51 elseif code < 0x10000 then
52 formatted = string.format("*u%04X", code)
53 else
54 formatted = string.format("*U%06X", code)
55 end
56 table.insert(t, formatted)
57 end
58 end
59
60 return table.concat(t)
61 end
62
63 function KKV.encode_tail(str)
64 local s = (str .. "\n"):gsub(ltjflg, "\n")
65 return KKV.encode(s)
66 end
67 ----------
68
69
70 ----- replacement -----
71 KKV.replacements = {}
72
73 function KKV.add_replacement(from_char, to_char)
74 KKV.replacements[from_char] = to_char
75 end
76
77 KKV.add_replacement(" ", "\194\160")
78 -- Avoid ignoring space.
79 ----------
80
81
82 ----- decode -----
83 function KKV.decode(rstr)
84 local chex = function(s) return utf8.char(tonumber(s, 16)) end
85 local decoded = rstr
86 :gsub('*U(%x%x%x%x%x%x)', chex)
87 :gsub('*u(%x%x%x%x)', chex)
88 :gsub('*(%x%x)', chex)
89
90 -- After characters are decoded, run the replacer.
91 for from, to in pairs(KKV.replacements) do
92 decoded = decoded:gsub(from, to)
93 end
94
95 -- How to process linebreak
96 local lb_flag = tex.gettoks("kklv@linebreak")
97
98 -- If lb_flag is "1",
99 -- a "verbatim paragraph" is produced.
100 -- Behave like an environment.
101 if lb_flag == "1" then
102 local dc_lines = {}
103 local fl_linenumber = (tex.count["kklv@linenum@start"] - 1)
104
105 -- Separate 'decoded' to 'dc_lines'.
106 for line in (decoded .. "\n"):gmatch("(.-)\n") do
107 table.insert(dc_lines, line)
108 end
109 local last_idx = #dc_lines
110 last_idx = last_idx - 1
111 -- Delete the last line.
112 tex.sprint("\\par\\noindent")
113 for i = 2, last_idx do -- ref: NOTE#1
114 local content = dc_lines[i]
115 if content ~= "" then
116 local map_to_use = KKV.active_map or {}
117 KKV.output_with_multiple_colors(content, map_to_use, true)
118 end
119 if i < last_idx then
120 tex.sprint("\\hfill\\break\\noindent")
121 else
122 tex.sprint("\\hspace*{\\fill}\\par")
123 end
124 end
125
126 -- If lb_flag is "2",
127 -- a "verbatim paragraph with line numbers"
128 -- is produced.
129 -- Behave like an environment.
130 elseif lb_flag == "2" then
131 local dc_lines = {}
132 local fl_linenumber = (tex.count["kklv@linenum@start"] - 1)
133
134 -- Separate 'decoded' to 'dc_lines'.
135 for line in (decoded .. "\n"):gmatch("(.-)\n") do
136 table.insert(dc_lines, line)
137 end
138 local last_idx = #dc_lines
139 last_idx = last_idx - 1
140 -- Delete the last line.
141 tex.sprint("\\par\\noindent")
142 for i = 2, last_idx do -- ref: NOTE#1
143 tex.sprint("\\KKlvLineNumber{" .. (i - 1 + fl_linenumber) .. "}")
144 local content = dc_lines[i]
145 if content ~= "" then
146 local map_to_use = KKV.active_map or {}
147 KKV.output_with_multiple_colors(content, map_to_use, true)
148 end
149 if i < last_idx then
150 tex.sprint("\\hfill\\break\\noindent")
151 else
152 tex.sprint("\\hspace*{\\fill}\\par")
153 end
154 end
155
156 -- If lb_flag is not "1" or "2",
157 -- any linebreaks are completely ignored.
158 else
159 decoded = decoded:gsub('[\t\r\n]', '')
160 local map_to_use = KKV.active_map or {}
161 KKV.output_with_multiple_colors(decoded, map_to_use)
162 end
163 end
164 ----------
165
166
167 ----- scanner -----
168 function KKV.scanner_for_verb(line)
169 -- If the scanner is unabled, it returns nil.
170 if not KKLuaVerb.enabled then return nil end
171
172 -- When the process_input_buffer runs,
173 -- a chunk of text on a single line
174 -- is passed to the function as the argument `line`
175
176 local spec = tex.gettoks("kklv@delims")
177
178 -- In the .sty, \kklv@delims is defined
179 -- as {token1}{token2}.
180 -- So cut off the brackets.
181 local ini_raw, trm_raw = spec:match("^{(.*)}{(.*)}$")
182 local ini = ini_raw or "|"
183 local trm = trm_raw or "|"
184
185 local pos = 1 -- the character index
186 local res = {} -- a transformed chunk
187 local start_cmd = DEFAULT_STARTER .. ini
188 local shortcut_start = DEFAULT_STARTER_flag1
189 local shortcut_end = DEFAULT_TERMINATOR_flag1
190
191 -- While the character index
192 -- <= the length of the line,
193 -- scan the chunk:
194 while (pos <= #line) or (in_process and pos == 1 and #line == 0) do
195 if not in_process then
196 -- for \KKverb
197 local s_idx, e_idx = line:find(start_cmd, pos, true)
198 -- for \KKcodeS, E
199 local s_short_idx, e_short_idx = line:find(shortcut_start, pos, true)
200
201 if s_short_idx and (not s_idx or s_short_idx < s_idx) then
202 in_process = true
203
204 local next_char = line:sub(e_short_idx + 1, e_short_idx + 1)
205 local style_num = "1"
206 local skip_len = 0
207
208 if next_char == "+" then
209 style_num = "2"
210 skip_len = 1
211 end
212
213 local transform = line:sub(pos, s_short_idx - 1) .. "{\\KKvLNChange{style=" .. style_num .. "}" .. CMD_INIT
214 table.insert(res, transform)
215
216 pos = e_short_idx + 1 + skip_len
217
218 -- NOTE#1
219 -- This part was added
220 -- in order to avoid being inserted
221 -- unwanted space to the first line
222 -- when the flag is 1 or 2.
223 if not line:find(shortcut_end, pos, true) then
224 local sc_content = line:sub(pos)
225 table.insert(res, KKV.encode_tail(sc_content) .. "%")
226 pos = #line + 1
227 end
228 elseif s_idx then
229 in_process = true
230 table.insert(res, line:sub(pos, s_idx - 1) .. CMD_INIT)
231 pos = e_idx + 1
232
233 -- NOTE#1
234 -- This part was added
235 -- in order to avoid being inserted
236 -- unwanted space to the first line
237 -- when the flag is 1 or 2.
238 if not line:find(trm, pos, true) then
239 local sc_content = line:sub(pos)
240 table.insert(res, KKV.encode_tail(sc_content) .. "%")
241 pos = #line + 1
242 end
243 else
244 local sc_content = line:sub(pos)
245 table.insert(res, sc_content)
246 break
247 end
248
249 else
250 local s_idx, e_idx = line:find(trm, pos, true)
251 local s_short_end_idx, e_short_end_idx = line:find(shortcut_end, pos, true)
252
253 if s_short_end_idx and (not s_idx or s_short_end_idx < s_idx) then
254 local sc_content = line:sub(pos, s_short_end_idx - 1)
255 table.insert(res, KKV.encode(sc_content) .. CMD_TERM .. "}")
256 in_process = false
257 pos = e_short_end_idx + 1
258
259 elseif s_idx then
260 local sc_content = line:sub(pos, s_idx - 1)
261 table.insert(res, KKV.encode(sc_content) .. CMD_TERM)
262 in_process = false
263 pos = e_idx + 1
264
265 else
266 local sc_content = line:sub(pos)
267 table.insert(res, KKV.encode_tail(sc_content) .. "%")
268 break
269 end
270 end
271 end
272 return table.concat(res)
273 end
274 ----------
275
276
277 ----- color changer -----
278 local function is_alnum(char, options)
279 if not char or char == "" then return false end
280 local p = options.word_components or "[A-Za-z0-9_]"
281 return char:match(p) ~= nil
282 end
283 -- Enhancement in v2.1.1
284 -- If you want to set a certain character like "\"
285 -- as a word component, use map-op:
286 --
287 -- options = {
288 -- word_components = "[A-Za-z0-9_\\]"
289 -- }
290
291 local function find_closing_delimiter(line, stop_char, start_pos, escape_char)
292 local search_pos = start_pos
293 while true do
294 local s = line:find(stop_char, search_pos, true)
295 if not s then return nil end
296
297 local is_escaped = false
298 if escape_char and s > 1 and line:sub(s-1, s-1) == escape_char then
299 local count = 0
300 local p = s - 1
301 while p >= 1 and line:sub(p, p) == escape_char do
302 count = count + 1
303 p = p - 1
304 end
305 if count % 2 == 1 then is_escaped = true end
306 end
307
308 if not is_escaped then
309 return s
310 end
311
312 search_pos = s + 1
313 end
314 end
315
316
317 local function parse_inside_delim(content, forced_tokens, base_color)
318 -- Only used in "delim" part
319
320 if not forced_tokens or type(forced_tokens) ~= "table" or not next(forced_tokens) then
321 return {{ type = "delim", content = content, color = base_color }}
322 end
323
324 local res = {}
325 local pos = 1
326
327 local keys = {}
328 for k in pairs(forced_tokens) do table.insert(keys, k) end
329
330 while pos <= #content do
331 local nearest_s, nearest_e, found_k
332
333 for _, k in ipairs(keys) do
334 local s, e = content:find(k, pos, true)
335 if s and (not nearest_s or s < nearest_s) then
336 nearest_s, nearest_e, found_k = s, e, k
337 end
338 end
339
340 if nearest_s then
341 if nearest_s > pos then
342 table.insert(res, { type = "delim_plain", content = content:sub(pos, nearest_s - 1), color = base_color })
343 end
344 -- forced
345 table.insert(res, { type = "token_delim", content = found_k, color = forced_tokens[found_k] })
346 pos = nearest_e + 1
347 else
348 -- plain
349 table.insert(res, { type = "delim_plain", content = content:sub(pos), color = base_color })
350 break
351 end
352 end
353
354 return res
355 end
356
357 function KKV.cut_multiple_tokens(line, targets, options)
358 local use_boundary = true
359 if options and options.word_boundary ~= nil then
360 use_boundary = options.word_boundary
361 end
362
363 local delims = (options and options.delimiters) or {}
364 -- unique delimiters
365 local forced = (options and options.forced_tokens) or {}
366 -- forced to change color even in delims
367
368 local escape_char = (options and options.escape_char) or "\\"
369 -- Currently, the default escaper is "\".
370 -- Is this a proper choice...?
371
372 local parts = {}
373 local pos = 1
374
375 while pos <= #line do
376 local nearest_s = nil
377 local nearest_e = nil
378 local found_token = nil
379 local found_delim_color = nil
380
381 for _, d in ipairs(delims) do
382 local s, _ = line:find(d.start, pos, true)
383 if s and (not nearest_s or s < nearest_s) then
384 local e = find_closing_delimiter(line, d.stop, s + #d.start, escape_char)
385 if e then
386 nearest_s = s
387 nearest_e = e + #d.stop - 1
388 found_token = nil
389 found_delim_color = d.color
390 end
391 end
392 end
393 -- Enhancement in v2.1.2
394 -- To make sure that keywords in "delim" category are color-changed,
395 -- I have to re-scan the delim part like this:
396 -- 1. When the system find a demil-pair, insert every text between them into "raw_delim" category.
397 -- 2. Serch for forced_keywords in the "raw_delim".
398 -- * forced_keywords means that this is completely different from the normal keywords and need to be set
399 -- in differnt part.
400 -- 3. Cut "raw_delim" like this:
401 -- $a + b = \frac{x}{y}$ (in this case, forced_keywords are "{" and "}".)
402 -- a + b = \frac → "plain_delim" colored by d_color
403 -- { → "token_delim" colored by t_d_color
404
405 for _, token in ipairs(targets) do
406 local s, e = line:find(token, pos, true)
407 if s then
408 local is_valid = true
409
410 if use_boundary then
411 -- Get the previous and next characters.
412 local prev_char = s > 1 and line:sub(s-1, s-1) or nil
413 local next_char = e < #line and line:sub(e+1, e+1) or nil
414
415 -- Check the tokens.
416 if is_alnum(token:sub(1, 1), options) and is_alnum(prev_char, options) then
417 is_valid = false
418 end
419 if is_alnum(token:sub(-1, -1), options) and is_alnum(next_char, options) then
420 is_valid = false
421 end
422 end
423
424 if is_valid and (not nearest_s or s < nearest_s) then
425 nearest_s = s
426 nearest_e = e
427 found_token = token
428 found_delim_color = nil
429 end
430 end
431 end
432
433 if nearest_s then
434 if nearest_s > pos then
435 table.insert(parts, { type = "plain", content = line:sub(pos, nearest_s - 1) })
436 end
437 if found_delim_color then
438 -- table.insert(parts, { type = "delim", content = line:sub(nearest_s, nearest_e), color = found_delim_color })
439
440 -- Enhancement in v2.1.2
441 -- Re-process "delim" part in order to search for forced_tokens.
442 local delim_raw = line:sub(nearest_s, nearest_e)
443 local sub_parts = parse_inside_delim(delim_raw, forced, found_delim_color)
444 for _, sp in ipairs(sub_parts) do
445 table.insert(parts, sp)
446 end
447 else
448 table.insert(parts, { type = "token", content = found_token })
449 end
450 pos = nearest_e + 1
451 else
452 local rest = line:sub(pos)
453 if #rest > 0 then
454 table.insert(parts, { type = "plain", content = rest })
455 end
456 break
457 end
458 end
459 return parts
460 end
461
462 function KKV.output_with_multiple_colors(line, color_map, allow_comments)
463 local options = (type(color_map) == "table" and color_map.options) or {}
464 local actual_map = color_map.map or color_map
465 local code_part = line
466 local comment_part = ""
467
468 local all_targets = {}
469 local token_to_color = {}
470
471 if allow_comments and options.comment_char then
472 local c_char = options.comment_char
473 local e_char = options.escape_char or "\\"
474
475 local search_pos = 1
476 while true do
477 local s = line:find(c_char, search_pos, true)
478 if not s then break end
479
480 local is_escaped = false
481 if s > 1 and line:sub(s-1, s-1) == e_char then
482 local count = 0
483 local p = s - 1
484 while p >= 1 and line:sub(p, p) == e_char do
485 count = count + 1
486 p = p - 1
487 end
488 if count % 2 == 1 then is_escaped = true end
489 end
490
491 if not is_escaped then
492 code_part = line:sub(1, s-1)
493 comment_part = line:sub(s)
494 break
495 else
496 search_pos = s + 1
497 end
498 end
499 end
500
501 for color, targets in pairs(actual_map) do
502 for _, t in ipairs(targets) do
503 table.insert(all_targets, t)
504 token_to_color[t] = color
505 end
506 end
507
508 local parts = KKV.cut_multiple_tokens(code_part, all_targets, options)
509
510 for _, p in ipairs(parts) do
511 if p.type == "token" then
512 local t_color = token_to_color[p.content] or "black"
513 tex.sprint("\\textcolor{" .. t_color .. "}{")
514 tex.sprint(-2, p.content)
515 tex.sprint("}")
516 -- elseif p.type == "delim" then
517 -- local d_color = p.color or "black"
518 -- tex.sprint("\\textcolor{" .. d_color .. "}{")
519 -- tex.sprint(-2, p.content)
520 -- tex.sprint("}")
521
522 -- Enhancement in v2.1.2
523 elseif p.type == "delim" or p.type == "delim_plain" then
524 local d_color = p.color or "black"
525 tex.sprint("\\textcolor{" .. d_color .. "}{")
526 tex.sprint(-2, p.content)
527 tex.sprint("}")
528
529 elseif p.type == "token_delim" then
530 local td_color = p.color or "black"
531 tex.sprint("\\textcolor{" .. td_color .. "}{")
532 tex.sprint(-2, p.content)
533 tex.sprint("}")
534 else
535 tex.sprint(-2, p.content)
536 end
537 end
538
539 if comment_part ~= "" then
540 local c_color = options.comment_color or "gray"
541 tex.sprint("\\textcolor{" .. c_color .. "}{")
542 tex.sprint(-2, comment_part)
543 tex.sprint("}")
544 end
545 end
546 ----------
547
548
549 ----- preset -----
550 KKV.presets = KKV.presets or {}
551
552 function KKV.set_preset(name, map)
553 KKV.presets[name] = map
554 end
555
556 function KKV.load_preset(name)
557 if KKV.presets[name] then
558 KKV.active_map = KKV.presets[name]
559 print("KKV: Preset [" .. name .. "] applied.")
560 else
561 print("KKV: Warning - Preset [" .. name .. "] not found.")
562 end
563 end
564 ----------
565
566 _G.KKLuaVerb = KKV