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

lunarmodules / Penlight / 44933622008

21 Nov 2026 06:05PM UTC coverage: 90.342%. Remained the same
44933622008

push

github

web-flow
fix(stringx): keep the whole delimiter in (r)partition (#540)

1 of 1 new or added line in 1 file covered. (100.0%)

10 existing lines in 1 file now uncovered.

5575 of 6171 relevant lines covered (90.34%)

897.44 hits per line

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

96.45
/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'
684 ✔
12
local is_callable = require 'pl.types'.is_callable
684 ✔
13
local string = string
684 ✔
14
local find = string.find
684 ✔
15
local type,setmetatable,ipairs = type,setmetatable,ipairs
684 ✔
16
local error = error
684 ✔
17
local gsub = string.gsub
684 ✔
18
local rep = string.rep
684 ✔
19
local sub = string.sub
684 ✔
20
local reverse = string.reverse
684 ✔
21
local concat = table.concat
684 ✔
22
local append = table.insert
684 ✔
23
local escape = utils.escape
684 ✔
24
local ceil, max = math.ceil, math.max
684 ✔
25
local assert_arg,usplit = utils.assert_arg,utils.split
684 ✔
26
local lstrip
27
local unpack = utils.unpack
684 ✔
28
local pack = utils.pack
684 ✔
29

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

34
local function non_empty(s)
35
    return #s > 0
304 ✔
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')
304 ✔
40
end
41

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

46
local stringx = {}
684 ✔
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)
684 ✔
55
    assert_string(1,s)
114 ✔
56
    return find(s,'^%a+$') == 1
114 ✔
57
end
58

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

66
--- does s only contain alphanumeric characters?
67
-- @string s a string
68
function stringx.isalnum(s)
684 ✔
69
    assert_string(1,s)
57 ✔
70
    return find(s,'^%w+$') == 1
57 ✔
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)
684 ✔
77
    assert_string(1,s)
76 ✔
78
    return find(s,'^%s+$') == 1
76 ✔
79
end
80

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

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

95
local function raw_startswith(s, prefix)
96
    return find(s,prefix,1,true) == 1
285 ✔
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
399 ✔
101
end
102

103
local function test_affixes(s, affixes, fn)
104
    if type(affixes) == 'string' then
608 ✔
105
        return fn(s,affixes)
494 ✔
106
    elseif type(affixes) == 'table' then
114 ✔
107
        for _,affix in ipairs(affixes) do
228 ✔
108
            if fn(s,affix) then return true end
240 ✔
109
        end
110
        return false
38 ✔
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)
684 ✔
120
    assert_string(1,s)
247 ✔
121
    return test_affixes(s,prefix,raw_startswith)
247 ✔
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)
684 ✔
128
    assert_string(1,s)
361 ✔
129
    return test_affixes(s,suffix,raw_endswith)
361 ✔
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)
684 ✔
141
    assert_string(1,s)
19 ✔
142
    return concat(seq,s)
19 ✔
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)
684 ✔
154
    assert_string(1, s)
171 ✔
155
    local res = {}
171 ✔
156
    local pos = 1
171 ✔
157
    while true do
158
        local line_end_pos = find(s, '[\r\n]', pos)
437 ✔
159
        if not line_end_pos then
437 ✔
160
            break
90 ✔
161
        end
162

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

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

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

177
    if pos <= #s then
171 ✔
178
        append(res, sub(s, pos))
24 ✔
179
    end
180
    return makelist(res)
171 ✔
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)
684 ✔
193
    assert_string(1,s)
532 ✔
194
    local plain = true
532 ✔
195
    if not re then -- default spaces
532 ✔
196
        s = lstrip(s)
480 ✔
197
        plain = false
380 ✔
198
    end
199
    local res = usplit(s,re,plain,n)
532 ✔
200
    if re and re ~= '' and
