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

lunarmodules / Penlight / 46279356752

29 Nov 2026 03:36PM UTC coverage: 83.225% (-7.1%) from 90.342%
46279356752

push

github

web-flow
Merge 0622ec222 into 44007e542

5125 of 6158 relevant lines covered (83.23%)

880.41 hits per line

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

78.42
/lua/pl/stringx.lua
1
--- Python-style extended string library.
2
--
3
-- see 3.6.1 of the Python reference.
4
-- If you want to make these available as string methods, then say
5
-- `stringx.import()` to bring them into the standard `string` table.
6
--
7
-- See @{03-strings.md|the Guide}
8
--
9
-- Dependencies: `pl.utils`, `pl.types`
10
-- @module pl.stringx
11
local utils = require 'pl.utils'
×
12
local is_callable = require 'pl.types'.is_callable
×
13
local string = string
×
14
local find = string.find
×
15
local type,setmetatable,ipairs = type,setmetatable,ipairs
×
16
local error = error
×
17
local gsub = string.gsub
×
18
local rep = string.rep
×
19
local sub = string.sub
×
20
local reverse = string.reverse
×
21
local concat = table.concat
×
22
local append = table.insert
×
23
local escape = utils.escape
×
24
local ceil, max = math.ceil, math.max
×
25
local assert_arg,usplit = utils.assert_arg,utils.split
×
26
local lstrip
27
local unpack = utils.unpack
×
28
local pack = utils.pack
×
29

30
local function assert_string (n,s)
31
    assert_arg(n,s,'string')
7,066 ✔
32
end
33

34
local function non_empty(s)
35
    return #s > 0
224 ✔
36
end
37

38
local function assert_nonempty_string(n,s)
39
    assert_arg(n,s,'string',non_empty,'must be a non-empty string')
224 ✔
40
end
41

42
local function makelist(l)
43
    return setmetatable(l, require('pl.List'))
700 ✔
44
end
45

46
local stringx = {}
×
47

48
------------------
49
-- String Predicates
50
-- @section predicates
51

52
--- does s only contain alphabetic characters?
53
-- @string s a string
54
function stringx.isalpha(s)
×
55
    assert_string(1,s)
84 ✔
56
    return find(s,'^%a+$') == 1
84 ✔
57
end
58

59
--- does s only contain digits?
60
-- @string s a string
61
function stringx.isdigit(s)
×
62
    assert_string(1,s)
224 ✔
63
    return find(s,'^%d+$') == 1
224 ✔
64
end
65

66
--- does s only contain alphanumeric characters?
67
-- @string s a string
68
function stringx.isalnum(s)
×
69
    assert_string(1,s)
42 ✔
70
    return find(s,'^%w+$') == 1
42 ✔
71
end
72

73
--- does s only contain whitespace?
74
-- Matches on pattern '%s' so matches space, newline, tabs, etc.
75
-- @string s a string
76
function stringx.isspace(s)
×
77
    assert_string(1,s)
56 ✔
78
    return find(s,'^%s+$') == 1
56 ✔
79
end
80

81
--- does s only contain lower case characters?
82
-- @string s a string
83
function stringx.islower(s)
×
84
    assert_string(1,s)
56 ✔
85
    return find(s,'^[%l%s]+$') == 1
56 ✔
86
end
87

88
--- does s only contain upper case characters?
89
-- @string s a string
90
function stringx.isupper(s)
×
91
    assert_string(1,s)
56 ✔
92
    return find(s,'^[%u%s]+$') == 1
56 ✔
93
end
94

95
local function raw_startswith(s, prefix)
96
    return find(s,prefix,1,true) == 1
210 ✔
97
end
98

99
local function raw_endswith(s, suffix)
100
    return #s >= #suffix and find(s, suffix, #s-#suffix+1, true) and true or false
294 ✔
101
end
102

103
local function test_affixes(s, affixes, fn)
104
    if type(affixes) == 'string' then
448 ✔
105
        return fn(s,affixes)
364 ✔
106
    elseif type(affixes) == 'table' then
84 ✔
107
        for _,affix in ipairs(affixes) do
168 ✔
108
            if fn(s,affix) then return true end
180 ✔
109
        end
110
        return false
28 ✔
111
    else
112
        error(("argument #2 expected a 'string' or a 'table', got a '%s'"):format(type(affixes)))
×
113
    end
114
end
115

116
--- does s start with prefix or one of prefixes?
117
-- @string s a string
118
-- @param prefix a string or an array of strings
119
function stringx.startswith(s,prefix)
×
120
    assert_string(1,s)
