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

sile-typesetter / sile / 11130695999

01 Oct 2024 05:48PM UTC coverage: 33.585% (+4.0%) from 29.567%
11130695999

push

github

web-flow
Merge pull request #2119 from Omikhleia/feat-math-sqrt

0 of 49 new or added lines in 2 files covered. (0.0%)

81 existing lines in 6 files now uncovered.

5867 of 17469 relevant lines covered (33.59%)

2199.5 hits per line

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

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

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

9
local utilities = {}
100✔
10

11
local epsilon = 1E-12
100✔
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)
100✔
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)
100✔
29
   local new_array = {}
23,029✔
30
   local last = #array
23,029✔
31
   for i = 1, last do
74,945✔
32
      new_array[i] = func(array[i])
98,294✔
33
   end
34
   return new_array
23,029✔
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)
100✔
43
   if not options[name] then
4,662✔
44
      utilities.error(context .. " needs a " .. name .. " parameter")
×
45
   end
46
   if required_type then
4,662✔
47
      return utilities.cast(required_type, options[name])
874✔
48
   end
49
   return options[name]
3,788✔
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)
100✔
UNCOV
58
   local keys = {}
×
UNCOV
59
   for k, _ in pairs(input) do
×
UNCOV
60
      keys[#keys + 1] = k
×
61
   end
UNCOV
62
   table.sort(keys, function (a, b)
×
UNCOV
63
      if type(a) == type(b) then
×
UNCOV
64
         return a < b
×
UNCOV
65
      elseif type(a) == "number" then
×
66
         return true
×
67
      else
UNCOV
68
         return false
×
69
      end
70
   end)
UNCOV
71
   return coroutine.wrap(function ()
×
UNCOV
72
      for i = 1, #keys do
×
UNCOV
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)
100✔
85
   local ptr = start
116✔
86
   local room = stop - start + 1
116✔
87
   local last = replacement and #replacement or 0
116✔
88
   for i = 1, last do
1,053✔
89
      if room > 0 then
937✔
90
         room = room - 1
107✔
91
         array[ptr] = replacement[i]
107✔
92
      else
93
         table.insert(array, ptr, replacement[i])
830✔
94
      end
95
      ptr = ptr + 1
937✔
96
   end
97

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

104
-- TODO: Unused, now deprecated?
105
function utilities.inherit (orig, spec)
100✔
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)
100✔
133
   if value == false then
3,959✔
134
      return false
21✔
135
   end
136
   if value == true then
3,938✔
137
      return true
1,604✔
138
   end
139
   if value == "false" then
2,334✔
140
      return false
2✔
141
   end
142
   if value == "true" then
2,332✔
143
      return true
5✔
144
   end
145
   if value == "no" then
2,327✔
146
      preferbool()
×
147
      return false
×
148
   end
149
   if value == "yes" then
2,327✔
150
      preferbool()
×
151
      return true
×
152
   end
153
   if value == nil then
2,327✔
154
      return default == true
2,327✔
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)
100✔
170
   local actualType = SU.type(value)
221,811✔
171
   wantedType = string.lower(wantedType)
443,622✔
172
   if wantedType:match(actualType) then
221,811✔
173
      return value
77,052✔
174
   elseif actualType == "nil" and wantedType:match("nil") then
144,759✔
175
      return nil
×
176
   elseif wantedType:match("length") then
144,759✔
177
      return SILE.types.length(value)
24,804✔
178
   elseif wantedType:match("measurement") then
120,054✔
179
      return SILE.types.measurement(value)
2,979✔
180
   elseif wantedType:match("vglue") then
117,075✔
181
      return SILE.types.node.vglue(value)
4✔
182
   elseif wantedType:match("glue") then
117,071✔
183
      return SILE.types.node.glue(value)
44✔
184
   elseif wantedType:match("kern") then
117,027✔
185
      return SILE.types.node.kern(value)
×
186
   elseif actualType == "nil" then
117,027✔
187
      SU.error("Cannot cast nil to " .. wantedType)
×
188
   elseif wantedType:match("boolean") then
117,027✔
189
      return SU.boolean(value)
1✔
190
   elseif wantedType:match("string") then
117,026✔
191
      return tostring(value)
×
192
   elseif wantedType:match("number") then
117,026✔
193
      if type(value) == "table" and type(value.tonumber) == "function" then
117,009✔
194
         return value:tonumber()
114,769✔
195
      end
196
      local num = tonumber(value)
2,240✔
197
      if not num then
2,240✔
198
         SU.error("Cannot cast '" .. value .. "'' to " .. wantedType)
×
199
      end
200
      return num
2,240✔
201
   elseif wantedType:match("integer") then
17✔
202
      local num
203
      if type(value) == "table" and type(value.tonumber) == "function" then
17✔
204
         num = value:tonumber()
×
205
      else
206
         num = tonumber(value)
17✔
207
      end
208
      if not num then
