• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

sile-typesetter / sile / 15507594683

07 Jun 2025 11:54AM UTC coverage: 30.951% (-30.4%) from 61.309%
15507594683

push

github

alerque
chore(tooling): Add post-checkout hook to clear makedeps on branch switch

6363 of 20558 relevant lines covered (30.95%)

3445.44 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

62.05
/core/utilities/init.lua
1
--- SILE.utilities (aliased as SU)
2
-- @module SU
3
-- @alias utilities
4

5
local bitshim = require("bitshim")
108✔
6
local luautf8 = require("lua-utf8")
108✔
7
local semver = require("rusile").semver
108✔
8

9
local utilities = {}
108✔
10

11
local epsilon = 1E-12
108✔
12

13
--- Generic
14
-- @section generic
15

16
--- Concatenate values from a table using a given separator.
17
-- Differs from `table.concat` in that all values are explicitly cast to strings, allowing debugging of tables that
18
-- include functions, other tables, data types, etc.
19
-- @tparam table array Input.
20
-- @tparam[opt=" "] string separator Separator.
21
function utilities.concat (array, separator)
108✔
22
   return table.concat(utilities.map(tostring, array), separator)
8✔
23
end
24

25
--- Execute a callback function on each value in a table.
26
-- @tparam function func Function to run on each value.
27
-- @tparam table array Input list-like table.
28
function utilities.map (func, array)
108✔
29
   local new_array = {}
16,098✔
30
   local last = #array
16,098✔
31
   for i = 1, last do
53,137✔
32
      new_array[i] = func(array[i])
70,707✔
33
   end
34
   return new_array
16,098✔
35
end
36

37
--- Require that an option table contains a specific value, otherwise raise an error.
38
-- @param options Input table of options.
39
-- @param name Name of the required option.
40
-- @param context User friendly name of the function or calling context.
41
-- @param required_type The name of a data type that the option must successfully cast to.
42
function utilities.required (options, name, context, required_type)
108✔
43
   if not options[name] then
3,648✔
44
      utilities.error(context .. " needs a " .. name .. " parameter")
×
45
   end
46
   if required_type then
3,648✔
47
      return utilities.cast(required_type, options[name])
902✔
48
   end
49
   return options[name]
2,746✔
50
end
51