182 ✔
121
    return test_affixes(s,prefix,raw_startswith)
182 ✔
122
end
123

124
--- does s end with suffix or one of suffixes?
125
-- @string s a string
126
-- @param suffix a string or an array of strings
127
function stringx.endswith(s,suffix)
×
128
    assert_string(1,s)
266 ✔
129
    return test_affixes(s,suffix,raw_endswith)
266 ✔
130
end
131

132
--- Strings and Lists
133
-- @section lists
134

135
--- concatenate the strings using this string as a delimiter.
136
-- Note that the arguments are reversed from `string.concat`.
137
-- @string s the string
138
-- @param seq a table of strings or numbers
139
-- @usage stringx.join(' ', {1,2,3}) == '1 2 3'
140
function stringx.join(s,seq)
×
141
    assert_string(1,s)
14 ✔
142
    return concat(seq,s)
14 ✔
143
end
144

145
--- Split a string into a list of lines.
146
-- `"\r"`, `"\n"`, and `"\r\n"` are considered line ends.
147
-- They are not included in the lines unless `keepends` is passed.
148
-- Terminal line end does not produce an extra line.
149
-- Splitting an empty string results in an empty list.
150
-- @string s the string.
151
-- @bool[opt] keep_ends include line ends.
152
-- @return List of lines
153
function stringx.splitlines(s, keep_ends)
×
154
    assert_string(1, s)
126 ✔
155
    local res = {}
126 ✔
156
    local pos = 1
126 ✔
157
    while true do
158
        local line_end_pos = find(s, '[\r\n]', pos)
322 ✔
159
        if not line_end_pos then
322 ✔
160
            break
72 ✔
161
        end
162

163
        local line_end = sub(s, line_end_pos, line_end_pos)
196 ✔
164
        if line_end == '\r' and sub(s, line_end_pos + 1, line_end_pos + 1) == '\n' then
214 ✔
165
            line_end = '\r\n'
28 ✔
166
        end
167

168
        local line = sub(s, pos, line_end_pos - 1)
196 ✔
169
        if keep_ends then
196 ✔
170
            line = line .. line_end
84 ✔
171
        end
172
        append(res, line)
196 ✔
173

174
        pos = line_end_pos + #line_end
196 ✔
175
    end
176

177
    if pos <= #s then
126 ✔
178
        append(res, sub(s, pos))
18 ✔
179
    end
180
    return makelist(res)
126 ✔
181
end
182

183
--- split a string into a list of strings using a delimiter.
184
-- @function split
185
-- @string s the string
186
-- @string[opt] re a delimiter (defaults to whitespace)
187
-- @int[opt] n maximum number of results
188
-- @return List
189
-- @usage #(stringx.split('one two')) == 2
190
-- @usage stringx.split('one,two,three', ',') == List{'one','two','three'}
191
-- @usage stringx.split('one,two,three', ',', 2) == List{'one','two,three'}
192
function stringx.split(s,re,n)
×
193
    assert_string(1,s)
392 ✔
194
    local plain = true
392 ✔
195
    if not re then -- default spaces
392 ✔
196
        s = lstrip(s)
360 ✔
197
        plain = false
280 ✔
198
    end
199
    local res = usplit(s,re,plain,n)
392 ✔
200
    if re and re ~= '' and