17✔
209
         SU.error("Cannot cast '" .. value .. "'' to " .. wantedType)
×
210
      end
211
      if not wantedType:match("number") and num % 1 ~= 0 then
17✔
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
17✔
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)
100✔
228
   if type(value) == "number" then
1,148,751✔
229
      return math.floor(value) == value and "integer" or "number"
283,234✔
230
   elseif type(value) == "table" and value.prototype then
865,517✔
231
      return value:prototype()
×
232
   elseif type(value) == "table" and value.is_a then
865,517✔
233
      return value.type
402,662✔
234
   else
235
      return type(value)
462,855✔
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, ...)
100✔
254
   if SILE.quiet then
66,560✔
255
      return
×
256
   end
257
   if utilities.debugging(category) then
133,120✔
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)
100✔
279
   return SILE.debugFlags.all and category ~= "profile" or SILE.debugFlags[category]
68,946✔
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)
100✔
292
   warnat, errorat = semver(warnat or 0), semver(errorat or 0)
15✔
293
   local current = SILE.version and semver(SILE.version:match("v([0-9]*.[0-9]*.[0-9]*)")) or warnat
10✔
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 "()"
10✔
300
   local _new = new and "Please use " .. (new .. brackets) .. " instead." or "Please don't use it."
5✔
301
   local msg = (old .. brackets)
5✔
302
      .. " was deprecated in SILE v"
×
303
      .. tostring(warnat)
5✔
304
      .. ". "
×
305
      .. _new
5✔
306
      .. (extra and ("\n\n" .. extra .. "\n") or "")
5✔
307
   if errorat and current >= errorat then
5✔
308
      SU.error(msg)
×
309
   elseif warnat and current >= warnat then
5✔
310
      SU.warn(msg)
5✔
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 (...)
100✔
318
   local arg = { ... } -- Avoid things that Lua stuffs in arg like args to self()
1✔
319
   pl.pretty.dump(#arg == 1 and arg[1] or arg, "/dev/stderr")
2✔
320
end
321

322
local _skip_traceback_levels = 2
100✔
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)
100✔
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)
100✔
343
   if SILE.quiet then
31✔
344
      return
×
345
   end
346
   io.stderr:write("\n! " .. message .. "\n")
31✔
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)
100✔
354
   if SILE.quiet then
31✔
355
      return
×
356
   end
357
   utilities.msg(message)
31✔
358
   if SILE.traceback or isbug then
31✔
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())
60✔
367
   end
368
   io.stderr:write("\n")
31✔
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)
100✔
382
   lhs = SU.cast("number", lhs)
82✔
383
   rhs = SU.cast("number", rhs)
82✔
384
   local abs = math.abs
41✔
385
   return abs(lhs - rhs) <= epsilon * (abs(lhs) + abs(rhs))
41✔
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)
100✔
392
   local total = 0
6,726✔
393
   local last = #array
6,726✔
394
   for i = 1, last do
13,069✔
395
      total = total + array[i]
6,343✔
396
   end
397
   return total
6,726✔
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 (...)
100✔
404
   local input = pl.utils.pack(...)
14,663✔
405
   local max = table.remove(input, 1)
14,663✔
406
   for _, val in ipairs(input) do
49,174✔
407
      if val > max then
34,511✔
408
         max = val
12,385✔
409
      end
410
   end
411
   return max
14,663✔
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 (...)
100✔
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)
100✔
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)
100✔
455
   local rv = {}
484✔
456
   local max = math.max(pl.utils.unpack(pl.tablex.keys(items)))
1,452✔
457
   for i = 1, max do
11,201✔
458
      if items[i] then
10,717✔
459
         rv[#rv + 1] = items[i]
10,717✔
460
      end
461
   end
462
   return rv
484✔
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)
100✔
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)
100✔
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)
100✔
498
   if spring == 0 then
9,293✔
499
      return inf_bad
240✔
500
   end
501
   local bad = math.floor(100 * math.abs(shortfall / spring) ^ 3)
9,053✔
502
   return math.min(inf_bad, bad)
9,053✔
503
end
504

505
function utilities.rationWidth (target, width, ratio)
100✔
506
   if ratio < 0 and width.shrink:tonumber() > 0 then
10,231✔
507
      target:___add(width.shrink:tonumber() * ratio)
2,298✔
508
   elseif ratio > 0 and width.stretch:tonumber() > 0 then
13,603✔
509
      target:___add(width.stretch:tonumber() * ratio)
3,698✔
510
   end
511
   return target
8,200✔
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)
100✔
523
   string = string and tostring(string) or ""
790✔
524
   pattern = pattern and tostring(pattern) or "%s+"
790✔
525
   local length = #string
790✔
526
   return coroutine.wrap(function ()
790✔
527
      local index = 1
790✔
528
      repeat
529
         local first, last = string:find(pattern, index)
1,020✔
530
         if last then
1,020✔
531
            if index < first then
339✔
532
               coroutine.yield({ string = string:sub(index, first - 1) })
438✔
533
            end
534
            coroutine.yield({ separator = string:sub(first, last) })
678✔
535
            index = last + 1
339✔
536
         else
537
            if index <= length then
681✔
538
               coroutine.yield({ string = string:sub(index) })
1,362✔
539
            end
540
            break
681✔
541
         end
542
      until index > length
339✔
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)
100✔
550
   local seq = 0
98,890✔
551
   local val = -1
98,890✔
552
   for i = 1, #uchar do
199,563✔
553
      local c = string.byte(uchar, i)
101,991✔
554
      if seq == 0 then
101,991✔
555
         if val > -1 then
99,118✔
556
            return val
1,318✔
557
         end
558
         seq = c < 0x80 and 1
97,800✔
559
            or c < 0xE0 and 2
97,800✔
560
            or c < 0xF0 and 3
2,700✔
561
            or c < 0xF8 and 4 --c < 0xFC and 5 or c < 0xFE and 6 or
173✔
562
            or error("invalid UTF-8 character sequence")
×
563
         val = bitshim.band(c, 2 ^ (8 - seq) - 1)
97,800✔
564
      else
565
         val = bitshim.bor(bitshim.lshift(val, 6), bitshim.band(c, 0x3F))
2,873✔
566
      end
567
      seq = seq - 1
100,673✔
568
   end
569
   return val
97,572✔
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)
100✔
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)
100✔
597
   local pos = 1
17,145✔
598
   return function ()
599
      if pos > #ustr then
525,309✔
600
         return nil
17,145✔
601
      else
602
         local c1, c2, c3, c4, wchar, lowchar
603
         c1 = string.byte(ustr, pos, pos + 1)
508,164✔
604
         pos = pos + 1
508,164✔
605
         c2 = string.byte(ustr, pos, pos + 1)
508,164✔
606
         pos = pos + 1
508,164✔
607
         if endian == "be" then
508,164✔
608
            wchar = c1 * 256 + c2
508,164✔
609
         else
610
            wchar = c2 * 256 + c1
×
611
         end
612
         if not (wchar >= 0xD800 and wchar <= 0xDBFF) then
508,164✔
613
            return wchar
508,164✔
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)
100✔
635
   local rv = {}
55,722✔
636
   for _, cp in luautf8.next, str do
370,505✔
637
      table.insert(rv, luautf8.char(cp))
314,783✔
638
   end
639
   return rv
55,722✔
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)
100✔
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)
100✔
658
   local chars = utilities.splitUtf8(str)
×
659
   return chars[1]
×
660
end
661

662
local byte, floor, reverse = string.byte, math.floor, string.reverse
100✔
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)
100✔
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")
17,145✔
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)
100✔
UNCOV
682
   local ustr = ""
×
UNCOV
683
   for i = 1, #str do
×
UNCOV
684
      ustr = ustr .. string.format("%02x", byte(str, i, i + 1))
×
685
   end
UNCOV
686
   return ustr
×
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)
100✔
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)
UNCOV
711
   local ustr = string.char(floor(uchr / 256)) .. string.char(uchr % 256)
×
UNCOV
712
   return endianness == "le" and reverse(ustr) or ustr
×
713
end
714

715
local utf8_to_utf16 = function (str, endianness)
UNCOV
716
   local ustr = utf16bom(endianness)
×
UNCOV
717
   for _, uchr in luautf8.codes(str) do
×
718
      ustr = ustr
×
UNCOV
719
         .. (uchr < 0x10000 and uchr_to_utf16_double_byte(uchr, endianness) or uchr_to_surrogate_pair(uchr, endianness))
×
720
   end
UNCOV
721
   return ustr
×
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)
100✔
UNCOV
728
   return utf8_to_utf16(str, "be")
×
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)
100✔
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)
100✔
UNCOV
742
   return utilities.hexencoded(utilities.utf8_to_utf16be(str))
×
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)
100✔
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)
17,145✔
754

755
   if str:find(bom) == 1 then
17,145✔
756
      str = string.sub(str, 3, #str)
×
757
   end
758
   local ustr = ""
17,145✔
759
   for uchr in utilities.utf16codes(str, endianness) do
1,067,763✔
760
      ustr = ustr .. luautf8.char(uchr)
508,164✔
761
   end
762
   return ustr
17,145✔
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)
100✔
769
   return utf16_to_utf8(str, "be")
17,145✔
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)
100✔
776
   return utf16_to_utf8(str, "le")
×
777
end
778

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

782
   setmetatable(breadcrumbs, {
202✔
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 ()
101✔
796
      SU.dump(self)
×
797
   end
798

799
   function breadcrumbs:parent (count)
101✔
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)
101✔
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
101✔
816
end
817

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

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

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

825
function utilities.subContent (content)
100✔
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)
100✔
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)
100✔
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)
100✔
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)
100✔
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
100✔
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