532 ✔
201
       find(s,re,-#re,true) and
114 ✔
202
       (n or math.huge) > #res then
57 ✔
203
        res[#res+1] = ""
38 ✔
204
    end
205
    return makelist(res)
532 ✔
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)
684 ✔
216
  assert_string(1,s)
152 ✔
217
  tabsize = tabsize or 8
152 ✔
218
  return (s:gsub("([^\t\r\n]*)\t", function(before_tab)
304 ✔
219
      if tabsize == 0 then
171 ✔
220
        return before_tab
19 ✔
221
      else
222
        return before_tab .. (" "):rep(tabsize - #before_tab % tabsize)
152 ✔
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
456 ✔
232
    last = last or #s
456 ✔
233
    if sub == '' then return last+1,last-first+1 end
456 ✔
234
    local i1,i2 = find(s,sub,first,true)
380 ✔
235
    local res
236
    local k = 0
380 ✔
237
    while i1 do
912 ✔
238
        if last and i2 > last then break end
589 ✔
239
        res = i1
532 ✔
240
        k = k + 1
532 ✔
241
        if allow_overlap then
532 ✔
242
            i1,i2 = find(s,sub,i1+1,true)
418 ✔
243
        else
244
            i1,i2 = find(s,sub,i2+1,true)
114 ✔
245
        end
246
    end
247
    return res,k
380 ✔
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)
684 ✔
257
    assert_string(1,s)
342 ✔
258
    assert_string(2,sub)
342 ✔
259
    local i1, i2 = find(s,sub,first,true)
342 ✔
260

261
    if i1 and (not last or i2 <= last) then
342 ✔
262
        return i1
266 ✔
263
    else
264
        return nil
76 ✔
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)
684 ✔
275
    assert_string(1,s)
323 ✔
276
    assert_string(2,sub)
323 ✔
277
    return (_find_all(s,sub,first,last,true))
408 ✔
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)
684 ✔
288
    assert_string(1,s)
171 ✔
289
    assert_string(2,old)
171 ✔
290
    assert_string(3,new)
171 ✔
291
    return (gsub(s,escape(old),new:gsub('%%','%%%%'),n))
216 ✔
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)
684 ✔
302
    assert_string(1,s)
133 ✔
303
    local _,k = _find_all(s,sub,1,false,allow_overlap)
133 ✔
304
    return k
133 ✔
305
end
306

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

310
local function _just(s,w,ch,left,right)
311
    local n = #s
304 ✔
312
    if w > n then
304 ✔
313
        if not ch then ch = ' ' end
190 ✔
314
        local f1,f2
315
        if left and right then
190 ✔
316
            local rn = ceil((w-n)/2)
76 ✔
317
            local ln = w - n - rn
76 ✔
318
            f1 = rep(ch,ln)
76 ✔
319
            f2 = rep(ch,rn)
76 ✔
320
        elseif right then
114 ✔
321
            f1 = rep(ch,w-n)
57 ✔
322
            f2 = ''
57 ✔
323
        else
324
            f2 = rep(ch,w-n)
57 ✔
325
            f1 = ''
57 ✔
326
        end
327
        return f1..s..f2
190 ✔
328
    else
329
        return s
114 ✔
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)
684 ✔
339
    assert_string(1,s)
95 ✔
340
    assert_arg(2,w,'number')
95 ✔
341
    return _just(s,w,ch,true,false)
95 ✔
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)
684 ✔
350
    assert_string(1,s)
95 ✔
351
    assert_arg(2,w,'number')
95 ✔
352
    return _just(s,w,ch,false,true)
95 ✔
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)
684 ✔
361
    assert_string(1,s)
114 ✔
362
    assert_arg(2,w,'number')
114 ✔
363
    return _just(s,w,ch,true,true)
114 ✔
364
end
365

366
local function _strip(s,left,right,chrs)
367
    if not chrs then
3,021 ✔
368
        chrs = '%s'
2,964 ✔
369
    else
370
        chrs = '['..escape(chrs)..']'
72 ✔
371
    end
372
    local f = 1
3,021 ✔
373
    local t
374
    if left then
3,021 ✔
375
        local i1,i2 = find(s,'^'..chrs..'*')
2,812 ✔
376
        if i2 >= i1 then
2,812 ✔
377
            f = i2+1
418 ✔
378
        end
379
    end
380
    if right then
3,021 ✔
381
        if #s < 200 then
2,432 ✔
382
            local i1,i2 = find(s,chrs..'*$',f)
2,394 ✔
383
            if i2 >= i1 then
2,394 ✔
384
                t = i1-1
361 ✔
385
            end
386
        else
387
            local rs = reverse(s)
38 ✔
388
            local i1,i2 = find(rs, '^'..chrs..'*')
38 ✔
389
            if i2 >= i1 then
38 ✔
390
                t = -i2-1
×
391
            end
392
        end
393
    end
394
    return sub(s,f,t)
3,021 ✔
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)
684 ✔
402
    assert_string(1,s)
589 ✔
403
    return _strip(s,true,false,chrs)
589 ✔
404
end
405
lstrip = stringx.lstrip
684 ✔
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)
684 ✔
412
    assert_string(1,s)
209 ✔
413
    return _strip(s,false,true,chrs)
209 ✔
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)
684 ✔
422
    assert_string(1,s)
2,223 ✔
423
    return _strip(s,true,true,chrs)
2,223 ✔
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)
684 ✔
436
    assert_string(1,s)
19 ✔
437
    return utils.splitv(s,re)
19 ✔
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)
266 ✔
444
    if not i1 or i1 == -1 then
266 ✔
445
        return p,'',''
57 ✔
446
    else
447
        if not i2 then i2 = i1 + #delim - 1 end
209 ✔
448
        return sub(p,1,i1-1),sub(p,i1,i2),sub(p,i2+1)
362 ✔
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)
684 ✔
462
    assert_string(1,s)
171 ✔
463
    assert_nonempty_string(2,ch)
171 ✔
464
    return _partition(s,ch,stringx.lfind)
152 ✔
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)
684 ✔
477
    assert_string(1,s)
133 ✔
478
    assert_nonempty_string(2,ch)
133 ✔
479
    local a,b,c = _partition(s,ch,stringx.rfind)
114 ✔
480
    if a == s then -- no match found
114 ✔
481
        return c,b,a
19 ✔
482
    end
483
    return a,b,c
95 ✔
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)
684 ✔
491
    assert_string(1,s)
76 ✔
492
    assert_arg(2,idx,'number')
76 ✔
493
    return sub(s,idx,idx)
76 ✔
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)
684 ✔
507
  assert_arg(1,s,'string')
76 ✔
508
  assert_arg(2,n,'number')
76 ✔
509
  local lines = usplit(s ,'\n')
76 ✔
510
  local prefix = string.rep(ch or ' ',n)
76 ✔
511
  for i, line in ipairs(lines) do
247 ✔
512
    lines[i] = prefix..line
171 ✔
513
  end
514
  return concat(lines,'\n')..'\n'
76 ✔
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)
684 ✔
539
  assert_arg(1,s,'string')
76 ✔
540
  local lst = usplit(s,'\n')
76 ✔
541
  if #lst>0 then
76 ✔
542
    local ind_size = math.huge
76 ✔
543
    for i, line in ipairs(lst) do
304 ✔
544
      local i1, i2 = lst[i]:find('^%s*[^%s]')
228 ✔
545
      if i1 and i2 < ind_size then
228 ✔
546
        ind_size = i2
114 ✔
547
      end
548
    end
549
    for i, line in ipairs(lst) do
304 ✔
550
      lst[i] = lst[i]:sub(ind_size, -1)
284 ✔
551
    end
552
  end
553
  return concat(lst,'\n')..'\n'
76 ✔
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,710 ✔
563
    if #words[i] > size then
1,710 ✔
564
      -- word longer than line
565
      if not breaklong then
665 ✔
566
        line[1] = words[i]
247 ✔
567
        i = i + 1
247 ✔
568
      else
569
        line[1] = words[i]:sub(1, size)
528 ✔
570
        words[i] = words[i]:sub(size + 1, -1)
528 ✔
571
      end
572
    else
573
      local len = 0
1,045 ✔
574
      while words[i] and (len + #words[i] <= size) or
3,420 ✔
575
            (len == 0 and #words[i] == size) do
1,670 ✔
576
        if words[i] ~= "" then
2,375 ✔
577
          line[#line+1] = words[i]
2,185 ✔
578
          len = len + #words[i] + 1
2,185 ✔
579
        end
580
        i = i + 1
2,375 ✔
581
      end
582
    end
583
    return stringx.strip(concat(line, " ")), i
2,160 ✔
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
285 ✔
597
    s = stringx.strip(s) -- remove leading/trailing whitespace
356 ✔
598
    if s == "" then
285 ✔
599
      return { "" }
38 ✔
600
    end
601
    width = width or 70
247 ✔
602
    local out = {}
247 ✔
603
    local words = usplit(s, "%s")
247 ✔
604
    local i = 1
247 ✔
605
    while words[i] do
1,957 ✔
606
      out[#out+1], i = buildline(words, i, width, breaklong)
2,160 ✔
607
    end
608
    return makelist(out)
247 ✔
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)
684 ✔
619
  return concat(stringx.wrap(s,width,breaklong),'\n') .. '\n'
24 ✔
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
72 ✔
UNCOV
629
    subst = tbl
×
630
  else
631
    function subst(f)
48 ✔
632
      local s = tbl[f]
76 ✔
633
      if not s then
76 ✔
UNCOV
634
        if safe then
×
UNCOV
635
          return f
×
636
        else
637
          error("not present in table "..f)
×
638
        end
639
      else
640
        return s
76 ✔
641
      end
642
    end
643
  end
644
  local res = gsub(s,'%${([%w_]+)}',subst)
57 ✔
645
  return (gsub(res,'%$([%w_]+)',subst))
57 ✔
646
end
647

648

649

650
local Template = {}
684 ✔
651
stringx.Template = Template
684 ✔
652
Template.__index = Template
684 ✔
653
setmetatable(Template, {
1,368 ✔
654
  __call = function(obj,tmpl)
655
    return Template.new(tmpl)
57 ✔
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)
684 ✔
665
  assert_arg(1,tmpl,'string')
57 ✔
666
  local res = {}
57 ✔
667
  res.tmpl = tmpl
57 ✔
668
  setmetatable(res,Template)
57 ✔
669
  return res
57 ✔
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)
684 ✔
677
  assert_arg(1,tbl,'table')
38 ✔
678
  return _substitute(self.tmpl,tbl,false)
38 ✔
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)
684 ✔
UNCOV
686
  assert_arg(1,tbl,'table')
×
UNCOV
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)
684 ✔
698
  assert_arg(1,tbl,'table')
19 ✔
699
  if not self.strings then
19 ✔
700
    self.strings = usplit(self.tmpl,'\n')
24 ✔
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)
99 ✔
708
      local subtmpl
709
      local s = tbl[f]
19 ✔
710
      if not s then error("not present in table "..f) end
19 ✔
711
      if getmetatable(s) == Template then
19 ✔
UNCOV
712
        subtmpl = s
×
UNCOV
713
        s = s.tmpl
×
714
      else
715
        s = tostring(s)
19 ✔
716
      end
717
      if s:find '\n' then
19 ✔
718
        local lines = usplit(s, '\n')
19 ✔
719
        for i, line in ipairs(lines) do
76 ✔
720
          lines[i] = sp..line
57 ✔
721
        end
722
        s = concat(lines, '\n') .. '\n'
19 ✔
723
      end
724
      if subtmpl then
19 ✔
UNCOV
725
        return _substitute(s, tbl)
×
726
      else
727
        return s
19 ✔
728
      end
729
    end)
730
  end
731

732
  local lines = {}
19 ✔
733
  for i, line in ipairs(self.strings) do
76 ✔
734
    lines[i] = subst(line)
72 ✔
735
  end
736
  return concat(lines,'\n')..'\n'
19 ✔
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)
684 ✔
754
    assert_string(1,s)
57 ✔
755
    if not s:find '\n$' then s = s..'\n' end
57 ✔
756
    return s:gmatch('([^\n]*)\n')
57 ✔
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)
684 ✔
765
    assert_string(1,s)
57 ✔
766
    return (s:gsub('(%S)(%S*)',function(f,r)
114 ✔
767
        return f:upper()..r:lower()
116 ✔
768
    end))
769
end
770

771
stringx.capitalize = stringx.title
684 ✔
772

773
do
774
  local ellipsis = '...'
684 ✔
775
  local n_ellipsis = #ellipsis
684 ✔
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)
684 ✔
786
      assert_string(1,s)
342 ✔
787
      if #s > w then
342 ✔
788
          if w < n_ellipsis then return ellipsis:sub(1,w) end
209 ✔
789
          if tail then
95 ✔
790
              local i = #s - w + 1 + n_ellipsis
38 ✔
791
              return ellipsis .. s:sub(i)
46 ✔
792
          else
793
              return s:sub(1,w-n_ellipsis) .. ellipsis
68 ✔
794
          end
795
      end
796
      return s
133 ✔
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'
1,078 ✔
809
      local equals, new_equals, _
810
      local finish = 1
1,078 ✔
811
      repeat
812
          _, finish, _, new_equals = s:find(lstring_pat, finish)
2,009 ✔
813
          if new_equals then
2,009 ✔
814
              equals = max(equals or 0, #new_equals)
931 ✔
815
          end
816
      until not new_equals
2,009 ✔
817

818
      return equals
1,078 ✔
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)
684 ✔
825
      assert_string(1,s)
1,078 ✔
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 .. "]")
1,078 ✔
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
1,078 ✔
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)
323 ✔
837
          -- Long strings strip out leading newline. We want to retain that, when quoting.
838
          if s:find("^\n") then s = "\n" .. s end
323 ✔
839
          local lbracket, rbracket =
840
              "[" .. equal_signs .. "[",
323 ✔
841
              "]" .. equal_signs .. "]"
323 ✔
842
          s = lbracket .. s .. rbracket
323 ✔
843
      else
844
          -- Escape funny stuff. Lua 5.1 does not handle "\r" correctly.
845
          s = ("%q"):format(s):gsub("\r", "\\r")
755 ✔
846
      end
847
      return s
1,078 ✔
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()
684 ✔
876

877
  local format = string.format
19 ✔
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(...)
57 ✔
883
    local i = 1
57 ✔
884
    for p in fmt:gmatch('%%.') do
133 ✔
885
      if p == '%s' and type(args[i]) ~= 'string' then
76 ✔
886
        args[i] = tostring(args[i])
24 ✔
887
      end
888
      i = i + 1
76 ✔
889
    end
890
    return format(fmt,unpack(args))
72 ✔
891
  end
892

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

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

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

919
return stringx
684 ✔
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