52
--- Iterate over key/value pairs in sequence of the sorted keys.
53
-- Table iteration order with `pairs` is non-deterministic. This function returns an iterator that can be used in plais
54
-- of `pairs` that will iterate through the values in the order of their *sorted* keys.
55
-- @tparam table input Input table.
56
-- @usage for val in SU.sortedpairs({ b: "runs second", a: "runs first" ) do print(val) end
57
function utilities.sortedpairs (input)
108✔
58
   local keys = {}
×
59
   for k, _ in pairs(input) do
×
60
      keys[#keys + 1] = k
×
61
   end
62
   table.sort(keys, function (a, b)
×
63
      if type(a) == type(b) then
×
64
         return a < b
×
65
      elseif type(a) == "number" then
×
66
         return true
×
67
      else
68
         return false
×
69
      end
70
   end)
71
   return coroutine.wrap(function ()
×
72
      for i = 1, #keys do
×
73
         coroutine.yield(keys[i], input[keys[i]])
×
74
      end
75
   end)
76
end
77

78
--- Substitute a range of value(s) in one table with values from another.
79
-- @tparam table array Table to modify.
80
-- @tparam integer start First key to replace.
81
-- @tparam integer stop Last key to replace.
82
-- @tparam table replacement Table from which to pull key/values plairs to inject in array.
83
-- @treturn table array First input array modified with values from replacement.
84
function utilities.splice (array, start, stop, replacement)
108✔
85
   local ptr = start
×
86
   local room = stop - start + 1
×
87
   local last = replacement and #replacement or 0
×
88
   for i = 1, last do
×
89
      if room > 0 then
×
90
         room = room - 1
×
91
         array[ptr] = replacement[i]
×
92
      else
93
         table.insert(array, ptr, replacement[i])
×
94
      end
95
      ptr = ptr + 1
×
96
   end
97

98
   for _ = 1, room do
×
99
      table.remove(array, ptr)
×
100
   end
101
   return array
×
102
end
103

104
-- TODO: Unused, now deprecated?
105
function utilities.inherit (orig, spec)
108✔
106
   local new = pl.tablex.deepcopy(orig)
×
107
   if spec then
×
108
      for k, v in pairs(spec) do
×
109
         new[k] = v
×
110
      end
111
   end
112
   if new.init then
×
113
      new:init()
×
114
   end
115
   return new
×
116
end
117

118
--- Type handling
119
-- @section types
120

121
local function preferbool ()
122
   utilities.warn("Please use boolean values or strings such as 'true' and 'false' instead of 'yes' and 'no'.")
×
123
end
124

125
--- Cast user input into a boolean type.
126
-- User input content such as options typed into documents will return string values such as "true" or "false rather
127
-- than true or false types. This evaluates those strings or other inputs ane returns a consistent boolean type in
128
-- return.
129
-- @tparam nil|bool|string value Input value such as a string to evaluate for thruthyness.
130
-- @tparam[opt=false] boolean default Whether to assume inputs that don't specifically evaluate to something should be true or false.
131
-- @treturn boolean
132
function utilities.boolean (value, default)
108✔
133
   if value == false then
5,286✔
134
      return false
29✔
135
   end
136
   if value == true then
5,257✔
137
      return true
1,377✔
138
   end
139
   if value == "false" then
3,880✔
140
      return false
2✔
141
   end
142
   if value == "true" then
3,878✔
143
      return true
11✔
144
   end
145
   if value == "no" then
3,867✔
146
      preferbool()
×
147
      return false
×
148
   end
149
   if value == "yes" then
3,867✔
150
      preferbool()
×
151
      return true
×
152
   end
153
   if value == nil then
3,867✔
154
      return default == true
3,867✔
155
   end
156
   if value == "" then
×
157
      return default == true
×
158
   end
159
   SU.error("Expecting a boolean value but got '" .. value .. "'")
×
160
   return default == true
×
161
end
162

163
--- Cast user input to an expected type.
164
-- If possible, converts input from one type to another. Not all types can be cast. For example "four" can't be cast to
165
-- a number, but "4" or 4 can. Likewise "6pt" or 6 can be cast to a SILE.types.measurement, SILE.types.length, or even
166
-- a SILE.types.node.glue, but not a SILE.types.color.
167
-- @tparam string wantedType Expected type.
168
-- @return A value of the type wantedType.
169
function utilities.cast (wantedType, value)
108✔
170
   local actualType = SU.type(value)
187,475✔
171
   wantedType = string.lower(wantedType)
374,950✔
172
   if wantedType:match(actualType) then
187,475✔
173
      return value
72,320✔
174
   elseif actualType == "nil" and wantedType:match("nil") then
115,155✔
175
      return nil
×
176
   elseif wantedType:match("length") then
115,155✔
177
      return SILE.types.length(value)
19,669✔
178
   elseif wantedType:match("measurement") then
95,539✔
179
      return SILE.types.measurement(value)
2,147✔
180
   elseif wantedType:match("vglue") then
93,392✔
181
      return SILE.types.node.vglue(value)
3✔
182
   elseif wantedType:match("glue") then
93,389✔
183
      return SILE.types.node.glue(value)
39✔
184
   elseif wantedType:match("kern") then
93,350✔
185
      return SILE.types.node.kern(value)
×
186
   elseif actualType == "nil" then
93,350✔
187
      SU.error("Cannot cast nil to " .. wantedType)
×
188
   elseif wantedType:match("boolean") then
93,350✔
189
      return SU.boolean(value)
1✔
190
   elseif wantedType:match("string") then
93,349✔
191
      return tostring(value)
×
192
   elseif wantedType:match("number") then
93,349✔
193
      if type(value) == "table" and type(value.tonumber) == "function" then
93,336✔
194
         return value:tonumber()
91,327✔
195
      end
196
      local num = tonumber(value)
2,009✔
197
      if not num then
2,009✔
198
         SU.error("Cannot cast '" .. value .. "'' to " .. wantedType)
×
199
      end
200
      return num
2,009✔
201
   elseif wantedType:match("integer") then
13✔
202
      local num
203
      if type(value) == "table" and type(value.tonumber) == "function" then
13✔
204
         num = value:tonumber()
×
205
      else
206
         num = tonumber(value)
13✔
207
      end
208
      if not num then
13✔
209
         SU.error("Cannot cast '" .. value .. "'' to " .. wantedType)
×
210
      end
211
      if not wantedType:match("number") and num % 1 ~= 0 then
13✔
212
         -- Could be an error but since it wasn't checked before, let's just warn:
213
         -- Some packages might have wrongly typed settings, for instance.
214
         SU.warn("Casting an integer but got a float number " .. num)
×
215
      end
216
      return num
13✔
217
   else
218
      SU.error("Cannot cast to unrecognized type " .. wantedType)
×
219
   end
220
end
221

222
--- Return the type of an object
223
-- Like Lua's `type`, but also handles various SILE user data types.
224
-- @tparam any value Any input value. If a table is one of SILE's classes or types, report on it's internal type.
225
-- Otherwise use the output of `type`.
226
-- @treturn string
227
function utilities.type (value)
108✔
228
   if type(value) == "number" then
1,060,489✔
229
      return math.floor(value) == value and "integer" or "number"
275,645✔
230
   elseif type(value) == "table" and value.prototype then
784,844✔
231
      return value:prototype()
×
232
   elseif type(value) == "table" and value.is_a then
784,844✔
233
      return value.type
379,769✔
234
   else
235
      return type(value)
405,075✔
236
   end
237
end
238

239
--- Errors and debugging
240
-- @section errors
241

242
--- Output a debug message only if debugging for a specific category is enabled.
243
-- Importantly passing siries of strings, functions, or tables is more efficient than trying to formulate a full message
244
-- using concatenation and tostring() methods in the original code because it doesn't have to even run if the relevant
245
-- debug flag is not enabled.
246
-- @tparam text category Category flag for which this message should be output.
247
-- @tparam string|function|table ... Each argument will be returned separated by spaces, strings directly, functions by
248
-- evaluating them and assuming the return value is a string, and tables by using their internal :__tostring() methods.
249
-- @usage
250
--    > glue = SILE.types.node.glue("6em")
251
--    > SU.debug("foo", "A glue node", glue)
252
--    [foo] A glue node G<6em>
253
function utilities.debug (category, ...)
108✔
254
   if SILE.quiet then
126,995✔
255
      return
×
256
   end
257
   if utilities.debugging(category) then
253,990✔
258
      local inputs = pl.utils.pack(...)
×
259
      for i, input in ipairs(inputs) do
×
260
         if type(input) == "function" then
×
261
            local status, output = pcall(input)
×
262
            inputs[i] = status and output
×
263
               or SU.warn(("Output of %s debug function was an error: %s"):format(category, output))
×
264
         elseif type(input) ~= "string" then
×
265
            inputs[i] = tostring(input)
×
266
         end
267
      end
268
      local message = utilities.concat(inputs, " ")
×
269
      if message then
×
270
         io.stderr:write(("\n[%s] %s"):format(category, message))
×
271
      end
272
   end
273
end
274

275
--- Determine if a specific debug flag is set.
276
-- @tparam string category Name of the flag status to check, e.g. "frames".
277
-- @treturn boolean
278
function utilities.debugging (category)
108✔
279
   return SILE.debugFlags.all and category ~= "profile" or SILE.debugFlags[category]
130,817✔
280
end
281

282
--- Warn about use of a deprecated feature.
283
-- Checks the current version and decides whether to warn or error, then oatputs a message with as much useful
284
-- information as possible to make it easy for end users to update their usage.
285
-- @tparam string old The name of the deprecated interface.
286
-- @tparam string new A name of a suggested replacement interface.
287
-- @tparam string warnat The first release where the interface is considered deprecated, at which point their might be
288
-- a shim.
289
-- @tparam string errorat The first release where the interface is no longer functional even with a shim.
290
-- @tparam string extra Longer-form help to include in output separate from the expected one-liner of warning messages.
291
function utilities.deprecated (old, new, warnat, errorat, extra)
108✔
292
   warnat, errorat = semver(warnat or 0), semver(errorat or 0)
2,823✔
293
   local current = SILE.version and semver(SILE.version:match("v([0-9]*.[0-9]*.[0-9]*)")) or warnat
2,823✔
294
   -- SILE.version is defined *after* most of SILE loads. It’s available at
295
   -- runtime but not useful if we encounter deprecated code in core code. Users
296
   -- will never encounter this failure, but as a developer it’s hard to test a
297
   -- deprecation when core code refactoring is an all-or-nothing proposition.
298
   -- Hence we fake it ‘till we make it, all deprecations internally are warnings.
299
   local brackets = old:sub(1, 1) == "\\" and "" or "()"
5,646✔
300
   local _new = new and "Please use " .. (new .. brackets) .. " instead." or "Please don't use it."
2,823✔
301
   local msg = (old .. brackets)
2,823✔
302
      .. " was deprecated in SILE v"
×
303
      .. tostring(warnat)
2,823✔
304
      .. "\n\n  "
×
305
      .. _new
2,823✔
306
      .. "\n\n"
2,823✔
307
      .. (extra and (pl.stringx.indent(pl.stringx.dedent(extra), 2)) or "")
3,027✔
308
   if errorat and current >= errorat then
2,823✔
309
      SU.error(msg)
×
310
   elseif warnat and current >= warnat then
2,823✔
311
      SU.warn(msg)
1✔
312
   end
313
end
314

315
--- Dump the contents of a any Lua type.
316
-- For quick debugging, can be used on any number of any type of Lua value. Pretty-prints tables.
317
-- @tparam any ... Any number of values
318
function utilities.dump (...)
108✔
319
   local arg = { ... } -- Avoid things that Lua stuffs in arg like args to self()
1✔
320
   pl.pretty.dump(#arg == 1 and arg[1] or arg, "/dev/stderr")
2✔
321
end
322

323
local _skip_traceback_levels = 2
108✔
324

325
--- Raise an error and exit.
326
-- Outputs a warning message via `warn`, then finishes up anything it can without processing more content, then exits.
327
-- @tparam string message The error message to give.
328
-- @tparam boolean isbug Whether or not hitting this error is expected to be a code bug (as opposed to mistakes in user input).
329
function utilities.error (message, isbug)
108✔
330
   SILE.quiet = false
×
331
   _skip_traceback_levels = 3
×
332
   utilities.warn(message, isbug)
×
333
   _skip_traceback_levels = 2
×
334
   io.stderr:flush()
×
335
   if type(SILE.outputter) == "table" then
×
336
      SILE.outputter:abort()
×
337
   end
338
   SILE.scratch.caughterror = true
×
339
   error("", 2)
×
340
end
341

342
--- Output an information message.
343
-- Basically like `warn`, except to source tracing information is added.
344
-- @tparam string message
345
function utilities.msg (message)
108✔
346
   if SILE.quiet then
19✔
347
      return
×
348
   end
349
   message = pl.stringx.rstrip(message)
38✔
350
   message = "                        " .. message
19✔
351
   message = pl.stringx.dedent(message)
38✔
352
   message = pl.stringx.lstrip(message)
38✔
353
   message = pl.stringx.indent(message, 2)
38✔
354
   message = message:gsub("^.", "!")
19✔
355
   io.stderr:write("\n" .. message .. "\n")
19✔
356
end
357

358
--- Output a warning.
359
-- Outputs a warning message including identifying where in the processing SILE is at when the warning is given.
360
-- @tparam string message The error message to give.
361
-- @tparam boolean isbug Whether or not hitting this warning is expected to be a code bug (as opposed to mistakes in user input).
362
function utilities.warn (message, isbug)
108✔
363
   if SILE.quiet then
19✔
364
      return
×
365
   end
366
   utilities.msg(message)
19✔
367
   if SILE.traceback or isbug then
19✔
368
      io.stderr:write("at:\n" .. SILE.traceStack:locationTrace())
2✔
369
      if _skip_traceback_levels == 2 then
1✔
370
         io.stderr:write(
2✔
371
            debug.traceback("", _skip_traceback_levels) or "\t! debug.traceback() did not identify code location"
1✔
372
         )
373
      end
374
   else
375
      io.stderr:write("  at " .. SILE.traceStack:locationHead())
36✔
376
   end
377
   io.stderr:write("\n")
19✔
378
end
379

380
--- Math
381
-- @section math
382

383
--- Check equality of floating point values.
384
-- Comparing floating point numbers using math functions in Lua may give different and unexpected answers depending on
385
-- the Lua VM and other environmental factors. This normalizes them using our standard internal epsilon value and
386
-- compares the absolute intereger value to avoid floating point number weirdness.
387
-- @tparam float lhs
388
-- @tparam float rhs
389
-- @treturn boolean
390
function utilities.feq (lhs, rhs)
108✔
391
   lhs = SU.cast("number", lhs)
78✔
392
   rhs = SU.cast("number", rhs)
78✔
393
   local abs = math.abs
39✔
394
   return abs(lhs - rhs) <= epsilon * (abs(lhs) + abs(rhs))
39✔
395
end
396

397
--- Add up all the values in a table.
398
-- @tparam table array Input list-like table.
399
-- @treturn number Sum of all values.
400
function utilities.sum (array)
108✔
401
   local total = 0
4,703✔
402
   local last = #array
4,703✔
403
   for i = 1, last do
9,058✔
404
      total = total + array[i]
4,355✔
405
   end
406
   return total
4,703✔
407
end
408

409
--- Return maximum value of inputs.
410
-- `math.max`, but works on SILE types such as SILE.types.measurement.
411
-- Lua <= 5.2 can't handle math operators on objects.
412
function utilities.max (...)
108✔
413
   local input = pl.utils.pack(...)
10,413✔
414
   local max = table.remove(input, 1)
10,413✔
415
   for _, val in ipairs(input) do
36,369✔
416
      if val > max then
25,956✔
417
         max = val
8,692✔
418
      end
419
   end
420
   return max
10,413✔
421
end
422

423
--- Return minimum value of inputs.
424
-- `math.min`, but works on SILE types such as SILE.types.measurement.
425
-- Lua <= 5.2 can't handle math operators on objects.
426
function utilities.min (...)
108✔
427
   local input = pl.utils.pack(...)
5✔
428
   local min = input[1]
5✔
429
   for _, val in ipairs(input) do
15✔
430
      if val < min then
10✔
431
         min = val
×
432
      end
433
   end
434
   return min
5✔
435
end
436

437
--- Round and normalize a number for debugging.
438
-- LuaJIT 2.1 betas (and inheritors such as OpenResty and Moonjit) are biased
439
-- towards rounding 0.5 up to 1, all other Lua interpreters are biased
440
-- towards rounding such floating point numbers down.  This hack shaves off
441
-- just enough to fix the bias so our test suite works across interpreters.
442
-- Note that even a true rounding function here will fail because the bias is
443
-- inherent to the floating point type. Also note we are erroring in favor of
444
-- the *less* common option because the LuaJIT VMS are hopelessly broken
445
-- whereas normal LUA VMs can be cooerced.
446
-- @tparam number input Input value.
447
-- @treturn string Four-digit precision foating point.
448
function utilities.debug_round (input)
108✔
449
   if input > 0 then
×
450
      input = input + 0.00000000000001
×
451
   end
452
   if input < 0 then
×
453
      input = input - 0.00000000000001
×
454
   end
455
   return string.format("%.4f", input)
×
456
end
457

458
--- Remove empty spaces from list-like tables
459
-- Iterating list-like tables is hard if some values have been removed. This converts { 1 = "a", 3 = "b" } into
460
-- { 1 = "a", 2 = "b" } which can be iterated using `ipairs` without stopping after 1.
461
-- @tparam table items List-like table potentially with holes.
462
-- @treturn table List like table without holes.
463
function utilities.compress (items)
108✔
464
   local rv = {}
438✔
465
   local max = math.max(pl.utils.unpack(pl.tablex.keys(items)))
1,314✔
466
   for i = 1, max do
8,966✔
467
      if items[i] then
8,528✔
468
         rv[#rv + 1] = items[i]
8,528✔
469
      end
470
   end
471
   return rv
438✔
472
end
473

474
--- Reverse the order of a list-like table.
475
-- @tparam table tbl Input list-like table.
476
function utilities.flip_in_place (tbl)
108✔
477
   local tmp, j
478
   for i = 1, math.floor(#tbl / 2) do
808✔
479
      tmp = tbl[i]
520✔
480
      j = #tbl - i + 1
520✔
481
      tbl[i] = tbl[j]
520✔
482
      tbl[j] = tmp
520✔
483
   end
484
end
485

486
-- TODO: Before documenting, consider whether this should be private to the one existing usage.
487
function utilities.allCombinations (options)
108✔
488
   local count = 1
×
489
   for i = 1, #options do
×
490
      count = count * options[i]
×
491
   end
492
   return coroutine.wrap(function ()
×
493
      for i = 0, count - 1 do
×
494
         local this = i
×
495
         local rv = {}
×
496
         for j = 1, #options do
×
497
            local base = options[j]
×
498
            rv[#rv + 1] = this % base + 1
×
499
            this = (this - this % base) / base
×
500
         end
501
         coroutine.yield(rv)
×
502
      end
503
   end)
504
end
505

506
function utilities.rateBadness (inf_bad, shortfall, spring)
108✔
507
   if spring == 0 then
7,778✔
508
      return inf_bad
245✔
509
   end
510
   local bad = math.floor(100 * math.abs(shortfall / spring) ^ 3)
7,533✔
511
   return math.min(inf_bad, bad)
7,533✔
512
end
513

514
function utilities.rationWidth (target, width, ratio)
108✔
515
   if ratio < 0 and width.shrink:tonumber() > 0 then
7,853✔
516
      target:___add(width.shrink:tonumber() * ratio)
1,449✔
517
   elseif ratio > 0 and width.stretch:tonumber() > 0 then
11,367✔
518
      target:___add(width.stretch:tonumber() * ratio)
2,952✔
519
   end
520
   return target
6,573✔
521
end
522

523
--- Text handling
524
-- @section text
525

526
--- Iterate over a string split into tokens via a pattern.
527
-- @tparam string string Input string.
528
-- @tparam string pattern Pattern on which to split the input.
529
-- @treturn function An iterator function
530
-- @usage for str in SU.gtoke("foo-bar-baz", "-") do print(str) end
531
function utilities.gtoke (string, pattern)
108✔
532
   string = string and tostring(string) or ""
736✔
533
   pattern = pattern and tostring(pattern) or "%s+"
736✔
534
   local length = #string
736✔
535
   return coroutine.wrap(function ()
736✔
536
      local index = 1
736✔
537
      repeat
538
         local first, last = string:find(pattern, index)
982✔
539
         if last then
982✔
540
            if index < first then
378✔
541
               coroutine.yield({ string = string:sub(index, first - 1) })
468✔
542
            end
543
            coroutine.yield({ separator = string:sub(first, last) })
756✔
544
            index = last + 1
378✔
545
         else
546
            if index <= length then
604✔
547
               coroutine.yield({ string = string:sub(index) })
1,208✔
548
            end
549
            break
604✔
550
         end
551
      until index > length
378✔
552
   end)
553
end
554

555
--- Convert a Unicode character to its corresponding codepoint.
556
-- @tparam string uchar A single inicode character.
557
-- @return number The Unicode code point where uchar is encoded.
558
function utilities.codepoint (uchar)
108✔
559
   local seq = 0
72,017✔
560
   local val = -1
72,017✔
561
   for i = 1, #uchar do
149,347✔
562
      local c = string.byte(uchar, i)
78,638✔
563
      if seq == 0 then
78,638✔
564
         if val > -1 then
72,235✔
565
            return val
1,308✔
566
         end
567
         seq = c < 0x80 and 1
70,927✔
568
            or c < 0xE0 and 2
70,927✔
569
            or c < 0xF0 and 3
6,223✔
570
            or c < 0xF8 and 4 --c < 0xFC and 5 or c < 0xFE and 6 or
180✔
571
            or error("invalid UTF-8 character sequence")
×
572
         val = bitshim.band(c, 2 ^ (8 - seq) - 1)
70,927✔
573
      else
574
         val = bitshim.bor(bitshim.lshift(val, 6), bitshim.band(c, 0x3F))
6,403✔
575
      end
576
      seq = seq - 1
77,330✔
577
   end
578
   return val
70,709✔
579
end
580

581
--- Covert a code point to a Unicode character.
582
-- @tparam number|string codepoint Input code point value, either as a number or a string representing the decimal value "U+NNNN" or hex value "0xFFFF".
583
-- @treturn string The character replestened by a codepoint descriptions.
584
function utilities.utf8charfromcodepoint (codepoint)
108✔
585
   local val = codepoint
355✔
586
   local cp = val
355✔
587
   local hex = (cp:match("[Uu]%+(%x+)") or cp:match("0[xX](%x+)"))
355✔
588
   if hex then
355✔
589
      cp = tonumber("0x" .. hex)
1✔
590
   elseif tonumber(cp) then
354✔
591
      cp = tonumber(cp)
×
592
   end
593

594
   if type(cp) == "number" then
355✔
595
      val = luautf8.char(cp)
1✔
596
   end
597
   return val
355✔
598
end
599

600
--- Convert a UTF-16 encoded string to a series of code points.
601
-- Like `luautf8.codes`, but for UTF-16 strings.
602
-- @tparam string ustr Input string.
603
-- @tparam string endian Either "le" or "be" depending on the encoding endedness.
604
-- @treturn string Serious of hex encoded code points.
605
function utilities.utf16codes (ustr, endian)
108✔
606
   local pos = 1
17,626✔
607
   return function ()
608
      if pos > #ustr then
548,183✔
609
         return nil
17,626✔
610
      else
611
         local c1, c2, c3, c4, wchar, lowchar
612
         c1 = string.byte(ustr, pos, pos + 1)
530,557✔
613
         pos = pos + 1
530,557✔
614
         c2 = string.byte(ustr, pos, pos + 1)
530,557✔
615
         pos = pos + 1
530,557✔
616
         if endian == "be" then
530,557✔
617
            wchar = c1 * 256 + c2
530,557✔
618
         else
619
            wchar = c2 * 256 + c1
×
620
         end
621
         if not (wchar >= 0xD800 and wchar <= 0xDBFF) then
530,557✔
622
            return wchar
530,557✔
623
         end
624
         c3 = string.byte(ustr, pos, pos + 1)
×
625
         pos = pos + 1
×
626
         c4 = string.byte(ustr, pos, pos + 1)
×
627
         pos = pos + 1
×
628
         if endian == "be" then
×
629
            lowchar = c3 * 256 + c4
×
630
         else
631
            lowchar = c4 * 256 + c3
×
632
         end
633
         return 0x10000 + bitshim.lshift(bitshim.band(wchar, 0x03FF), 10) + bitshim.band(lowchar, 0x03FF)
×
634
      end
635
   end
636
end
637

638
--- Split a UTF-8 string into characters.
639
-- Lua's `string.split` will only explode a string by bytes. For text processing purposes it is usually more desirable
640
-- to split it into 1, 2, 3, or 4 byte groups matching the UTF-8 encoding.
641
-- @tparam string str Input UTF-8 encoded string.
642
-- @treturn table A list-like table of UTF8 strings each representing a Unicode char from the input string.
643
function utilities.splitUtf8 (str)
108✔
644
   local rv = {}
714,988✔
645
   for _, cp in luautf8.next, str do
4,425,972✔
646
      table.insert(rv, luautf8.char(cp))
3,710,984✔
647
   end
648
   return rv
714,988✔
649
end
650

651
--- The last Unicode character in a UTF-8 encoded string.
652
-- Uses `SU.splitUtf8` to break an string into segments represtenting encoded characters, returns the last one. May be
653
-- more than one byte.
654
-- @tparam string str Input string.
655
-- @treturn string A single Unicode character.
656
function utilities.lastChar (str)
108✔
657
   local chars = utilities.splitUtf8(str)
×
658
   return chars[#chars]
×
659
end
660

661
--- The first Unicode character in a UTF-8 encoded string.
662
-- Uses `SU.splitUtf8` to break an string into segments represtenting encoded characters, returns the first one. May be
663
-- more than one byte.
664
-- @tparam string str Input string.
665
-- @treturn string A single Unicode character.
666
function utilities.firstChar (str)
108✔
667
   local chars = utilities.splitUtf8(str)
×
668
   return chars[1]
×
669
end
670

671
local byte, floor, reverse = string.byte, math.floor, string.reverse
108✔
672

673
--- The Unicode character in a UTF-8 encoded string at a specific position
674
-- Uses `SU.splitUtf8` to break an string into segments represtenting encoded characters, returns the Nth one. May be
675
-- more than one byte.
676
-- @tparam string str Input string.
677
-- @tparam number index Index of character to return.
678
-- @treturn string A single Unicode character.
679
function utilities.utf8charat (str, index)
108✔
680
   return str:sub(index):match("([%z\1-\127\194-\244][\128-\191]*)")
×
681
end
682

683
local utf16bom = function (endianness)
684
   return endianness == "be" and "\254\255" or endianness == "le" and "\255\254" or SU.error("Unrecognized endianness")
17,626✔
685
end
686

687
--- Encode a string to a hexadecimal replesentation.
688
-- @tparam string str Input UTF-8 string
689
-- @treturn string Hexadecimal replesentation of str.
690
function utilities.hexencoded (str)
108✔
691
   local ustr = ""
×
692
   for i = 1, #str do
×
693
      ustr = ustr .. string.format("%02x", byte(str, i, i + 1))
×
694
   end
695
   return ustr
×
696
end
697

698
--- Decode a hexadecimal replesentation into a string.
699
-- @tparam string str Input hexadecimal encoded string.
700
-- @treturn string UTF-8 string.
701
function utilities.hexdecoded (str)
108✔
702
   if #str % 2 == 1 then
×
703
      SU.error("Cannot decode hex string with odd len")
×
704
   end
705
   local ustr = ""
×
706
   for i = 1, #str, 2 do
×
707
      ustr = ustr .. string.char(tonumber(string.sub(str, i, i + 1), 16))
×
708
   end
709
   return ustr
×
710
end
711

712
local uchr_to_surrogate_pair = function (uchr, endianness)
713
   local hi, lo = floor((uchr - 0x10000) / 0x400) + 0xd800, (uchr - 0x10000) % 0x400 + 0xdc00
×
714
   local s_hi, s_lo =
715
      string.char(floor(hi / 256)) .. string.char(hi % 256), string.char(floor(lo / 256)) .. string.char(lo % 256)
×
716
   return endianness == "le" and (reverse(s_hi) .. reverse(s_lo)) or s_hi .. s_lo
×
717
end
718

719
local uchr_to_utf16_double_byte = function (uchr, endianness)
720
   local ustr = string.char(floor(uchr / 256)) .. string.char(uchr % 256)
×
721
   return endianness == "le" and reverse(ustr) or ustr
×
722
end
723

724
local utf8_to_utf16 = function (str, endianness)
725
   local ustr = utf16bom(endianness)
×
726
   for _, uchr in luautf8.codes(str) do
×
727
      ustr = ustr
×
728
         .. (uchr < 0x10000 and uchr_to_utf16_double_byte(uchr, endianness) or uchr_to_surrogate_pair(uchr, endianness))
×
729
   end
730
   return ustr
×
731
end
732

733
--- Convert a UTF-8 string to big-endian UTF-16.
734
-- @tparam string str UTF-8 encoded string.
735
-- @treturn string Big-endian UTF-16 encoded string.
736
function utilities.utf8_to_utf16be (str)
108✔
737
   return utf8_to_utf16(str, "be")
×
738
end
739

740
--- Convert a UTF-8 string to little-endian UTF-16.
741
-- @tparam string str UTF-8 encoded string.
742
-- @treturn string Little-endian UTF-16 encoded string.
743
function utilities.utf8_to_utf16le (str)
108✔
744
   return utf8_to_utf16(str, "le")
×
745
end
746

747
--- Convert a UTF-8 string to big-endian UTF-16, then encode in hex.
748
-- @tparam string str UTF-8 encoded string.
749
-- @treturn string Hexadecimal representation of a big-endian UTF-16 encoded string.
750
function utilities.utf8_to_utf16be_hexencoded (str)
108✔
751
   return utilities.hexencoded(utilities.utf8_to_utf16be(str))
×
752
end
753

754
--- Convert a UTF-8 string to little-endian UTF-16, then encode in hex.
755
-- @tparam string str UTF-8 encoded string.
756
-- @treturn string Hexadecimal representation of a little-endian UTF-16 encoded string.
757
function utilities.utf8_to_utf16le_hexencoded (str)
108✔
758
   return utilities.hexencoded(utilities.utf8_to_utf16le(str))
×
759
end
760

761
local utf16_to_utf8 = function (str, endianness)
762
   local bom = utf16bom(endianness)
17,626✔
763

764
   if str:find(bom) == 1 then
17,626✔
765
      str = string.sub(str, 3, #str)
×
766
   end
767
   local ustr = ""
17,626✔
768
   for uchr in utilities.utf16codes(str, endianness) do
1,113,992✔
769
      ustr = ustr .. luautf8.char(uchr)
530,557✔
770
   end
771
   return ustr
17,626✔
772
end
773

774
--- Convert a big-endian UTF-16 string to UTF-8.
775
-- @tparam string str Big-endian UTF-16 encoded string.
776
-- @treturn string UTF-8 encoded string.
777
function utilities.utf16be_to_utf8 (str)
108✔
778
   return utf16_to_utf8(str, "be")
17,626✔
779
end
780

781
--- Convert a little-endian UTF-16 string to UTF-8.
782
-- @tparam string str Little-endian UTF-16 encoded string.
783
-- @treturn string UTF-8 encoded string.
784
function utilities.utf16le_to_utf8 (str)
108✔
785
   return utf16_to_utf8(str, "le")
×
786
end
787

788
function utilities.breadcrumbs ()
108✔
789
   local breadcrumbs = {}
104✔
790

791
   setmetatable(breadcrumbs, {
208✔
792
      __index = function (_, key)
793
         local frame = SILE.traceStack[key]
×
794
         return frame and frame.command or nil
×
795
      end,
796
      __len = function (_)
797
         return #SILE.traceStack
×
798
      end,
799
      __tostring = function (self)
800
         return "B»" .. table.concat(self, "»")
×
801
      end,
802
   })
803

804
   function breadcrumbs:dump ()
104✔
805
      SU.dump(self)
×
806
   end
807

808
   function breadcrumbs:parent (count)
104✔
809
      -- Note LuaJIT does not support __len, so this has to work even when that metamethod doesn't fire...
810
      return self[#SILE.traceStack - (count or 1)]
×
811
   end
812

813
   function breadcrumbs:contains (needle, startdepth)
104✔
814
      startdepth = startdepth or 0
×
815
      for i = startdepth, #SILE.traceStack - 1 do
×
816
         local frame = SILE.traceStack[#SILE.traceStack - i]
×
817
         if frame.command == needle then
×
818
            return true, #self - i
×
819
         end
820
      end
821
      return false, -1
×
822
   end
823

824
   return breadcrumbs
104✔
825
end
826

827
utilities.formatNumber = require("core.utilities.numbers")
108✔
828

829
utilities.collatedSort = require("core.utilities.sorting")
108✔
830

831
utilities.ast = require("core.utilities.ast")
108✔
832
utilities.debugAST = utilities.ast.debug
108✔
833

834
function utilities.subContent (content)
108✔
835
   SU.deprecated(
×
836
      "SU.subContent",
837
      "SU.ast.subContent",
838
      "0.15.0",
839
      "0.17.0",
840
      [[Note that the new implementation no longer introduces an id="stuff" key.]]
841
   )
842
   return utilities.ast.subContent(content)
×
843
end
844

845
function utilities.hasContent (content)
108✔
846
   SU.deprecated("SU.hasContent", "SU.ast.hasContent", "0.15.0", "0.17.0")
×
847
   return SU.ast.hasContent(content)
×
848
end
849

850
function utilities.contentToString (content)
108✔
851
   SU.deprecated("SU.contentToString", "SU.ast.contentToString", "0.15.0", "0.17.0")
×
852
   return SU.ast.contentToString(content)
×
853
end
854

855
function utilities.walkContent (content, action)
108✔
856
   SU.deprecated("SU.walkContent", "SU.ast.walkContent", "0.15.0", "0.17.0")
×
857
   SU.ast.walkContent(content, action)
×
858
end
859

860
function utilities.stripContentPos (content)
108✔
861
   SU.deprecated("SU.stripContentPos", "SU.ast.stripContentPos", "0.15.0", "0.17.0")
×
862
   return SU.ast.stripContentPos(content)
×
863
end
864

865
return utilities
108✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc