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

sile-typesetter / sile / 10881107806

16 Sep 2024 09:29AM UTC coverage: 61.663% (-7.2%) from 68.912%
10881107806

push

github

web-flow
chore(deps): Bump DeterminateSystems/nix-installer-action from 13 to 14 (#2110)

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

10751 of 17435 relevant lines covered (61.66%)

2338.25 hits per line

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

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

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

9
local utilities = {}
83✔
10

11
local epsilon = 1E-12
83✔
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)
83✔
22
   return table.concat(utilities.map(tostring, array), separator)
×
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)
83✔
29
   local new_array = {}
13,068✔
30
   local last = #array
13,068✔
31
   for i = 1, last do
43,461✔
32
      new_array[i] = func(array[i])
58,080✔
33
   end
34
   return new_array
13,068✔
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)
83✔
43
   if not options[name] then
3,958✔
44
      utilities.error(context .. " needs a " .. name .. " parameter")
×
45
   end
46
   if required_type then
3,958✔
47
      return utilities.cast(required_type, options[name])
781✔
48
   end
49
   return options[name]
3,177✔
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)
83✔
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)
83✔
85
   local ptr = start
97✔
86
   local room = stop - start + 1
97✔
87
   local last = replacement and #replacement or 0
97✔
88
   for i = 1, last do
887✔
89
      if room > 0 then
790✔
90
         room = room - 1
88✔
91
         array[ptr] = replacement[i]
88✔
92
      else
93
         table.insert(array, ptr, replacement[i])
702✔
94
      end
95
      ptr = ptr + 1
790✔
96
   end
97

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

104
-- TODO: Unused, now deprecated?
105
function utilities.inherit (orig, spec)
83✔
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)
83✔
133
   if value == false then
3,358✔
134
      return false
21✔
135
   end
136
   if value == true then
3,337✔
137
      return true
1,335✔
138
   end
139
   if value == "false" then
2,002✔
140
      return false
2✔
141
   end
142
   if value == "true" then
2,000✔
143
      return true
5✔
144
   end
145
   if value == "no" then
1,995✔
146
      preferbool()
×
147
      return false
×
148
   end
149
   if value == "yes" then
1,995✔
150
      preferbool()
×
151
      return true
×
152
   end
153
   if value == nil then
1,995✔
154
      return default == true
1,995✔
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)
83✔
170
   local actualType = SU.type(value)
150,479✔
171
   wantedType = string.lower(wantedType)
300,958✔
172
   if wantedType:match(actualType) then
150,479✔
173
      return value
56,855✔
174
   elseif actualType == "nil" and wantedType:match("nil") then
93,624✔
175
      return nil
×
176
   elseif wantedType:match("length") then
93,624✔
177
      return SILE.types.length(value)
15,698✔
178
   elseif wantedType:match("measurement") then
78,008✔
179
      return SILE.types.measurement(value)
2,050✔
180
   elseif wantedType:match("vglue") then
75,958✔
181
      return SILE.types.node.vglue(value)
2✔
182
   elseif wantedType:match("glue") then
75,956✔
183
      return SILE.types.node.glue(value)
37✔
184
   elseif wantedType:match("kern") then
75,919✔
185
      return SILE.types.node.kern(value)
×
186
   elseif actualType == "nil" then
75,919✔
187
      SU.error("Cannot cast nil to " .. wantedType)
×
188
   elseif wantedType:match("boolean") then
75,919✔
189
      return SU.boolean(value)
1✔
190
   elseif wantedType:match("string") then
75,918✔
191
      return tostring(value)
×
192
   elseif wantedType:match("number") then
75,918✔
193
      if type(value) == "table" and type(value.tonumber) == "function" then
75,905✔
194
         return value:tonumber()
73,785✔
195
      end
196
      local num = tonumber(value)
2,120✔
197
      if not num then
2,120✔
198
         SU.error("Cannot cast '" .. value .. "'' to " .. wantedType)
×
199
      end
200
      return num
2,120✔
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)
83✔
228
   if type(value) == "number" then
824,103✔
229
      return math.floor(value) == value and "integer" or "number"
211,640✔
230
   elseif type(value) == "table" and value.prototype then
612,463✔
231
      return value:prototype()
×
232
   elseif type(value) == "table" and value.is_a then
612,463✔
233
      return value.type
298,270✔
234
   else
235
      return type(value)
314,193✔
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, ...)
83✔
254
   if SILE.quiet then