392 ✔
201
       find(s,re,-#re,true) and
84 ✔
202
       (n or math.huge) > #res then
42 ✔
203
        res[#res+1] = ""
28 ✔
204
    end
205
    return makelist(res)
392 ✔
206
end
207

208
--- replace all tabs in s with tabsize spaces. If not specified, tabsize defaults to 8.
209
-- Tab stops will be honored.
210
-- @string s the string (multi-line strings are supported)
211
-- @int tabsize[opt=8] number of spaces to expand each tab
212
-- @return expanded string
213
-- @usage stringx.expandtabs('\tone,two,three', 4)   == '    one,two,three'
214
-- @usage stringx.expandtabs('  \tone,two,three', 4) == '    one,two,three'
215
function stringx.expandtabs(s,tabsize)
×
216
  assert_string(1,s)
112 ✔
217
  tabsize = tabsize or 8
112 ✔
218
  return (s:gsub("([^\t\r\n]*)\t", function(before_tab)
224 ✔
219
      if tabsize == 0 then
126 ✔
220
        return before_tab
14 ✔
221
      else
222
        return before_tab .. (" "):rep(tabsize - #before_tab % tabsize)
112 ✔
223
      end
224
    end))
225
end
226

227
--- Finding and Replacing
228
-- @section find
229

230
local function _find_all(s,sub,first,last,allow_overlap)
231
    first = first or 1
336 ✔
232
    last = last or #s
336 ✔
233
    if sub == '' then return last+1,last-first+1 end
336 ✔
234
    local i1,i2 = find(s,sub,first,true)
280 ✔
235
    local res
236
    local k = 0
280 ✔
237
    while i1 do
672 ✔
238
        if last and i2 > last then break end
434 ✔
239
        res = i1
392 ✔
240
        k = k + 1
392 ✔
241
        if allow_overlap then
392 ✔
242
            i1,i2 = find(s,sub,i1+1,true)
308 ✔
243
        else
244
            i1,i2 = find(s,sub,i2+1,true)
84 ✔
245
        end
246
    end
247
    return res,k
280 ✔
248
end
249

250
--- find index of first instance of sub in s from the left.
251
-- @string s the string
252
-- @string sub substring
253
-- @int[opt] first first index
254
-- @int[opt] last last index
255
-- @return start index, or nil if not found
256
function stringx.lfind(s,sub,first,last)
×
257
    assert_string(1,s)
252 ✔
258
    assert_string(2,sub)
252 ✔
259
    local i1, i2 = find(s,sub,first,true)
252 ✔
260

261
    if i1 and (not last or i2 <= last) then
252 ✔
262
        return i1
196 ✔
263
    else
264
        return nil
56 ✔
265
    end
266
end
267

268
--- find index of first instance of sub in s from the right.
269
-- @string s the string
270
-- @string sub substring
271
-- @int[opt] first first index
272
-- @int[opt] last last index
273
-- @return start index, or nil if not found
274
function stringx.rfind(s,sub,first,last)
×
275
    assert_string(1,s)
238 ✔
276
    assert_string(2,sub)
238 ✔
277
    return (_find_all(s,sub,first,last,true))
306 ✔
278
end
279

280
--- replace up to n instances of old by new in the string s.
281
-- If n is not present, replace all instances.
282
-- @string s the string
283
-- @string old the target substring
284
-- @string new the substitution
285
-- @int[opt] n optional maximum number of substitutions
286
-- @return result string
287
function stringx.replace(s,old,new,n)
×
288
    assert_string(1,s)
126 ✔
289
    assert_string(2,old)
126 ✔
290
    assert_string(3,new)
126 ✔
291
    return (gsub(s,escape(old),new:gsub('%%','%%%%'),n))
162 ✔
292
end
293

294
--- count all instances of substring in string.
295
-- @string s the string
296
-- @string sub substring
297
-- @bool[opt] allow_overlap allow matches to overlap
298
-- @usage
299
-- assert(stringx.count('banana', 'ana') == 1)
300
-- assert(stringx.count('banana', 'ana', true) == 2)
301
function stringx.count(s,sub,allow_overlap)
×
302
    assert_string(1,s)
98 ✔
303
    local _,k = _find_all(s,sub,1,false,allow_overlap)
98 ✔
304
    return k
98 ✔
305
end
306

307
--- Stripping and Justifying
308
-- @section strip
309

310
local function _just(s,w,ch,left,right)
311
    local n = #s
224 ✔
312
    if w > n then
224 ✔
313
        if not ch then ch = ' ' end
140 ✔
314
        local f1,f2
315
        if left and right then
140 ✔
316
            local rn = ceil((w-n)/2)
56 ✔
317
            local ln = w - n - rn
56 ✔
318
            f1 = rep(ch,ln)
56 ✔
319
            f2 = rep(ch,rn)
56 ✔
320
        elseif right then
84 ✔
321
            f1 = rep(ch,w-n)
42 ✔
322
            f2 = ''
42 ✔
323
        else
324
            f2 = rep(ch,w-n)
42 ✔
325
            f1 = ''
42 ✔
326
        end
327
        return f1..s..f2
140 ✔
328
    else
329
        return s
84 ✔
330
    end
331
end
332

333
--- left-justify s with width w.
334
-- @string s the string
335
-- @int w width of justification
336
-- @string[opt=' '] ch padding character
337
-- @usage stringx.ljust('hello', 10, '*') == '*****hello'
338
function stringx.ljust(s,w,ch)
×
339
    assert_string(1,s)
70 ✔
340
    assert_arg(2,w,'number')
70 ✔
341
    return _just(s,w,ch,true,false)
70 ✔
342
end
343

344
--- right-justify s with width w.
345
-- @string s the string
346
-- @int w width of justification
347
-- @string[opt=' '] ch padding character
348
-- @usage stringx.rjust('hello', 10, '*') == 'hello*****'
349
function stringx.rjust(s,w,ch)
×
350
    assert_string(1,s)
70 ✔
351
    assert_arg(2,w,'number')
70 ✔
352
    return _just(s,w,ch,false,true)
70 ✔
353
end
354

355
--- center-justify s with width w.
356
-- @string s the string
357
-- @int w width of justification
358
-- @string[opt=' '] ch padding character
359
-- @usage stringx.center('hello', 10, '*') == '**hello***'
360
function stringx.center(s,w,ch)
×
361
    assert_string(1,s)
84 ✔
362
    assert_arg(2,w,'number')
84 ✔
363
    return _just(s,w,ch,true,true)
84 ✔
364
end
365

366
local function _strip(s,left,right,chrs)
367
    if not chrs then
2,226 ✔
368
        chrs = '%s'
2,184 ✔
369
    else
370
        chrs = '['..escape(chrs)..']'
54 ✔
371
    end
372
    local f = 1
2,226 ✔
373
    local t
374
    if left then
2,226 ✔
375
        local i1,i2 = find(s,'^'..chrs..'*')
2,072 ✔
376
        if i2 >= i1 then
2,072 ✔
377
            f = i2+1
308 ✔
378
        end
379
    end
380
    if right then
2,226 ✔
381
        if #s < 200 then
1,792 ✔
382
            local i1,i2 = find(s,chrs..'*$',f)
1,764 ✔
383
            if i2 >= i1 then
1,764 ✔
384
                t = i1-1
266 ✔
385
            end
386
        else
387
            local rs = reverse(s)
28 ✔
388
            local i1,i2 = find(rs, '^'..chrs..'*')
28 ✔
389
            if i2 >= i1 then
28 ✔
390
                t = -i2-1
×
391
            end
392
        end
393
    end
394
    return sub(s,f,t)
2,226 ✔
395
end
396

397
--- trim any characters on the left of s.
398
-- @string s the string
399
-- @string[opt='%s'] chrs default any whitespace character,
400
-- but can be a string of characters to be trimmed
401
function stringx.lstrip(s,chrs)
×
402
    assert_string(1,s)
434 ✔
403
    return _strip(s,true,false,chrs)
434 ✔
404
end
405
lstrip = stringx.lstrip
×
406

407
--- trim any characters on the right of s.
408
-- @string s the string
409
-- @string[opt='%s'] chrs default any whitespace character,
410
-- but can be a string of characters to be trimmed
411
function stringx.rstrip(s,chrs)
×
412
    assert_string(1,s)
154 ✔
413
    return _strip(s,false,true,chrs)
154 ✔
414
end
415

416
--- trim any characters on both left and right of s.
417
-- @string s the string
418
-- @string[opt='%s'] chrs default any whitespace character,
419
-- but can be a string of characters to be trimmed
420
-- @usage stringx.strip('  --== Hello ==--  ', "- =")  --> 'Hello'
421
function stringx.strip(s,chrs)
×
422
    assert_string(1,s)
1,638 ✔
423
    return _strip(s,true,true,chrs)
1,638 ✔
424
end
425

426
--- Partitioning Strings
427
-- @section partitioning
428

429
--- split a string using a pattern. Note that at least one value will be returned!
430
-- @string s the string
431
-- @string[opt='%s'] re a Lua string pattern (defaults to whitespace)
432
-- @return the parts of the string
433
-- @usage  a,b = line:splitv('=')
434
-- @see utils.splitv
435
function stringx.splitv(s,re)
×
436
    assert_string(1,s)
14 ✔
437
    return utils.splitv(s,re)
14 ✔
438
end
439

440
-- The partition functions split a string using a delimiter into three parts:
441
-- the part before, the delimiter itself, and the part afterwards
442
local function _partition(p,delim,fn)
443
    local i1,i2 = fn(p,delim)
196 ✔
444
    if not i1 or i1 == -1 then
196 ✔
445
        return p,'',''
42 ✔
446
    else
447
        if not i2 then i2 = i1 + #delim - 1 end
154 ✔
448
        return sub(p,1,i1-1),sub(p,i1,i2),sub(p,i2+1)
274 ✔
449
    end
450
end
451

452
--- partition the string using first occurrence of a delimiter
453
-- @string s the string
454
-- @string ch delimiter, one or more characters (match as plain string, no patterns)
455
-- @return part before ch
456
-- @return ch
457
-- @return part after ch
458
-- @usage {stringx.partition('a,b,c', ','))} == {'a', ',', 'b,c'}
459
-- @usage {stringx.partition('a::b::c', '::'))} == {'a', '::', 'b::c'}
460
-- @usage {stringx.partition('abc', 'x'))} == {'abc', '', ''}
461
function stringx.partition(s,ch)
×
462
    assert_string(1,s)
126 ✔
463
    assert_nonempty_string(2,ch)
126 ✔
464
    return _partition(s,ch,stringx.lfind)
112 ✔
465
end
466

467
--- partition the string p using last occurrence of a delimiter
468
-- @string s the string
469
-- @string ch delimiter, one or more characters (match as plain string, no patterns)
470
-- @return part before ch
471
-- @return ch
472
-- @return part after ch
473
-- @usage {stringx.rpartition('a,b,c', ','))} == {'a,b', ',', 'c'}
474
-- @usage {stringx.rpartition('a::b::c', '::'))} == {'a::b', '::', 'c'}
475
-- @usage {stringx.rpartition('abc', 'x'))} == {'', '', 'abc'}
476
function stringx.rpartition(s,ch)
×
477
    assert_string(1,s)
98 ✔
478
    assert_nonempty_string(2,ch)
98 ✔
479
    local a,b,c = _partition(s,ch,stringx.rfind)
84 ✔
480
    if a == s then -- no match found
84 ✔
481
        return c,b,a
14 ✔
482
    end
483
    return a,b,c
70 ✔
484
end
485

486
--- return the 'character' at the index.
487
-- @string s the string
488
-- @int idx an index (can be negative)
489
-- @return a substring of length 1 if successful, empty string otherwise.
490
function stringx.at(s,idx)
×
491
    assert_string(1,s)