55,483✔
255
      return
×
256
   end
257
   if utilities.debugging(category) then
110,966✔
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)
83✔
279
   return SILE.debugFlags.all and category ~= "profile" or SILE.debugFlags[category]
57,409✔
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)
83✔
292
   warnat, errorat = semver(warnat or 0), semver(errorat or 0)
6✔
293
   local current = SILE.version and semver(SILE.version:match("v([0-9]*.[0-9]*.[0-9]*)")) or warnat
4✔
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 "()"
4✔
300
   local _new = new and "Please use " .. (new .. brackets) .. " instead." or "Please don't use it."
2✔
301
   local msg = (old .. brackets)
2✔
302
      .. " was deprecated in SILE v"
×
303
      .. tostring(warnat)
2✔
304
      .. ". "
×
305
      .. _new
2✔
306
      .. (extra and ("\n\n" .. extra .. "\n") or "")
2✔
307
   if errorat and current >= errorat then
2✔
308
      SU.error(msg)
×
309
   elseif warnat and current >= warnat then
2✔
310
      SU.warn(msg)
2✔
311
   end
312
end
313

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

322
local _skip_traceback_levels = 2
83✔
323

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

339
--- Output an information message.
340
-- Basically like `warn`, except to source tracing information is added.
341
-- @tparam string message
342
function utilities.msg (message)
83✔
343
   if SILE.quiet then
23✔
344
      return
×
345
   end
346
   io.stderr:write("\n! " .. message .. "\n")
23✔
347
end
348

349
--- Output a warning.
350
-- Outputs a warning message including identifying where in the processing SILE is at when the warning is given.
351
-- @tparam string message The error message to give.
352
-- @tparam boolean isbug Whether or not hitting this warning is expected to be a code bug (as opposed to mistakes in user input).
353
function utilities.warn (message, isbug)
83✔
354
   if SILE.quiet then
23✔
355
      return
×
356
   end
357
   utilities.msg(message)
23✔
358
   if SILE.traceback or isbug then
23✔
359
      io.stderr:write(" at:\n" .. SILE.traceStack:locationTrace())
2✔
360
      if _skip_traceback_levels == 2 then
1✔
361
         io.stderr:write(
2✔
362
            debug.traceback("", _skip_traceback_levels) or "\t! debug.traceback() did not identify code location"
1✔
363
         )
364
      end
365
   else
366
      io.stderr:write(" at " .. SILE.traceStack:locationHead())
44✔
367
   end
368
   io.stderr:write("\n")
23✔
369
end
370

371
--- Math
372
-- @section math
373

374
--- Check equality of floating point values.
375
-- Comparing floating point numbers using math functions in Lua may give different and unexpected answers depending on
376
-- the Lua VM and other environmental factors. This normalizes them using our standard internal epsilon value and
377
-- compares the absolute intereger value to avoid floating point number weirdness.
378
-- @tparam float lhs
379
-- @tparam float rhs
380
-- @treturn boolean
381
function utilities.feq (lhs, rhs)
83✔
382
   lhs = SU.cast("number", lhs)
72✔
383
   rhs = SU.cast("number", rhs)
72✔
384
   local abs = math.abs
36✔
385
   return abs(lhs - rhs) <= epsilon * (abs(lhs) + abs(rhs))
36✔
386
end
387

388
--- Add up all the values in a table.
389
-- @tparam table array Input list-like table.
390
-- @treturn number Sum of all values.
391
function utilities.sum (array)
83✔
392
   local total = 0
3,815✔
393
   local last = #array
3,815✔
394
   for i = 1, last do
7,308✔
395
      total = total + array[i]
3,493✔
396
   end
397
   return total
3,815✔
398
end
399

400
--- Return maximum value of inputs.
401
-- `math.max`, but works on SILE types such as SILE.types.measurement.
402
-- Lua <= 5.2 can't handle math operators on objects.
403
function utilities.max (...)
83✔
404
   local input = pl.utils.pack(...)
8,483✔
405
   local max = table.remove(input, 1)
8,483✔
406
   for _, val in ipairs(input) do
29,977✔
407
      if val > max then
21,494✔
408
         max = val
7,194✔
409
      end
410
   end
411
   return max
8,483✔
412
end
413

414
--- Return minimum value of inputs.
415
-- `math.min`, but works on SILE types such as SILE.types.measurement.
416
-- Lua <= 5.2 can't handle math operators on objects.
417
function utilities.min (...)
83✔
418
   local input = pl.utils.pack(...)
6✔
419
   local min = input[1]
6✔
420
   for _, val in ipairs(input) do
18✔
421
      if val < min then
12✔
422
         min = val
×
423
      end
424
   end
425
   return min
6✔
426
end
427

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

449
--- Remove empty spaces from list-like tables
450
-- Iterating list-like tables is hard if some values have been removed. This converts { 1 = "a", 3 = "b" } into
451
-- { 1 = "a", 2 = "b" } which can be iterated using `ipairs` without stopping after 1.
452
-- @tparam table items List-like table potentially with holes.
453
-- @treturn table List like table without holes.
454
function utilities.compress (items)
83✔
455
   local rv = {}
370✔
456
   local max = math.max(pl.utils.unpack(pl.tablex.keys(items)))
1,110✔
457
   for i = 1, max do
7,530✔
458
      if items[i] then
7,160✔
459
         rv[#rv + 1] = items[i]
7,160✔
460
      end
461
   end
462
   return rv
370✔
463
end
464

465
--- Reverse the order of a list-like table.
466
-- @tparam table tbl Input list-like table.
467
function utilities.flip_in_place (tbl)
83✔
468
   local tmp, j
469
   for i = 1, math.floor(#tbl / 2) do
808✔
470
      tmp = tbl[i]
520✔
471
      j = #tbl - i + 1
520✔
472
      tbl[i] = tbl[j]
520✔
473
      tbl[j] = tmp
520✔
474
   end
475
end
476

477
-- TODO: Before documenting, consider whether this should be private to the one existing usage.
478
function utilities.allCombinations (options)
83✔
479
   local count = 1
×
480
   for i = 1, #options do
×
481
      count = count * options[i]
×
482
   end
483
   return coroutine.wrap(function ()
×
484
      for i = 0, count - 1 do
×
485
         local this = i
×
486
         local rv = {}
×
487
         for j = 1, #options do
×
488
            local base = options[j]
×
489
            rv[#rv + 1] = this % base + 1
×
490
            this = (this - this % base) / base
×
491
         end
492
         coroutine.yield(rv)
×
493
      end
494
   end)
495
end
496

497
function utilities.rateBadness (inf_bad, shortfall, spring)
83✔
498
   if spring == 0 then
7,435✔
499
      return inf_bad
210✔
500
   end
501
   local bad = math.floor(100 * math.abs(shortfall / spring) ^ 3)
7,225✔
502
   return math.min(inf_bad, bad)
7,225✔
503
end
504

505
function utilities.rationWidth (target, width, ratio)
83✔
506
   if ratio < 0 and width.shrink:tonumber() > 0 then
6,881✔
507
      target:___add(width.shrink:tonumber() * ratio)
1,269✔
508
   elseif ratio > 0 and width.stretch:tonumber() > 0 then
9,877✔
509
      target:___add(width.stretch:tonumber() * ratio)
2,588✔
510
   end
511
   return target
5,727✔
512
end
513

514
--- Text handling
515
-- @section text
516

517
--- Iterate over a string split into tokens via a pattern.
518
-- @tparam string string Input string.
519
-- @tparam string pattern Pattern on which to split the input.
520
-- @treturn function An iterator function
521
-- @usage for str in SU.gtoke("foo-bar-baz", "-") do print(str) end
522
function utilities.gtoke (string, pattern)
83✔
523
   string = string and tostring(string) or ""
638✔
524
   pattern = pattern and tostring(pattern) or "%s+"
638✔
525
   local length = #string
638✔
526
   return coroutine.wrap(function ()
638✔
527
      local index = 1
638✔
528
      repeat
529
         local first, last = string:find(pattern, index)
829✔
530
         if last then
829✔
531
            if index < first then
282✔
532
               coroutine.yield({ string = string:sub(index, first - 1) })
370✔
533
            end
534
            coroutine.yield({ separator = string:sub(first, last) })
564✔
535
            index = last + 1
282✔
536
         else
537
            if index <= length then
547✔
538
               coroutine.yield({ string = string:sub(index) })
1,094✔
539
            end
540
            break
547✔
541
         end
542
      until index > length
282✔
543
   end)
544
end
545

546
--- Convert a Unicode character to its corresponding codepoint.
547
-- @tparam string uchar A single inicode character.
548
-- @return number The Unicode code point where uchar is encoded.
549
function utilities.codepoint (uchar)
83✔
550
   local seq = 0
57,985✔
551
   local val = -1
57,985✔
552
   for i = 1, #uchar do
117,749✔
553
      local c = string.byte(uchar, i)
61,083✔
554
      if seq == 0 then
61,083✔
555
         if val > -1 then
58,214✔
556
            return val
1,319✔
557
         end
558
         seq = c < 0x80 and 1
56,895✔
559
            or c < 0xE0 and 2
56,895✔
560
            or c < 0xF0 and 3
2,698✔
561
            or c < 0xF8 and 4 --c < 0xFC and 5 or c < 0xFE and 6 or
171✔
562
            or error("invalid UTF-8 character sequence")
×
563
         val = bitshim.band(c, 2 ^ (8 - seq) - 1)
56,895✔
564
      else
565
         val = bitshim.bor(bitshim.lshift(val, 6), bitshim.band(c, 0x3F))
2,869✔
566
      end
567
      seq = seq - 1
59,764✔
568
   end
569
   return val
56,666✔
570
end
571

572
--- Covert a code point to a Unicode character.
573
-- @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".
574
-- @treturn string The character replestened by a codepoint descriptions.
575
function utilities.utf8charfromcodepoint (codepoint)
83✔
576
   local val = codepoint
355✔
577
   local cp = val
355✔
578
   local hex = (cp:match("[Uu]%+(%x+)") or cp:match("0[xX](%x+)"))
355✔
579
   if hex then
355✔
580
      cp = tonumber("0x" .. hex)
1✔
581
   elseif tonumber(cp) then
354✔
582
      cp = tonumber(cp)
×
583
   end
584

585
   if type(cp) == "number" then
355✔
586
      val = luautf8.char(cp)
1✔
587
   end
588
   return val
355✔
589
end
590

591
--- Convert a UTF-16 encoded string to a series of code points.
592
-- Like `luautf8.codes`, but for UTF-16 strings.
593
-- @tparam string ustr Input string.
594
-- @tparam string endian Either "le" or "be" depending on the encoding endedness.
595
-- @treturn string Serious of hex encoded code points.
596
function utilities.utf16codes (ustr, endian)
83✔
597
   local pos = 1
13,706✔
598
   return function ()
599
      if pos > #ustr then
419,348✔
600
         return nil
13,706✔
601
      else
602
         local c1, c2, c3, c4, wchar, lowchar
603
         c1 = string.byte(ustr, pos, pos + 1)
405,642✔
604
         pos = pos + 1
405,642✔
605
         c2 = string.byte(ustr, pos, pos + 1)
405,642✔
606
         pos = pos + 1
405,642✔
607
         if endian == "be" then
405,642✔
608
            wchar = c1 * 256 + c2
405,642✔
609
         else
610
            wchar = c2 * 256 + c1
×
611
         end
612
         if not (wchar >= 0xD800 and wchar <= 0xDBFF) then
405,642✔
613
            return wchar
405,642✔
614
         end
615
         c3 = string.byte(ustr, pos, pos + 1)
×
616
         pos = pos + 1
×
617
         c4 = string.byte(ustr, pos, pos + 1)
×
618
         pos = pos + 1
×
619
         if endian == "be" then
×
620
            lowchar = c3 * 256 + c4
×
621
         else
622
            lowchar = c4 * 256 + c3
×
623
         end
624
         return 0x10000 + bitshim.lshift(bitshim.band(wchar, 0x03FF), 10) + bitshim.band(lowchar, 0x03FF)
×
625
      end
626
   end
627
end
628

629
--- Split a UTF-8 string into characters.
630
-- Lua's `string.split` will only explode a string by bytes. For text processing purposes it is usually more desirable
631
-- to split it into 1, 2, 3, or 4 byte groups matching the UTF-8 encoding.
632
-- @tparam string str Input UTF-8 encoded string.
633
-- @treturn table A list-like table of UTF8 strings each representing a Unicode char from the input string.
634
function utilities.splitUtf8 (str)
83✔
635
   local rv = {}
29,633✔
636
   for _, cp in luautf8.next, str do
192,315✔
637
      table.insert(rv, luautf8.char(cp))
162,682✔
638
   end
639
   return rv
29,633✔
640
end
641

642
--- The last Unicode character in a UTF-8 encoded string.
643
-- Uses `SU.splitUtf8` to break an string into segments represtenting encoded characters, returns the last one. May be
644
-- more than one byte.
645
-- @tparam string str Input string.
646
-- @treturn string A single Unicode character.
647
function utilities.lastChar (str)
83✔
648
   local chars = utilities.splitUtf8(str)
×
649
   return chars[#chars]
×
650
end
651

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

662
local byte, floor, reverse = string.byte, math.floor, string.reverse
83✔
663

664
--- The Unicode character in a UTF-8 encoded string at a specific position
665
-- Uses `SU.splitUtf8` to break an string into segments represtenting encoded characters, returns the Nth one. May be
666
-- more than one byte.
667
-- @tparam string str Input string.
668
-- @tparam number index Index of character to return.
669
-- @treturn string A single Unicode character.
670
function utilities.utf8charat (str, index)
83✔
671
   return str:sub(index):match("([%z\1-\127\194-\244][\128-\191]*)")
×
672
end
673

674
local utf16bom = function (endianness)
675
   return endianness == "be" and "\254\255" or endianness == "le" and "\255\254" or SU.error("Unrecognized endianness")
13,709✔
676
end
677

678
--- Encode a string to a hexadecimal replesentation.
679
-- @tparam string str Input UTF-8 string
680
-- @treturn string Hexadecimal replesentation of str.
681
function utilities.hexencoded (str)
83✔
682
   local ustr = ""
3✔
683
   for i = 1, #str do
71✔
684
      ustr = ustr .. string.format("%02x", byte(str, i, i + 1))
68✔
685
   end
686
   return ustr
3✔
687
end
688

689
--- Decode a hexadecimal replesentation into a string.
690
-- @tparam string str Input hexadecimal encoded string.
691
-- @treturn string UTF-8 string.
692
function utilities.hexdecoded (str)
83✔
693
   if #str % 2 == 1 then
×
694
      SU.error("Cannot decode hex string with odd len")
×
695
   end
696
   local ustr = ""
×
697
   for i = 1, #str, 2 do
×
698
      ustr = ustr .. string.char(tonumber(string.sub(str, i, i + 1), 16))
×
699
   end
700
   return ustr
×
701
end
702

703
local uchr_to_surrogate_pair = function (uchr, endianness)
704
   local hi, lo = floor((uchr - 0x10000) / 0x400) + 0xd800, (uchr - 0x10000) % 0x400 + 0xdc00
×
705
   local s_hi, s_lo =
706
      string.char(floor(hi / 256)) .. string.char(hi % 256), string.char(floor(lo / 256)) .. string.char(lo % 256)
×
707
   return endianness == "le" and (reverse(s_hi) .. reverse(s_lo)) or s_hi .. s_lo
×
708
end
709

710
local uchr_to_utf16_double_byte = function (uchr, endianness)
711
   local ustr = string.char(floor(uchr / 256)) .. string.char(uchr % 256)
93✔
712
   return endianness == "le" and reverse(ustr) or ustr
31✔
713
end
714

715
local utf8_to_utf16 = function (str, endianness)
716
   local ustr = utf16bom(endianness)
3✔
717
   for _, uchr in luautf8.codes(str) do
34✔
718
      ustr = ustr
×
719
         .. (uchr < 0x10000 and uchr_to_utf16_double_byte(uchr, endianness) or uchr_to_surrogate_pair(uchr, endianness))
62✔
720
   end
721
   return ustr
3✔
722
end
723

724
--- Convert a UTF-8 string to big-endian UTF-16.
725
-- @tparam string str UTF-8 encoded string.
726
-- @treturn string Big-endian UTF-16 encoded string.
727
function utilities.utf8_to_utf16be (str)
83✔
728
   return utf8_to_utf16(str, "be")
3✔
729
end
730

731
--- Convert a UTF-8 string to little-endian UTF-16.
732
-- @tparam string str UTF-8 encoded string.
733
-- @treturn string Little-endian UTF-16 encoded string.
734
function utilities.utf8_to_utf16le (str)
83✔
735
   return utf8_to_utf16(str, "le")
×
736
end
737

738
--- Convert a UTF-8 string to big-endian UTF-16, then encode in hex.
739
-- @tparam string str UTF-8 encoded string.
740
-- @treturn string Hexadecimal representation of a big-endian UTF-16 encoded string.
741
function utilities.utf8_to_utf16be_hexencoded (str)
83✔
742
   return utilities.hexencoded(utilities.utf8_to_utf16be(str))
6✔
743
end
744

745
--- Convert a UTF-8 string to little-endian UTF-16, then encode in hex.
746
-- @tparam string str UTF-8 encoded string.
747
-- @treturn string Hexadecimal representation of a little-endian UTF-16 encoded string.
748
function utilities.utf8_to_utf16le_hexencoded (str)
83✔
749
   return utilities.hexencoded(utilities.utf8_to_utf16le(str))
×
750
end
751

752
local utf16_to_utf8 = function (str, endianness)
753
   local bom = utf16bom(endianness)
13,706✔
754

755
   if str:find(bom) == 1 then
13,706✔
756
      str = string.sub(str, 3, #str)
×
757
   end
758
   local ustr = ""
13,706✔
759
   for uchr in utilities.utf16codes(str, endianness) do
852,402✔
760
      ustr = ustr .. luautf8.char(uchr)
405,642✔
761
   end
762
   return ustr
13,706✔
763
end
764

765
--- Convert a big-endian UTF-16 string to UTF-8.
766
-- @tparam string str Big-endian UTF-16 encoded string.
767
-- @treturn string UTF-8 encoded string.
768
function utilities.utf16be_to_utf8 (str)
83✔
769
   return utf16_to_utf8(str, "be")
13,706✔
770
end
771

772
--- Convert a little-endian UTF-16 string to UTF-8.
773
-- @tparam string str Little-endian UTF-16 encoded string.
774
-- @treturn string UTF-8 encoded string.
775
function utilities.utf16le_to_utf8 (str)
83✔
776
   return utf16_to_utf8(str, "le")
×
777
end
778

779
function utilities.breadcrumbs ()
83✔
780
   local breadcrumbs = {}
83✔
781

782
   setmetatable(breadcrumbs, {
166✔
783
      __index = function (_, key)
784
         local frame = SILE.traceStack[key]
×
785
         return frame and frame.command or nil
×
786
      end,
787
      __len = function (_)
788
         return #SILE.traceStack
×
789
      end,
790
      __tostring = function (self)
791
         return "B»" .. table.concat(self, "»")
×
792
      end,
793
   })
794

795
   function breadcrumbs:dump ()
83✔
796
      SU.dump(self)
×
797
   end
798

799
   function breadcrumbs:parent (count)
83✔
800
      -- Note LuaJIT does not support __len, so this has to work even when that metamethod doesn't fire...
801
      return self[#SILE.traceStack - (count or 1)]
×
802
   end
803

804
   function breadcrumbs:contains (needle, startdepth)
83✔
805
      startdepth = startdepth or 0
×
806
      for i = startdepth, #SILE.traceStack - 1 do
×
807
         local frame = SILE.traceStack[#SILE.traceStack - i]
×
808
         if frame.command == needle then
×
809
            return true, #self - i
×
810
         end
811
      end
812
      return false, -1
×
813
   end
814

815
   return breadcrumbs
83✔
816
end
817

818
utilities.formatNumber = require("core.utilities.numbers")
83✔
819

820
utilities.collatedSort = require("core.utilities.sorting")
83✔
821

822
utilities.ast = require("core.utilities.ast")
83✔
823
utilities.debugAST = utilities.ast.debug
83✔
824

825
function utilities.subContent (content)
83✔
826
   SU.deprecated(
×
827
      "SU.subContent",
828
      "SU.ast.subContent",
829
      "0.15.0",
830
      "0.17.0",
831
      [[
×
832
    Note that the new implementation no longer introduces an id="stuff" key.]]
×
833
   )
834
   return utilities.ast.subContent(content)
×
835
end
836

837
function utilities.hasContent (content)
83✔
838
   SU.deprecated("SU.hasContent", "SU.ast.hasContent", "0.15.0", "0.17.0")
×
839
   return SU.ast.hasContent(content)
×
840
end
841

842
function utilities.contentToString (content)
83✔
843
   SU.deprecated("SU.contentToString", "SU.ast.contentToString", "0.15.0", "0.17.0")
×
844
   return SU.ast.contentToString(content)
×
845
end
846

847
function utilities.walkContent (content, action)
83✔
848
   SU.deprecated("SU.walkContent", "SU.ast.walkContent", "0.15.0", "0.17.0")
×
849
   SU.ast.walkContent(content, action)
×
850
end
851

852
function utilities.stripContentPos (content)
83✔
853
   SU.deprecated("SU.stripContentPos", "SU.ast.stripContentPos", "0.15.0", "0.17.0")
×
854
   return SU.ast.stripContentPos(content)
×
855
end
856

857
return utilities
83✔
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