56 ✔
492
    assert_arg(2,idx,'number')
56 ✔
493
    return sub(s,idx,idx)
56 ✔
494
end
495

496

497
--- Text handling
498
-- @section text
499

500

501
--- indent a multiline string.
502
-- @tparam string s the (multiline) string
503
-- @tparam integer n the size of the indent
504
-- @tparam[opt=' '] string ch the character to use when indenting
505
-- @return indented string
506
function stringx.indent (s,n,ch)
×
507
  assert_arg(1,s,'string')
56 ✔
508
  assert_arg(2,n,'number')
56 ✔
509
  local lines = usplit(s ,'\n')
56 ✔
510
  local prefix = string.rep(ch or ' ',n)
56 ✔
511
  for i, line in ipairs(lines) do
182 ✔
512
    lines[i] = prefix..line
126 ✔
513
  end
514
  return concat(lines,'\n')..'\n'
56 ✔
515
end
516

517

518
--- dedent a multiline string by removing any initial indent.
519
-- useful when working with [[..]] strings.
520
-- Empty lines are ignored.
521
-- @tparam string s the (multiline) string
522
-- @return a string with initial indent zero.
523
-- @usage
524
-- local s = dedent [[
525
--          One
526
--
527
--        Two
528
--
529
--      Three
530
-- ]]
531
-- assert(s == [[
532
--     One
533
--
534
--   Two
535
--
536
-- Three
537
-- ]])
538
function stringx.dedent (s)
×
539
  assert_arg(1,s,'string')
56 ✔
540
  local lst = usplit(s,'\n')
56 ✔
541
  if #lst>0 then
56 ✔
542
    local ind_size = math.huge
56 ✔
543
    for i, line in ipairs(lst) do
224 ✔
544
      local i1, i2 = lst[i]:find('^%s*[^%s]')
168 ✔
545
      if i1 and i2 < ind_size then
168 ✔
546
        ind_size = i2
84 ✔
547
      end
548
    end
549
    for i, line in ipairs(lst) do
224 ✔
550
      lst[i] = lst[i]:sub(ind_size, -1)
212 ✔
551
    end
552
  end
553
  return concat(lst,'\n')..'\n'
56 ✔
554
end
555

556

557

558
do
559
  local buildline = function(words, i, size, breaklong)
560
    -- if overflow is set, a word longer than size, will overflow the size
561
    -- otherwise it will be chopped in line-length pieces
562
    local line = {}
1,260 ✔
563
    if #words[i] > size then
1,260 ✔
564
      -- word longer than line
565
      if not breaklong then
490 ✔
566
        line[1] = words[i]
182 ✔
567
        i = i + 1
182 ✔
568
      else
569
        line[1] = words[i]:sub(1, size)
396 ✔
570
        words[i] = words[i]:sub(size + 1, -1)
396 ✔
571
      end
572
    else
573
      local len = 0
770 ✔
574
      while words[i] and (len + #words[i] <= size) or
2,520 ✔
575
            (len == 0 and #words[i] == size) do
1,270 ✔
576
        if words[i] ~= "" then
1,750 ✔
577
          line[#line+1] = words[i]
1,610 ✔
578
          len = len + #words[i] + 1
1,610 ✔
579
        end
580
        i = i + 1
1,750 ✔
581
      end
582
    end
583
    return stringx.strip(concat(line, " ")), i
1,620 ✔
584
  end
585

586
  --- format a paragraph into lines so that they fit into a line width.
587
  -- It will not break long words by default, so lines can be over the length
588
  -- to that extent.
589
  -- @tparam string s the string to format
590
  -- @tparam[opt=70] integer width the margin width
591
  -- @tparam[opt=false] boolean breaklong if truthy, words longer than the width given will be forced split.
592
  -- @return a list of lines (List object), use `fill` to return a string instead of a `List`.
593
  -- @see pl.List
594
  -- @see fill
595
  stringx.wrap = function(s, width, breaklong)
596
    s = s:gsub('\n',' ') -- remove line breaks
210 ✔
597
    s = stringx.strip(s) -- remove leading/trailing whitespace
266 ✔
598
    if s == "" then
210 ✔
599
      return { "" }
28 ✔
600
    end
601
    width = width or 70
182 ✔
602
    local out = {}
182 ✔
603
    local words = usplit(s, "%s")
182 ✔
604
    local i = 1
182 ✔
605
    while words[i] do
1,442 ✔
606
      out[#out+1], i = buildline(words, i, width, breaklong)
1,620 ✔
607
    end
608
    return makelist(out)
182 ✔
609
  end
610
end
611

612
--- format a paragraph so that it fits into a line width.
613
-- @tparam string s the string to format
614
-- @tparam[opt=70] integer width the margin width
615
-- @tparam[opt=false] boolean breaklong if truthy, words longer than the width given will be forced split.
616
-- @return a string, use `wrap` to return a list of lines instead of a string.
617
-- @see wrap
618
function stringx.fill (s,width,breaklong)
×
619
  return concat(stringx.wrap(s,width,breaklong),'\n') .. '\n'
18 ✔
620
end
621

622
--- Template
623
-- @section Template
624

625

626
local function _substitute(s,tbl,safe)
627
  local subst
628
  if is_callable(tbl) then
54 ✔
629
    subst = tbl
×
630
  else
631
    function subst(f)
36 ✔
632
      local s = tbl[f]
56 ✔
633
      if not s then
56 ✔
634
        if safe then
×
635
          return f
×
636
        else
637
          error("not present in table "..f)
×
638
        end
639
      else
640
        return s
56 ✔
641
      end
642
    end
643
  end
644
  local res = gsub(s,'%${([%w_]+)}',subst)
42 ✔
645
  return (gsub(res,'%$([%w_]+)',subst))
42 ✔
646
end
647

648

649

650
local Template = {}
×
651
stringx.Template = Template
×
652
Template.__index = Template
×
653
setmetatable(Template, {
×
654
  __call = function(obj,tmpl)
655
    return Template.new(tmpl)
42 ✔
656
  end
657
})
658

659
--- Creates a new Template class.
660
-- This is a shortcut to `Template.new(tmpl)`.
661
-- @tparam string tmpl the template string
662
-- @function Template
663
-- @treturn Template
664
function Template.new(tmpl)
×
665
  assert_arg(1,tmpl,'string')
42 ✔
666
  local res = {}
42 ✔
667
  res.tmpl = tmpl
42 ✔
668
  setmetatable(res,Template)
42 ✔
669
  return res
42 ✔
670
end
671

672
--- substitute values into a template, throwing an error.
673
-- This will throw an error if no name is found.
674
-- @tparam table tbl a table of name-value pairs.
675
-- @return string with place holders substituted
676
function Template:substitute(tbl)
×
677
  assert_arg(1,tbl,'table')
28 ✔
678
  return _substitute(self.tmpl,tbl,false)
28 ✔
679
end
680

681
--- substitute values into a template.
682
-- This version just passes unknown names through.
683
-- @tparam table tbl a table of name-value pairs.
684
-- @return string with place holders substituted
685
function Template:safe_substitute(tbl)
×
686
  assert_arg(1,tbl,'table')
×
687
  return _substitute(self.tmpl,tbl,true)
×
688
end
689

690
--- substitute values into a template, preserving indentation. <br>
691
-- If the value is a multiline string _or_ a template, it will insert
692
-- the lines at the correct indentation. <br>
693
-- Furthermore, if a template, then that template will be substituted
694
-- using the same table.
695
-- @tparam table tbl a table of name-value pairs.
696
-- @return string with place holders substituted
697
function Template:indent_substitute(tbl)
×
698
  assert_arg(1,tbl,'table')
14 ✔
699
  if not self.strings then
14 ✔
700
    self.strings = usplit(self.tmpl,'\n')
18 ✔
701
  end
702

703
  -- the idea is to substitute line by line, grabbing any spaces as
704
  -- well as the $var. If the value to be substituted contains newlines,
705
  -- then we split that into lines and adjust the indent before inserting.
706
  local function subst(line)
707
    return line:gsub('(%s*)%$([%w_]+)',function(sp,f)
72 ✔
708
      local subtmpl
709
      local s = tbl[f]
14 ✔
710
      if not s then error("not present in table "..f) end
14 ✔
711
      if getmetatable(s) == Template then
14 ✔
712
        subtmpl = s
×
713
        s = s.tmpl
×
714
      else
715
        s = tostring(s)
14 ✔
716
      end
717
      if s:find '\n' then
14 ✔
718
        local lines = usplit(s, '\n')
14 ✔
719
        for i, line in ipairs(lines) do
56 ✔
720
          lines[i] = sp..line
42 ✔
721
        end
722
        s = concat(lines, '\n') .. '\n'
14 ✔
723
      end
724
      if subtmpl then
14 ✔
725
        return _substitute(s, tbl)
×
726
      else
727
        return s
14 ✔
728
      end
729
    end)
730
  end
731

732
  local lines = {}
14 ✔
733
  for i, line in ipairs(self.strings) do
56 ✔
734
    lines[i] = subst(line)
54 ✔
735
  end
736
  return concat(lines,'\n')..'\n'
14 ✔
737
end
738

739

740

741
--- Miscellaneous
742
-- @section misc
743

744
--- return an iterator over all lines in a string
745
-- @string s the string
746
-- @return an iterator
747
-- @usage
748
-- local line_no = 1
749
-- for line in stringx.lines(some_text) do
750
--   print(line_no, line)
751
--   line_no = line_no + 1
752
-- end
753
function stringx.lines(s)
×
754
    assert_string(1,s)
42 ✔
755
    if not s:find '\n$' then s = s..'\n' end
42 ✔
756
    return s:gmatch('([^\n]*)\n')
42 ✔
757
end
758

759
--- initial word letters uppercase ('title case').
760
-- Here 'words' mean chunks of non-space characters.
761
-- @string s the string
762
-- @return a string with each word's first letter uppercase
763
-- @usage stringx.title("hello world") == "Hello World")
764
function stringx.title(s)
×
765
    assert_string(1,s)
42 ✔
766
    return (s:gsub('(%S)(%S*)',function(f,r)
84 ✔
767
        return f:upper()..r:lower()
88 ✔
768
    end))
769
end
770

771
stringx.capitalize = stringx.title
×
772

773
do
774
  local ellipsis = '...'
×
775
  local n_ellipsis = #ellipsis
×
776

777
  --- Return a shortened version of a string.
778
  -- Fits string within w characters. Removed characters are marked with ellipsis.
779
  -- @string s the string
780
  -- @int w the maximum size allowed
781
  -- @bool tail true if we want to show the end of the string (head otherwise)
782
  -- @usage ('1234567890'):shorten(8) == '12345...'
783
  -- @usage ('1234567890'):shorten(8, true) == '...67890'
784
  -- @usage ('1234567890'):shorten(20) == '1234567890'
785
  function stringx.shorten(s,w,tail)
×
786
      assert_string(1,s)
252 ✔
787
      if #s > w then
252 ✔
788
          if w < n_ellipsis then return ellipsis:sub(1,w) end
154 ✔
789
          if tail then
70 ✔
790
              local i = #s - w + 1 + n_ellipsis
28 ✔
791
              return ellipsis .. s:sub(i)
34 ✔
792
          else
793
              return s:sub(1,w-n_ellipsis) .. ellipsis
50 ✔
794
          end
795
      end
796
      return s
98 ✔
797
  end
798
end
799

800

801
do
802
  -- Utility function that finds any patterns that match a long string's an open or close.
803
  -- Note that having this function use the least number of equal signs that is possible is a harder algorithm to come up with.
804
  -- Right now, it simply returns the greatest number of them found.
805
  -- @param s The string
806
  -- @return 'nil' if not found. If found, the maximum number of equal signs found within all matches.
807
  local function has_lquote(s)
808
      local lstring_pat = '([%[%]])(=*)%1'
920 ✔
809
      local equals, new_equals, _
810
      local finish = 1
920 ✔
811
      repeat
812
          _, finish, _, new_equals = s:find(lstring_pat, finish)
1,606 ✔
813
          if new_equals then
1,606 ✔
814
              equals = max(equals or 0, #new_equals)
686 ✔
815
          end
816
      until not new_equals
1,606 ✔
817

818
      return equals
920 ✔
819
  end
820

821
  --- Quote the given string and preserve any control or escape characters, such that reloading the string in Lua returns the same result.
822
  -- @param s The string to be quoted.
823
  -- @return The quoted string.
824
  function stringx.quote_string(s)
×
825
      assert_string(1,s)
920 ✔
826
      -- Find out if there are any embedded long-quote sequences that may cause issues.
827
      -- This is important when strings are embedded within strings, like when serializing.
828
      -- Append a closing bracket to catch unfinished long-quote sequences at the end of the string.
829
      local equal_signs = has_lquote(s .. "]")
920 ✔
830

831
      -- Note that strings containing "\r" can't be quoted using long brackets
832
      -- as Lua lexer converts all newlines to "\n" within long strings.
833
      if (s:find("\n") or equal_signs) and not s:find("\r") then
920 ✔
834
          -- If there is an embedded sequence that matches a long quote, then
835
          -- find the one with the maximum number of = signs and add one to that number.
836
          equal_signs = ("="):rep((equal_signs or -1) + 1)
238 ✔
837
          -- Long strings strip out leading newline. We want to retain that, when quoting.
838
          if s:find("^\n") then s = "\n" .. s end
238 ✔
839
          local lbracket, rbracket =
840
              "[" .. equal_signs .. "[",
238 ✔
841
              "]" .. equal_signs .. "]"
238 ✔
842
          s = lbracket .. s .. rbracket
238 ✔
843
      else
844
          -- Escape funny stuff. Lua 5.1 does not handle "\r" correctly.
845
          s = ("%q"):format(s):gsub("\r", "\\r")
682 ✔
846
      end
847
      return s
920 ✔
848
  end
849
end
850

851

852
--- Python-style formatting operator.
853
-- Calling `text.format_operator()` overloads the % operator for strings to give
854
-- Python/Ruby style formatted output.
855
-- This is extended to also do template-like substitution for map-like data.
856
--
857
-- Note this goes further than the original, and will allow these cases:
858
--
859
-- 1. a single value
860
-- 2. a list of values
861
-- 3. a map of var=value pairs
862
-- 4. a function, as in gsub
863
--
864
-- For the second two cases, it uses $-variable substitution.
865
--
866
-- When called, this function will monkey-patch the global `string` metatable by
867
-- adding a `__mod` method.
868
--
869
-- See <a href="http://lua-users.org/wiki/StringInterpolation">the lua-users wiki</a>
870
--
871
-- @usage
872
-- require 'pl.text'.format_operator()
873
-- local out1 = '%s = %5.3f' % {'PI',math.pi}                   --> 'PI = 3.142'
874
-- local out2 = '$name = $value' % {name='dog',value='Pluto'}   --> 'dog = Pluto'
875
function stringx.format_operator()
×
876

877
  local format = string.format
14 ✔
878

879
  -- a more forgiving version of string.format, which applies
880
  -- tostring() to any value with a %s format.
881
  local function formatx (fmt,...)
882
    local args = pack(...)
42 ✔
883
    local i = 1
42 ✔
884
    for p in fmt:gmatch('%%.') do
98 ✔
885
      if p == '%s' and type(args[i]) ~= 'string' then
56 ✔
886
        args[i] = tostring(args[i])
18 ✔
887
      end
888
      i = i + 1
56 ✔
889
    end
890
    return format(fmt,unpack(args))
54 ✔
891
  end
892

893
  local function basic_subst(s,t)
894
    return (s:gsub('%$([%w_]+)',t))
14 ✔
895
  end
896

897
  getmetatable("").__mod = function(a, b)
14 ✔
898
    if b == nil then
70 ✔
899
      return a
×
900
    elseif type(b) == "table" and getmetatable(b) == nil then
70 ✔
901
      if #b == 0 then -- assume a map-like table
28 ✔
902
        return _substitute(a,b,true)
14 ✔
903
      else
904
        return formatx(a,unpack(b))
18 ✔
905
      end
906
    elseif type(b) == 'function' then
42 ✔
907
      return basic_subst(a,b)
14 ✔
908
    else
909
      return formatx(a,b)
28 ✔
910
    end
911
  end
912
end
913

914
--- import the stringx functions into the global string (meta)table
915
function stringx.import()
×
916
    utils.import(stringx,string)
×
917
end
918

919
return stringx
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc