Debian Codegraph @

texmf-dist/tex/luatex/lualibs/lualibs-util-str.lua

raw
1 if not modules then modules = { } end modules ['util-str'] = {
2 version = 1.001,
3 comment = "companion to luat-lib.mkiv",
4 author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
5 copyright = "PRAGMA ADE / ConTeXt Development Team",
6 license = "see context related readme files"
7 }
8
9 utilities = utilities or { }
10 utilities.strings = utilities.strings or { }
11 local strings = utilities.strings
12
13 local format, gsub, rep, sub, find, char = string.format, string.gsub, string.rep, string.sub, string.find, string.char
14 local load, dump = load, string.dump
15 local tonumber, type, tostring, next, setmetatable = tonumber, type, tostring, next, setmetatable
16 local unpack, concat = table.unpack, table.concat
17 local P, V, C, S, R, Ct, Cs, Cp, Carg, Cc = lpeg.P, lpeg.V, lpeg.C, lpeg.S, lpeg.R, lpeg.Ct, lpeg.Cs, lpeg.Cp, lpeg.Carg, lpeg.Cc
18 local patterns, lpegmatch = lpeg.patterns, lpeg.match
19 local tsplitat = lpeg.tsplitat
20 local utfchar, utfbyte, utflen = utf.char, utf.byte, utf.len
21
22 ----- loadstripped = utilities.lua.loadstripped
23 ----- setmetatableindex = table.setmetatableindex
24
25 local loadstripped = function(str,shortcuts)
26 if shortcuts then
27 return load(dump(load(str),true),nil,nil,shortcuts)
28 else
29 return load(dump(load(str),true))
30 end
31 end
32
33 -- todo: make a special namespace for the formatter
34
35 if not number then number = { } end -- temp hack for luatex-fonts
36
37 local stripzero = patterns.stripzero
38 local stripzeros = patterns.stripzeros
39 local newline = patterns.newline
40 local endofstring = patterns.endofstring
41 local anything = patterns.anything
42 local whitespace = patterns.whitespace
43 local space = patterns.space
44 local spacer = patterns.spacer
45 local spaceortab = patterns.spaceortab
46 local digit = patterns.digit
47 local sign = patterns.sign
48 local period = patterns.period
49
50 -- local function points(n)
51 -- n = tonumber(n)
52 -- return (not n or n == 0) and "0pt" or lpegmatch(stripzeros,format("%.5fpt",n/65536))
53 -- end
54
55 -- local function basepoints(n)
56 -- n = tonumber(n)
57 -- return (not n or n == 0) and "0bp" or lpegmatch(stripzeros,format("%.5fbp", n*(7200/7227)/65536))
58 -- end
59
60 local ptf = 1 / 65536
61 local bpf = (7200/7227) / 65536
62
63 local function points(n)
64 if n == 0 then
65 return "0pt"
66 end
67 n = tonumber(n)
68 if not n or n == 0 then
69 return "0pt"
70 end
71 n = n * ptf
72 if n % 1 == 0 then
73 return format("%ipt",n)
74 else
75 return lpegmatch(stripzeros,format("%.5fpt",n)) -- plural as we need to keep the pt
76 end
77 end
78
79 local function nupoints(n)
80 if n == 0 then
81 return "0"
82 end
83 n = tonumber(n)
84 if not n or n == 0 then
85 return "0"
86 end
87 n = n * ptf
88 if n % 1 == 0 then
89 return format("%i",n)
90 else
91 return format("%.5f",n) -- no strip
92 end
93 end
94
95 local function basepoints(n)
96 if n == 0 then
97 return "0bp"
98 end
99 n = tonumber(n)
100 if not n or n == 0 then
101 return "0bp"
102 end
103 n = n * bpf
104 if n % 1 == 0 then
105 return format("%ibp",n)
106 else
107 return lpegmatch(stripzeros,format("%.5fbp",n)) -- plural as we need to keep the pt
108 end
109 end
110
111 local function nubasepoints(n)
112 if n == 0 then
113 return "0"
114 end
115 n = tonumber(n)
116 if not n or n == 0 then
117 return "0"
118 end
119 n = n * bpf
120 if n % 1 == 0 then
121 return format("%i",n)
122 else
123 return format("%.5f",n) -- no strip
124 end
125 end
126
127 number.points = points
128 number.nupoints = nupoints
129 number.basepoints = basepoints
130 number.nubasepoints = nubasepoints
131
132 -- str = " \n \ntest \n test\ntest "
133 -- print("["..string.gsub(string.collapsecrlf(str),"\n","+").."]")
134
135 local rubish = spaceortab^0 * newline
136 local anyrubish = spaceortab + newline
137 local stripped = (spaceortab^1 / "") * newline
138 local leading = rubish^0 / ""
139 local trailing = (anyrubish^1 * endofstring) / ""
140 local redundant = rubish^3 / "\n"
141
142 local pattern = Cs(leading * (trailing + redundant + stripped + anything)^0)
143
144 function strings.collapsecrlf(str)
145 return lpegmatch(pattern,str)
146 end
147
148 -- The following functions might end up in another namespace.
149
150 local repeaters = { } -- watch how we also moved the -1 in depth-1 to the creator
151
152 function strings.newrepeater(str,offset)
153 offset = offset or 0
154 local s = repeaters[str]
155 if not s then
156 s = { }
157 repeaters[str] = s
158 end
159 local t = s[offset]
160 if t then
161 return t
162 end
163 t = { }
164 setmetatable(t, { __index = function(t,k)
165 if not k then
166 return ""
167 end
168 local n = k + offset
169 local s = n > 0 and rep(str,n) or ""
170 t[k] = s
171 return s
172 end })
173 s[offset] = t
174 return t
175 end
176
177 -- local dashes = strings.newrepeater("--",-1)
178 -- print(dashes[2],dashes[3],dashes[1])
179
180 local extra, tab, start = 0, 0, 4, 0
181
182 local nspaces = strings.newrepeater(" ")
183
184 string.nspaces = nspaces
185
186 local pattern =
187 Carg(1) / function(t)
188 extra, tab, start = 0, t or 7, 1
189 end
190 * Cs((
191 Cp() * patterns.tab / function(position)
192 local current = (position - start + 1) + extra
193 local spaces = tab-(current-1) % tab
194 if spaces > 0 then
195 extra = extra + spaces - 1
196 return nspaces[spaces] -- rep(" ",spaces)
197 else
198 return ""
199 end
200 end
201 + newline * Cp() / function(position)
202 extra, start = 0, position
203 end
204 + anything
205 )^1)
206
207 function strings.tabtospace(str,tab)
208 -- no real gain in first checking if a \t is there
209 return lpegmatch(pattern,str,1,tab or 7)
210 end
211
212 function string.utfpadding(s,n)
213 if not n or n == 0 then
214 return ""
215 end
216 local l = utflen(s)
217 if n > 0 then
218 return nspaces[n-l]
219 else
220 return nspaces[-n-l]
221 end
222 end
223
224 -- local t = {
225 -- "1234567123456712345671234567",
226 -- "\tb\tc",
227 -- "a\tb\tc",
228 -- "aa\tbb\tcc",
229 -- "aaa\tbbb\tccc",
230 -- "aaaa\tbbbb\tcccc",
231 -- "aaaaa\tbbbbb\tccccc",
232 -- "aaaaaa\tbbbbbb\tcccccc\n aaaaaa\tbbbbbb\tcccccc",
233 -- "one\n two\nxxx three\nxx four\nx five\nsix",
234 -- }
235 -- for k=1,#t do
236 -- print(strings.tabtospace(t[k]))
237 -- end
238
239 -- todo: lpeg
240
241 -- function strings.striplong(str) -- strips all leading spaces
242 -- str = gsub(str,"^%s*","")
243 -- str = gsub(str,"[\n\r]+ *","\n")
244 -- return str
245 -- end
246
247 local optionalspace = spacer^0
248 local nospace = optionalspace/""
249 local endofline = nospace * newline
250
251 local stripend = (whitespace^1 * endofstring)/""
252
253 local normalline = (nospace * ((1-optionalspace*(newline+endofstring))^1) * nospace)
254
255 local stripempty = endofline^1/""
256 local normalempty = endofline^1
257 local singleempty = endofline * (endofline^0/"")
258 local doubleempty = endofline * endofline^-1 * (endofline^0/"")
259 local stripstart = stripempty^0
260
261 local intospace = whitespace^1/" "
262 local noleading = whitespace^1/""
263 local notrailing = noleading * endofstring
264
265 local p_prune_normal = Cs ( stripstart * ( stripend + normalline + normalempty )^0 )
266 local p_prune_collapse = Cs ( stripstart * ( stripend + normalline + doubleempty )^0 )
267 local p_prune_noempty = Cs ( stripstart * ( stripend + normalline + singleempty )^0 )
268 local p_prune_intospace = Cs ( noleading * ( notrailing + intospace + 1 )^0 )
269 local p_retain_normal = Cs ( ( normalline + normalempty )^0 )
270 local p_retain_collapse = Cs ( ( normalline + doubleempty )^0 )
271 local p_retain_noempty = Cs ( ( normalline + singleempty )^0 )
272 local p_collapse_all = Cs ( stripstart * ( stripend + ((whitespace+newline)^1/" ") + 1)^0 )
273
274 -- function striplines(str,prune,collapse,noempty)
275 -- if prune then
276 -- if noempty then
277 -- return lpegmatch(p_prune_noempty,str) or str
278 -- elseif collapse then
279 -- return lpegmatch(p_prune_collapse,str) or str
280 -- else
281 -- return lpegmatch(p_prune_normal,str) or str
282 -- end
283 -- else
284 -- if noempty then
285 -- return lpegmatch(p_retain_noempty,str) or str
286 -- elseif collapse then
287 -- return lpegmatch(p_retain_collapse,str) or str
288 -- else
289 -- return lpegmatch(p_retain_normal,str) or str
290 -- end
291 -- end
292 -- end
293
294 local striplinepatterns = {
295 ["prune"] = p_prune_normal,
296 ["prune and collapse"] = p_prune_collapse, -- default
297 ["prune and no empty"] = p_prune_noempty,
298 ["prune and to space"] = p_prune_intospace,
299 ["retain"] = p_retain_normal,
300 ["retain and collapse"] = p_retain_collapse,
301 ["retain and no empty"] = p_retain_noempty,
302 ["collapse all"] = p_collapse_all,
303 ["collapse"] = patterns.collapser,
304 }
305
306 setmetatable(striplinepatterns,{ __index = function(t,k) return p_prune_collapse end })
307
308 strings.striplinepatterns = striplinepatterns
309
310 function strings.striplines(str,how)
311 return str and lpegmatch(striplinepatterns[how],str) or str
312 end
313
314 function strings.collapse(str) -- maybe also in strings
315 return str and lpegmatch(p_prune_intospace,str) or str
316 end
317
318 -- local s = "\naa\n\naa\na a\n\n"
319 -- print("["..strings.striplines(s,"collapse all").."]")
320
321 -- also see: string.collapsespaces
322
323 strings.striplong = strings.striplines -- for old times sake
324
325 -- local str = table.concat( {
326 -- " ",
327 -- " aap",
328 -- " noot mies",
329 -- " ",
330 -- " ",
331 -- " zus wim jet",
332 -- "zus wim jet",
333 -- " zus wim jet",
334 -- " ",
335 -- }, "\n")
336 --
337 -- local str = table.concat( {
338 -- " aaaa",
339 -- " bb",
340 -- " cccccc",
341 -- " ",
342 -- }, "\n")
343 --
344 -- for k, v in table.sortedhash(utilities.strings.striplinepatterns) do
345 -- logs.report("stripper","method: %s, result: [[%s]]",k,utilities.strings.striplines(str,k))
346 -- end
347
348 -- inspect(strings.striplong([[
349 -- aaaa
350 -- bb
351 -- cccccc
352 -- ]]))
353
354 function strings.nice(str)
355 str = gsub(str,"[:%-+_]+"," ") -- maybe more
356 return str
357 end
358
359 -- Work in progress. Interesting is that compared to the built-in this is faster in
360 -- luatex than in luajittex where we have a comparable speed. It only makes sense
361 -- to use the formatter when a (somewhat) complex format is used a lot. Each formatter
362 -- is a function so there is some overhead and not all formatted output is worth that
363 -- overhead. Keep in mind that there is an extra function call involved. In principle
364 -- we end up with a string concatination so one could inline such a sequence but often
365 -- at the cost of less readabinity. So, it's a sort of (visual) compromise. Of course
366 -- there is the benefit of more variants. (Concerning the speed: a simple format like
367 -- %05fpt is better off with format than with a formatter, but as soon as you put
368 -- something in front formatters become faster. Passing the pt as extra argument makes
369 -- formatters behave better. Of course this is rather implementation dependent. Also,
370 -- when a specific format is only used a few times the overhead in creating it is not
371 -- compensated by speed.)
372 --
373 -- More info can be found in cld-mkiv.pdf so here I stick to a simple list.
374 --
375 -- integer %...i number
376 -- integer %...d number
377 -- unsigned %...u number -- not used
378 -- character %...c number
379 -- hexadecimal %...x number
380 -- HEXADECIMAL %...X number
381 -- octal %...o number
382 -- string %...s string number
383 -- float %...f number
384 -- checked float %...F number
385 -- exponential %...e number
386 -- exponential %...E number
387 -- stripped e %...j number
388 -- stripped E %...J number
389 -- autofloat %...g number
390 -- autofloat %...G number
391 -- utf character %...c number
392 -- force tostring %...S any
393 -- force tostring %Q any
394 -- force tonumber %N number (strip leading zeros)
395 -- signed number %I number
396 -- rounded number %r number
397 -- 0xhexadecimal %...h character number
398 -- 0xHEXADECIMAL %...H character number
399 -- U+hexadecimal %...u character number
400 -- U+HEXADECIMAL %...U character number
401 -- points %p number (scaled points)
402 -- nupoints %P number (scaled points) / without unit / always 5 decimals
403 -- basepoints %b number (scaled points)
404 -- nubasepoints %B number (scaled points) / without unit / always 5 decimals
405 -- table concat %...t table
406 -- table concat %{.}t table
407 -- serialize %...T sequenced (no nested tables)
408 -- serialize %{.}T sequenced (no nested tables)
409 -- boolean (logic) %l boolean
410 -- BOOLEAN %L boolean
411 -- whitespace %...w number
412 -- whitespace %...W (fixed)
413 -- automatic %...a 'whatever' (string, table, ...)
414 -- automatic %...A "whatever" (string, table, ...)
415 -- zap %...z skip
416 -- stripped %...N %...N
417 -- comma/period real %...m
418 -- period/comma real %...M
419 -- formatted float %...k n.m
420
421 local n = 0
422
423 -- we are somewhat sloppy in parsing prefixes as it's not that critical
424
425 -- hard to avoid but we can collect them in a private namespace if needed
426
427 -- inline the next two makes no sense as we only use this in logging
428
429 local sequenced = table.sequenced
430
431 function string.autodouble(s,sep)
432 if s == nil then
433 return '""'
434 end
435 local t = type(s)
436 if t == "number" then
437 return tostring(s) -- tostring not really needed
438 end
439 if t == "table" then
440 return ('"' .. sequenced(s,sep or ",") .. '"')
441 end
442 return ('"' .. tostring(s) .. '"')
443 end
444
445 function string.autosingle(s,sep)
446 if s == nil then
447 return "''"
448 end
449 local t = type(s)
450 if t == "number" then
451 return tostring(s) -- tostring not really needed
452 end
453 if t == "table" then
454 return ("'" .. sequenced(s,sep or ",") .. "'")
455 end
456 return ("'" .. tostring(s) .. "'")
457 end
458
459 local tracedchars = { [0] =
460 -- the regular bunch
461 "[null]", "[soh]", "[stx]", "[etx]", "[eot]", "[enq]", "[ack]", "[bel]",
462 "[bs]", "[ht]", "[lf]", "[vt]", "[ff]", "[cr]", "[so]", "[si]",
463 "[dle]", "[dc1]", "[dc2]", "[dc3]", "[dc4]", "[nak]", "[syn]", "[etb]",
464 "[can]", "[em]", "[sub]", "[esc]", "[fs]", "[gs]", "[rs]", "[us]",
465 -- plus space
466 "[space]", -- 0x20
467 }
468
469 string.tracedchars = tracedchars
470 strings.tracers = tracedchars
471
472 function string.tracedchar(b)
473 -- todo: table
474 if type(b) == "number" then
475 return tracedchars[b] or (utfchar(b) .. " (U+" .. format("%05X",b) .. ")")
476 else
477 local c = utfbyte(b)
478 return tracedchars[c] or (b .. " (U+" .. (c and format("%05X",c) or "?????") .. ")")
479 end
480 end
481
482 function number.signed(i)
483 if i > 0 then
484 return "+", i
485 else
486 return "-", -i
487 end
488 end
489
490 -- maybe to util-num
491
492 local two = digit * digit
493 local three = two * digit
494 local prefix = (Carg(1) * three)^1
495
496 local splitter = Cs (
497 (((1 - (three^1 * period))^1 + C(three)) * prefix + C((1-period)^1))
498 * (anything/"" * Carg(2)) * C(2)
499 )
500
501 local splitter3 = Cs (
502 three * prefix * endofstring +
503 two * prefix * endofstring +
504 digit * prefix * endofstring +
505 three +
506 two +
507 digit
508 )
509
510 patterns.formattednumber = splitter
511
512 function number.formatted(n,sep1,sep2)
513 if sep1 == false then
514 if type(n) == "number" then
515 n = tostring(n)
516 end
517 return lpegmatch(splitter3,n,1,sep2 or ".")
518 else
519 if type(n) == "number" then
520 n = format("%0.2f",n)
521 end
522 if sep1 == true then
523 return lpegmatch(splitter,n,1,".",",")
524 elseif sep1 == "." then
525 return lpegmatch(splitter,n,1,sep1,sep2 or ",")
526 elseif sep1 == "," then
527 return lpegmatch(splitter,n,1,sep1,sep2 or ".")
528 else
529 return lpegmatch(splitter,n,1,sep1 or ",",sep2 or ".")
530 end
531 end
532 end
533
534 -- print(number.formatted(1))
535 -- print(number.formatted(12))
536 -- print(number.formatted(123))
537 -- print(number.formatted(1234))
538 -- print(number.formatted(12345))
539 -- print(number.formatted(123456))
540 -- print(number.formatted(1234567))
541 -- print(number.formatted(12345678))
542 -- print(number.formatted(12345678,true))
543 -- print(number.formatted(1,false))
544 -- print(number.formatted(12,false))
545 -- print(number.formatted(123,false))
546 -- print(number.formatted(1234,false))
547 -- print(number.formatted(12345,false))
548 -- print(number.formatted(123456,false))
549 -- print(number.formatted(1234567,false))
550 -- print(number.formatted(12345678,false))
551 -- print(number.formatted(1234.56,"!","?"))
552
553 local p = Cs(
554 P("-")^0
555 * (P("0")^1/"")^0
556 * (1-period)^0
557 * (period * P("0")^1 * endofstring/"" + period^0)
558 * P(1-P("0")^1*endofstring)^0
559 )
560
561 function number.compactfloat(n,fmt)
562 if n == 0 then
563 return "0"
564 elseif n == 1 then
565 return "1"
566 end
567 n = lpegmatch(p,format(fmt or "%0.3f",n))
568 if n == "." or n == "" or n == "-" then
569 return "0"
570 end
571 return n
572 end
573
574 local zero = P("0")^1 / ""
575 local plus = P("+") / ""
576 local minus = P("-")
577 local separator = period
578 local trailing = zero^1 * #S("eE")
579 local exponent = (S("eE") * (plus + Cs((minus * zero^0 * endofstring)/"") + minus) * zero^0 * (endofstring * Cc("0") + anything^1))
580 local pattern_a = Cs(minus^0 * digit^1 * (separator/"" * trailing + separator * (trailing + digit)^0) * exponent)
581 local pattern_b = Cs((exponent + anything)^0)
582
583 function number.sparseexponent(f,n)
584 if not n then
585 n = f
586 f = "%e"
587 end
588 local tn = type(n)
589 if tn == "string" then -- cast to number
590 local m = tonumber(n)
591 if m then
592 return lpegmatch((f == "%e" or f == "%E") and pattern_a or pattern_b,format(f,m))
593 end
594 elseif tn == "number" then
595 return lpegmatch((f == "%e" or f == "%E") and pattern_a or pattern_b,format(f,n))
596 end
597 return tostring(n)
598 end
599
600 local hf = { }
601 local hs = { }
602
603 setmetatable(hf, { __index = function(t,k)
604 local v = "%." .. k .. "f"
605 t[k] = v
606 return v
607 end } )
608
609 setmetatable(hs, { __index = function(t,k)
610 local v = "%" .. k .. "s"
611 t[k] = v
612 return v
613 end } )
614
615 function number.formattedfloat(n,b,a)
616 local s = format(hf[a],n)
617 local l = (b or 0) + (a or 0) + 1
618 if #s < l then
619 return format(hs[l],s)
620 else
621 return s
622 end
623 end
624
625 local template = [[
626 %s
627 %s
628 return function(%s) return %s end
629 ]]
630
631 -- We only use fast serialize in controlled cases.
632
633 local pattern = Cs(Cc('"') * (
634 (1-S('"\\\n\r'))^1
635 + P('"') / '\\"'
636 + P('\\') / '\\\\'
637 + P('\n') / '\\n'
638 + P('\r') / '\\r'
639 )^0 * Cc('"'))
640
641 -- -- I need to do more experiments with this:
642 --
643 -- local pattern = Cs(Cc('"') * (
644 -- (1-S('"\\\n\r'))^1
645 -- + P('"') / '\\034'
646 -- + P('\\') / '\\092'
647 -- + P('\n') / '\\013'
648 -- + P('\r') / '\\010'
649 -- )^0 * Cc('"'))
650
651 patterns.escapedquotes = pattern
652
653 function string.escapedquotes(s)
654 return lpegmatch(pattern,s)
655 end
656
657 local pattern = (1 - P("\\"))^1 ; pattern = Cs (
658 pattern
659 * ( (P("\\") / "" * (digit^-3 / function(s) return char(tonumber(s)) end)) + pattern )^1
660 )
661
662 patterns.unescapedquotes = pattern
663
664 function string.unescapedquotes(s)
665 return lpegmatch(pattern,s) or s
666 end
667
668 -- function string.longifneeded(s)
669 -- if find(s,'["\\\n\r]') then
670 -- return "[===[" .. s .. "]===]"
671 -- else
672 -- return '"' .. s ..'"'
673 -- end
674 -- end
675
676 string.texnewlines = lpeg.replacer(patterns.newline,"\r",true)
677
678 -- print(string.escapedquotes('1\\23\n"'))
679
680 -- but for now here
681
682 local preamble = ""
683
684 local environment = {
685 global = global or _G,
686 lpeg = lpeg,
687 type = type,
688 tostring = tostring,
689 tonumber = tonumber,
690 format = string.format,
691 concat = table.concat,
692 signed = number.signed,
693 points = number.points,
694 nupoints = number.nupoints,
695 basepoints = number.basepoints,
696 nubasepoints = number.nubasepoints,
697 utfchar = utf.char,
698 utfbyte = utf.byte,
699 lpegmatch = lpeg.match,
700 nspaces = string.nspaces,
701 utfpadding = string.utfpadding,
702 tracedchar = string.tracedchar,
703 autosingle = string.autosingle,
704 autodouble = string.autodouble,
705 sequenced = table.sequenced,
706 formattednumber = number.formatted,
707 sparseexponent = number.sparseexponent,
708 formattedfloat = number.formattedfloat,
709 stripzero = patterns.stripzero,
710 stripzeros = patterns.stripzeros,
711 escapedquotes = string.escapedquotes,
712
713 FORMAT = string.f6,
714 }
715
716 -- -- --
717
718 local arguments = { "a1" } -- faster than previously used (select(n,...))
719
720 setmetatable(arguments, { __index =
721 function(t,k)
722 local v = t[k-1] .. ",a" .. k
723 t[k] = v
724 return v
725 end
726 })
727
728 local prefix_any = C((sign + space + period + digit)^0)
729 local prefix_sub = (C((sign + digit)^0) + Cc(0))
730 * period
731 * (C((sign + digit)^0) + Cc(0))
732 local prefix_tab = P("{") * C((1-P("}"))^0) * P("}") + C((1-R("az","AZ","09","%%"))^0)
733
734 -- we've split all cases as then we can optimize them (let's omit the fuzzy u)
735
736 -- todo: replace outer formats in next by ..
737
738 local format_s = function(f)
739 n = n + 1
740 if f and f ~= "" then
741 return format("format('%%%ss',a%s)",f,n)
742 else -- best no tostring in order to stay compatible (.. does a selective tostring too)
743 return format("(a%s or '')",n) -- goodie: nil check
744 end
745 end
746
747 local format_S = function(f) -- can be optimized
748 n = n + 1
749 if f and f ~= "" then
750 return format("format('%%%ss',tostring(a%s))",f,n)
751 else
752 return format("tostring(a%s)",n)
753 end
754 end
755
756 local format_right = function(f)
757 n = n + 1
758 f = tonumber(f)
759 if not f or f == 0 then
760 return format("(a%s or '')",n)
761 elseif f > 0 then
762 return format("utfpadding(a%s,%i)..a%s",n,f,n)
763 else
764 return format("a%s..utfpadding(a%s,%i)",n,n,f)
765 end
766 end
767
768 local format_left = function(f)
769 n = n + 1
770 f = tonumber(f)
771 if not f or f == 0 then
772 return format("(a%s or '')",n)
773 end
774 if f < 0 then
775 return format("utfpadding(a%s,%i)..a%s",n,-f,n)
776 else
777 return format("a%s..utfpadding(a%s,%i)",n,n,-f)
778 end
779 end
780
781 local format_q = JITSUPPORTED and function()
782 n = n + 1
783 -- lua 5.3 has a different q than lua 5.2 (which does a tostring on numbers)
784 -- return format("(a%s ~= nil and format('%%q',a%s) or '')",n,n)
785 return format("(a%s ~= nil and format('%%q',tostring(a%s)) or '')",n,n)
786 -- return format("(a%s ~= nil and escapedquotes(tostring(a%s)) or '')",n,n)
787 end or function()
788 n = n + 1
789 return format("(a%s ~= nil and format('%%q',a%s) or '')",n,n)
790 end
791
792
793 local format_Q = function() -- fast escaping
794 n = n + 1
795 -- return format("format('%%q',tostring(a%s))",n)
796 return format("escapedquotes(tostring(a%s))",n)
797 end
798
799 local format_i = function(f)
800 n = n + 1
801 if f and f ~= "" then
802 return format("format('%%%si',a%s)",f,n)
803 else
804 return format("format('%%i',a%s)",n) -- why not just tostring()
805 end
806 end
807
808 local format_d = format_i
809
810 local format_I = function(f)
811 n = n + 1
812 return format("format('%%s%%%si',signed(a%s))",f,n)
813 end
814
815 local format_f = function(f)
816 n = n + 1
817 return format("format('%%%sf',a%s)",f,n)
818 end
819
820 -- The next one formats an integer as integer and very small values as zero. This is needed
821 -- for pdf backend code.
822 --
823 -- 1.23 % 1 : 0.23
824 -- - 1.23 % 1 : 0.77
825 --
826 -- We could probably use just %s with integers but who knows what Lua 5.3 will do? So let's
827 -- for the moment use %i.
828
829 local format_F = function(f) -- beware, no cast to number
830 n = n + 1
831 if not f or f == "" then
832 return format("(((a%s > -0.0000000005 and a%s < 0.0000000005) and '0') or format((a%s %% 1 == 0) and '%%i' or '%%.9f',a%s))",n,n,n,n)
833 else
834 return format("format((a%s %% 1 == 0) and '%%i' or '%%%sf',a%s)",n,f,n)
835 end
836 end
837
838 -- if string.f9 then
839 -- format_F = function(f) -- beware, no cast to number
840 -- n = n + 1
841 -- if not f or f == "" then
842 -- return format("(((a%s > -0.0000000005 and a%s < 0.0000000005) and '0') or FORMAT(a%s))",n,n,n,n,n)
843 -- else
844 -- return format("((a%s %% 1 == 0) and format('%%i',a%s) or FORMAT(a%s,'%%%sf'))",n,n,n,f)
845 -- end
846 -- end
847 -- end
848
849 local format_k = function(b,a) -- slow
850 n = n + 1
851 return format("formattedfloat(a%s,%s,%s)",n,b or 0,a or 0)
852 end
853
854 local format_g = function(f)
855 n = n + 1
856 return format("format('%%%sg',a%s)",f,n)
857 end
858
859 local format_G = function(f)
860 n = n + 1
861 return format("format('%%%sG',a%s)",f,n)
862 end
863
864 local format_e = function(f)
865 n = n + 1
866 return format("format('%%%se',a%s)",f,n)
867 end
868
869 local format_E = function(f)
870 n = n + 1
871 return format("format('%%%sE',a%s)",f,n)
872 end
873
874 local format_j = function(f)
875 n = n + 1
876 return format("sparseexponent('%%%se',a%s)",f,n)
877 end
878
879 local format_J = function(f)
880 n = n + 1
881 return format("sparseexponent('%%%sE',a%s)",f,n)
882 end
883
884 local format_x = function(f)
885 n = n + 1
886 return format("format('%%%sx',a%s)",f,n)
887 end
888
889 local format_X = function(f)
890 n = n + 1
891 return format("format('%%%sX',a%s)",f,n)
892 end
893
894 local format_o = function(f)
895 n = n + 1
896 return format("format('%%%so',a%s)",f,n)
897 end
898
899 local format_c = function()
900 n = n + 1
901 return format("utfchar(a%s)",n)
902 end
903
904 local format_C = function()
905 n = n + 1
906 return format("tracedchar(a%s)",n)
907 end
908
909 local format_r = function(f)
910 n = n + 1
911 return format("format('%%%s.0f',a%s)",f,n)
912 end
913
914 local format_h = function(f)
915 n = n + 1
916 if f == "-" then
917 f = sub(f,2)
918 return format("format('%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f == "" and "05" or f,n,n,n)
919 else
920 return format("format('0x%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f == "" and "05" or f,n,n,n)
921 end
922 end
923
924 local format_H = function(f)
925 n = n + 1
926 if f == "-" then
927 f = sub(f,2)
928 return format("format('%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f == "" and "05" or f,n,n,n)
929 else
930 return format("format('0x%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f == "" and "05" or f,n,n,n)
931 end
932 end
933
934 local format_u = function(f)
935 n = n + 1
936 if f == "-" then
937 f = sub(f,2)
938 return format("format('%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f == "" and "05" or f,n,n,n)
939 else
940 return format("format('u+%%%sx',type(a%s) == 'number' and a%s or utfbyte(a%s))",f == "" and "05" or f,n,n,n)
941 end
942 end
943
944 local format_U = function(f)
945 n = n + 1
946 if f == "-" then
947 f = sub(f,2)
948 return format("format('%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f == "" and "05" or f,n,n,n)
949 else
950 return format("format('U+%%%sX',type(a%s) == 'number' and a%s or utfbyte(a%s))",f == "" and "05" or f,n,n,n)
951 end
952 end
953
954 local format_p = function()
955 n = n + 1
956 return format("points(a%s)",n)
957 end
958
959 local format_P = function()
960 n = n + 1
961 return format("nupoints(a%s)",n)
962 end
963
964 local format_b = function()
965 n = n + 1
966 return format("basepoints(a%s)",n)
967 end
968
969 local format_B = function()
970 n = n + 1
971 return format("nubasepoints(a%s)",n)
972 end
973
974 local format_t = function(f)
975 n = n + 1
976 if f and f ~= "" then
977 return format("concat(a%s,%q)",n,f)
978 else
979 return format("concat(a%s)",n)
980 end
981 end
982
983 local format_T = function(f)
984 n = n + 1
985 if f and f ~= "" then
986 return format("sequenced(a%s,%q)",n,f)
987 else
988 return format("sequenced(a%s)",n)
989 end
990 end
991
992 local format_l = function()
993 n = n + 1
994 return format("(a%s and 'true' or 'false')",n)
995 end
996
997 local format_L = function()
998 n = n + 1
999 return format("(a%s and 'TRUE' or 'FALSE')",n)
1000 end
1001
1002 local format_n = function() -- strips leading and trailing zeros and removes .0, beware: can produce e notation
1003 n = n + 1
1004 return format("((a%s %% 1 == 0) and format('%%i',a%s) or tostring(a%s))",n,n,n)
1005 end
1006
1007 -- local format_N = function() -- strips leading and trailing zeros (also accepts string)
1008 -- n = n + 1
1009 -- return format("tostring(tonumber(a%s) or a%s)",n,n)
1010 -- end
1011
1012 -- local format_N = function(f) -- strips leading and trailing zeros
1013 -- n = n + 1
1014 -- -- stripzero (singular) as we only have a number
1015 -- if not f or f == "" then
1016 -- return format("(((a%s > -0.0000000005 and a%s < 0.0000000005) and '0') or ((a%s %% 1 == 0) and format('%%i',a%s)) or lpegmatch(stripzero,format('%%.9f',a%s)))",n,n,n,n,n)
1017 -- else
1018 -- return format("(((a%s %% 1 == 0) and format('%%i',a%s)) or lpegmatch(stripzero,format('%%%sf',a%s)))",n,n,f,n)
1019 -- end
1020 -- end
1021
1022 -- local format_N = function(f) -- strips leading and trailing zeros
1023 -- n = n + 1
1024 -- -- stripzero (singular) as we only have a number
1025 -- if not f or f == "" then
1026 -- return format("(((a%s %% 1 == 0) and format('%%i',a%s)) or ((a%s > -0.0000000005 and a%s < 0.0000000005) and '0') or lpegmatch(stripzero,format('%%.9f',a%s)))",n,n,n,n,n)
1027 -- else
1028 -- return format("(((a%s %% 1 == 0) and format('%%i',a%s)) or lpegmatch(stripzero,format('%%%sf',a%s)))",n,n,f,n)
1029 -- end
1030 -- end
1031
1032 local format_N if environment.FORMAT then
1033
1034 format_N = function(f)
1035 n = n + 1
1036 if not f or f == "" then
1037 return format("FORMAT(a%s,'%%.9f')",n)
1038 elseif f == ".6" or f == "0.6" then
1039 return format("FORMAT(a%s)",n)
1040 else
1041 return format("FORMAT(a%s,'%%%sf')",n,f)
1042 end
1043 end
1044
1045 else
1046
1047 format_N = function(f) -- strips leading and trailing zeros
1048 n = n + 1
1049 -- stripzero (singular) as we only have a number
1050 if not f or f == "" then
1051 f = ".9"
1052 end -- always a leading number !
1053 return format("(((a%s %% 1 == 0) and format('%%i',a%s)) or lpegmatch(stripzero,format('%%%sf',a%s)))",n,n,f,n)
1054 end
1055
1056 end
1057
1058 local format_a = function(f)
1059 n = n + 1
1060 if f and f ~= "" then
1061 return format("autosingle(a%s,%q)",n,f)
1062 else
1063 return format("autosingle(a%s)",n)
1064 end
1065 end
1066
1067 local format_A = function(f)
1068 n = n + 1
1069 if f and f ~= "" then
1070 return format("autodouble(a%s,%q)",n,f)
1071 else
1072 return format("autodouble(a%s)",n)
1073 end
1074 end
1075
1076 local format_w = function(f) -- handy when doing depth related indent
1077 n = n + 1
1078 f = tonumber(f)
1079 if f then -- not that useful
1080 return format("nspaces[%s+a%s]",f,n) -- no real need for tonumber
1081 else
1082 return format("nspaces[a%s]",n) -- no real need for tonumber
1083 end
1084 end
1085
1086 local format_W = function(f) -- handy when doing depth related indent
1087 return format("nspaces[%s]",tonumber(f) or 0)
1088 end
1089
1090 local format_m = function(f)
1091 n = n + 1
1092 if not f or f == "" then
1093 f = ","
1094 end
1095 if f == "0" then
1096 return format([[formattednumber(a%s,false)]],n)
1097 else
1098 return format([[formattednumber(a%s,%q,".")]],n,f)
1099 end
1100 end
1101
1102 local format_M = function(f)
1103 n = n + 1
1104 if not f or f == "" then
1105 f = "."
1106 end
1107 if f == "0" then
1108 return format([[formattednumber(a%s,false)]],n)
1109 else
1110 return format([[formattednumber(a%s,%q,",")]],n,f)
1111 end
1112 end
1113
1114 --
1115
1116 local format_z = function(f)
1117 n = n + (tonumber(f) or 1)
1118 return "''" -- okay, not that efficient to append '' but a special case anyway
1119 end
1120
1121 --
1122
1123 -- local strip
1124 --
1125 -- local format_Z = function(f)
1126 -- n = n + 1
1127 -- if not f or f == "" then
1128 -- f = ".9"
1129 -- end
1130 -- return format("(((a%s %% 1 == 0) and format('%%i',a%s)) or (strip and lpegmatch(stripzero,format('%%%sf',a%s))) or format('%%%sf',a%s))",n,n,f,n,f,n)
1131 -- end
1132 --
1133 -- function strings.stripformatterzeros()
1134 -- strip = true
1135 -- end
1136
1137 -- add(formatters,"texexp", [[texexp(...)]], "local texexp = metapost.texexp")
1138 --
1139 -- add(formatters,"foo:bar",[[foo(...)]], { foo = function(...) print(...) return "!" end })
1140 -- print(string.formatters["foo %3!foo:bar! bar"](1,2,3))
1141
1142
1143 local format_rest = function(s)
1144 return format("%q",s) -- catches " and \n and such
1145 end
1146
1147 local format_extension = function(extensions,f,name)
1148 local extension = extensions[name] or "tostring(%s)"
1149 local f = tonumber(f) or 1
1150 local w = find(extension,"%.%.%.")
1151 if f == 0 then
1152 if w then
1153 extension = gsub(extension,"%.%.%.","")
1154 end
1155 return extension
1156 elseif f == 1 then
1157 if w then
1158 extension = gsub(extension,"%.%.%.","%%s")
1159 end
1160 n = n + 1
1161 local a = "a" .. n
1162 return format(extension,a,a) -- maybe more times?
1163 elseif f < 0 then
1164 if w then
1165 -- not supported
1166 extension = gsub(extension,"%.%.%.","")
1167 return extension
1168 else
1169 local a = "a" .. (n + f + 1)
1170 return format(extension,a,a)
1171 end
1172 else
1173 if w then
1174 extension = gsub(extension,"%.%.%.",rep("%%s,",f-1).."%%s")
1175 end
1176 -- we could fill an array and then n = n + 1 unpack(t,n,n+f) but as we
1177 -- cache we don't save much and there are hardly any extensions anyway
1178 local t = { }
1179 for i=1,f do
1180 n = n + 1
1181 -- t[#t+1] = "a" .. n
1182 t[i] = "a" .. n
1183 end
1184 return format(extension,unpack(t))
1185 end
1186 end
1187
1188 -- aA b cC d eE f gG hH iI jJ lL mM N o p qQ r sS tT uU wW xX z
1189
1190 -- extensions : %!tag!
1191
1192 -- can be made faster but not called that often
1193
1194 local builder = Cs { "start",
1195 start = (
1196 (
1197 P("%") / ""
1198 * (
1199 V("!") -- new
1200 + V("s") + V("q")
1201 + V("i") + V("d")
1202 + V("f") + V("F") + V("g") + V("G") + V("e") + V("E")
1203 + V("x") + V("X") + V("o")
1204 --
1205 + V("c")
1206 + V("C")
1207 + V("S") -- new
1208 + V("Q") -- new
1209 + V("n") -- new
1210 + V("N") -- new
1211 + V("k") -- new
1212 --
1213 + V("r")
1214 + V("h") + V("H") + V("u") + V("U")
1215 + V("p") + V("P") + V("b") + V("B")
1216 + V("t") + V("T")
1217 + V("l") + V("L")
1218 + V("I")
1219 + V("w") -- new
1220 + V("W") -- new
1221 + V("a") -- new
1222 + V("A") -- new
1223 + V("j") + V("J") -- stripped e E
1224 + V("m") + V("M") -- new (formatted number)
1225 + V("z") -- new
1226 --
1227 + V(">") -- left padding
1228 + V("<") -- right padding
1229 --
1230 -- + V("?") -- ignored, probably messed up %
1231 )
1232 + V("*")
1233 )
1234 * (endofstring + Carg(1))
1235 )^0,
1236 --
1237 ["s"] = (prefix_any * P("s")) / format_s, -- %s => regular %s (string)
1238 ["q"] = (prefix_any * P("q")) / format_q, -- %q => regular %q (quoted string)
1239 ["i"] = (prefix_any * P("i")) / format_i, -- %i => regular %i (integer)
1240 ["d"] = (prefix_any * P("d")) / format_d, -- %d => regular %d (integer)
1241 ["f"] = (prefix_any * P("f")) / format_f, -- %f => regular %f (float)
1242 ["F"] = (prefix_any * P("F")) / format_F, -- %F => regular %f (float) but 0/1 check
1243 ["g"] = (prefix_any * P("g")) / format_g, -- %g => regular %g (float)
1244 ["G"] = (prefix_any * P("G")) / format_G, -- %G => regular %G (float)
1245 ["e"] = (prefix_any * P("e")) / format_e, -- %e => regular %e (float)
1246 ["E"] = (prefix_any * P("E")) / format_E, -- %E => regular %E (float)
1247 ["x"] = (prefix_any * P("x")) / format_x, -- %x => regular %x (hexadecimal)
1248 ["X"] = (prefix_any * P("X")) / format_X, -- %X => regular %X (HEXADECIMAL)
1249 ["o"] = (prefix_any * P("o")) / format_o, -- %o => regular %o (octal)
1250 --
1251 ["S"] = (prefix_any * P("S")) / format_S, -- %S => %s (tostring)
1252 ["Q"] = (prefix_any * P("Q")) / format_Q, -- %Q => %q (tostring)
1253 ["n"] = (prefix_any * P("n")) / format_n, -- %n => tonumber (strips leading and trailing zeros, as well as .0, expects number)
1254 ["N"] = (prefix_any * P("N")) / format_N, -- %N => tonumber (strips leading and trailing zeros, also takes string)
1255 ["k"] = (prefix_sub * P("k")) / format_k, -- %k => like f but with n.m
1256 ["c"] = (prefix_any * P("c")) / format_c, -- %c => utf character (extension to regular)
1257 ["C"] = (prefix_any * P("C")) / format_C, -- %c => U+.... utf character
1258 --
1259 ["r"] = (prefix_any * P("r")) / format_r, -- %r => round
1260 ["h"] = (prefix_any * P("h")) / format_h, -- %h => 0x0a1b2 (when - no 0x) was v
1261 ["H"] = (prefix_any * P("H")) / format_H, -- %H => 0x0A1B2 (when - no 0x) was V
1262 ["u"] = (prefix_any * P("u")) / format_u, -- %u => u+0a1b2 (when - no u+)
1263 ["U"] = (prefix_any * P("U")) / format_U, -- %U => U+0A1B2 (when - no U+)
1264 ["p"] = (prefix_any * P("p")) / format_p, -- %p => 12.345pt
1265 ["P"] = (prefix_any * P("P")) / format_P, -- %p => 12.345
1266 ["b"] = (prefix_any * P("b")) / format_b, -- %b => 12.342bp
1267 ["B"] = (prefix_any * P("B")) / format_B, -- %b => 12.342
1268 ["t"] = (prefix_tab * P("t")) / format_t, -- %t => concat
1269 ["T"] = (prefix_tab * P("T")) / format_T, -- %t => sequenced
1270 ["l"] = (prefix_any * P("l")) / format_l, -- %l => boolean
1271 ["L"] = (prefix_any * P("L")) / format_L, -- %L => BOOLEAN
1272 ["I"] = (prefix_any * P("I")) / format_I, -- %I => signed integer
1273 --
1274 ["w"] = (prefix_any * P("w")) / format_w, -- %w => n spaces (optional prefix is added)
1275 ["W"] = (prefix_any * P("W")) / format_W, -- %W => mandate prefix, no specifier
1276 --
1277 ["j"] = (prefix_any * P("j")) / format_j, -- %j => %e (float) stripped exponent (irrational)
1278 ["J"] = (prefix_any * P("J")) / format_J, -- %J => %E (float) stripped exponent (irrational)
1279 --
1280 ["m"] = (prefix_any * P("m")) / format_m, -- %m => xxx.xxx.xxx,xx (optional prefix instead of .)
1281 ["M"] = (prefix_any * P("M")) / format_M, -- %M => xxx,xxx,xxx.xx (optional prefix instead of ,)
1282 --
1283 ["z"] = (prefix_any * P("z")) / format_z, -- %z => skip n arguments
1284 -- ["Z"] = (prefix_any * P("Z")) / format_Z, -- %Z => optionally strip zeros
1285 --
1286 ["a"] = (prefix_any * P("a")) / format_a, -- %a => '...' (forces tostring)
1287 ["A"] = (prefix_any * P("A")) / format_A, -- %A => "..." (forces tostring)
1288 --
1289 ["<"] = (prefix_any * P("<")) / format_left,
1290 [">"] = (prefix_any * P(">")) / format_right,
1291 --
1292 ["*"] = Cs(((1-P("%"))^1 + P("%%")/"%%")^1) / format_rest, -- rest (including %%)
1293 ["?"] = Cs(((1-P("%"))^1 )^1) / format_rest, -- rest (including %%)
1294 --
1295 ["!"] = Carg(2) * prefix_any * P("!") * C((1-P("!"))^1) * P("!") / format_extension,
1296 }
1297
1298 -- We can be clever and only alias what is needed:
1299
1300 local xx = setmetatable({ }, { __index = function(t,k) local v = format("%02x",k) t[k] = v return v end })
1301 local XX = setmetatable({ }, { __index = function(t,k) local v = format("%02X",k) t[k] = v return v end })
1302
1303 local preset = {
1304 ["%02x"] = function(n) return xx[n] end,
1305 ["%02X"] = function(n) return XX[n] end,
1306 }
1307
1308 local direct =
1309 P("%") * (sign + space + period + digit)^0 * S("sqidfgGeExXo") * endofstring
1310 / [[local format = string.format return function(str) return format("%0",str) end]]
1311
1312 local function make(t,str)
1313 local f = preset[str]
1314 if f then
1315 return f
1316 end
1317 local p = lpegmatch(direct,str)
1318 if p then
1319 -- print("builder 1 >",p)
1320 f = loadstripped(p)()
1321 else
1322 n = 0 -- used in patterns
1323 -- p = lpegmatch(builder,str,1,"..",t._extensions_) -- after this we know n
1324 p = lpegmatch(builder,str,1,t._connector_,t._extensions_) -- after this we know n
1325 if n > 0 then
1326 p = format(template,preamble,t._preamble_,arguments[n],p)
1327 -- print("builder 2 >",p)
1328 f = loadstripped(p,t._environment_)() -- t._environment is not populated (was experiment)
1329 else
1330 f = function() return str end
1331 end
1332 end
1333 t[str] = f
1334 return f
1335 end
1336
1337 -- -- collect periodically
1338 --
1339 -- local threshold = 1000 -- max nof cached formats
1340 --
1341 -- local function make(t,str)
1342 -- local f = rawget(t,str)
1343 -- if f then
1344 -- return f
1345 -- end
1346 -- local parent = t._t_
1347 -- if parent._n_ > threshold then
1348 -- local m = { _t_ = parent }
1349 -- getmetatable(parent).__index = m
1350 -- setmetatable(m, { __index = make })
1351 -- else
1352 -- parent._n_ = parent._n_ + 1
1353 -- end
1354 -- local f
1355 -- local p = lpegmatch(direct,str)
1356 -- if p then
1357 -- f = loadstripped(p)()
1358 -- else
1359 -- n = 0
1360 -- p = lpegmatch(builder,str,1,"..",parent._extensions_) -- after this we know n
1361 -- if n > 0 then
1362 -- p = format(template,preamble,parent._preamble_,arguments[n],p)
1363 -- -- print("builder>",p)
1364 -- f = loadstripped(p)()
1365 -- else
1366 -- f = function() return str end
1367 -- end
1368 -- end
1369 -- t[str] = f
1370 -- return f
1371 -- end
1372
1373 local function use(t,fmt,...)
1374 return t[fmt](...)
1375 end
1376
1377 strings.formatters = { }
1378
1379 -- we cannot make these tables weak, unless we start using an indirect
1380 -- table (metatable) in which case we could better keep a count and
1381 -- clear that table when a threshold is reached
1382
1383 -- _connector_ is an experiment
1384
1385 function strings.formatters.new(noconcat)
1386 local e = { } -- better make a copy as we can overload
1387 for k, v in next, environment do
1388 e[k] = v
1389 end
1390 local t = {
1391 _type_ = "formatter",
1392 _connector_ = noconcat and "," or "..",
1393 _extensions_ = { },
1394 _preamble_ = "",
1395 _environment_ = e,
1396 }
1397 setmetatable(t, { __index = make, __call = use })
1398 return t
1399 end
1400
1401 local formatters = strings.formatters.new() -- the default instance
1402
1403 string.formatters = formatters -- in the main string namespace
1404 string.formatter = function(str,...) return formatters[str](...) end -- sometimes nicer name
1405
1406 local function add(t,name,template,preamble)
1407 if type(t) == "table" and t._type_ == "formatter" then
1408 t._extensions_[name] = template or "%s"
1409 if type(preamble) == "string" then
1410 t._preamble_ = preamble .. "\n" .. t._preamble_ -- so no overload !
1411 elseif type(preamble) == "table" then
1412 for k, v in next, preamble do
1413 t._environment_[k] = v
1414 end
1415 end
1416 end
1417 end
1418
1419 strings.formatters.add = add
1420
1421 -- registered in the default instance (should we fall back on this one?)
1422
1423 patterns.xmlescape = Cs((P("<")/"&lt;" + P(">")/"&gt;" + P("&")/"&amp;" + P('"')/"&quot;" + anything)^0)
1424 patterns.texescape = Cs((C(S("#$%\\{}"))/"\\%1" + anything)^0)
1425 patterns.luaescape = Cs(((1-S('"\n'))^1 + P('"')/'\\"' + P('\n')/'\\n"')^0) -- maybe also \0
1426 patterns.luaquoted = Cs(Cc('"') * ((1-S('"\n'))^1 + P('"')/'\\"' + P('\n')/'\\n"')^0 * Cc('"'))
1427
1428 -- escaping by lpeg is faster for strings without quotes, slower on a string with quotes, but
1429 -- faster again when other q-escapables are found (the ones we don't need to escape)
1430
1431 add(formatters,"xml",[[lpegmatch(xmlescape,%s)]],{ xmlescape = patterns.xmlescape })
1432 add(formatters,"tex",[[lpegmatch(texescape,%s)]],{ texescape = patterns.texescape })
1433 add(formatters,"lua",[[lpegmatch(luaescape,%s)]],{ luaescape = patterns.luaescape })
1434
1435 -- -- yes or no:
1436 --
1437 -- local function make(t,str)
1438 -- local f
1439 -- local p = lpegmatch(direct,str)
1440 -- if p then
1441 -- f = loadstripped(p)()
1442 -- else
1443 -- n = 0
1444 -- p = lpegmatch(builder,str,1,",") -- after this we know n
1445 -- if n > 0 then
1446 -- p = format(template,template_shortcuts,arguments[n],p)
1447 -- f = loadstripped(p)()
1448 -- else
1449 -- f = function() return str end
1450 -- end
1451 -- end
1452 -- t[str] = f
1453 -- return f
1454 -- end
1455 --
1456 -- local formatteds = string.formatteds or { }
1457 -- string.formatteds = formatteds
1458 --
1459 -- setmetatable(formatteds, { __index = make, __call = use })
1460
1461 -- This is a somewhat silly one used in commandline reconstruction but the older
1462 -- method, using a combination of fine, gsub, quoted and unquoted was not that
1463 -- reliable.
1464 --
1465 -- '"foo"bar \"and " whatever"' => "foo\"bar \"and \" whatever"
1466 -- 'foo"bar \"and " whatever' => "foo\"bar \"and \" whatever"
1467
1468 local dquote = patterns.dquote -- P('"')
1469 local equote = patterns.escaped + dquote / '\\"' + 1
1470 local cquote = Cc('"')
1471
1472 local pattern =
1473 Cs(dquote * (equote - P(-2))^0 * dquote) -- we keep the outer but escape unescaped ones
1474 + Cs(cquote * (equote - space)^0 * space * equote^0 * cquote) -- we escape unescaped ones
1475
1476 function string.optionalquoted(str)
1477 return lpegmatch(pattern,str) or str
1478 end
1479
1480 local pattern = Cs((newline / (os.newline or "\r") + 1)^0)
1481
1482 function string.replacenewlines(str)
1483 return lpegmatch(pattern,str)
1484 end
1485
1486 --
1487
1488 function strings.newcollector()
1489 local result, r = { }, 0
1490 return
1491 function(fmt,str,...) -- write
1492 r = r + 1
1493 result[r] = str == nil and fmt or formatters[fmt](str,...)
1494 end,
1495 function(connector) -- flush
1496 if result then
1497 local str = concat(result,connector)
1498 result, r = { }, 0
1499 return str
1500 end
1501 end
1502 end
1503
1504 --
1505
1506 local f_16_16 = formatters["%0.5N"]
1507
1508 function number.to16dot16(n)
1509 return f_16_16(n/65536.0)
1510 end
1511
1512 --
1513
1514 if not string.explode then
1515
1516 -- local tsplitat = lpeg.tsplitat
1517
1518 local p_utf = patterns.utf8character
1519 local p_check = C(p_utf) * (P("+") * Cc(true))^0
1520 local p_split = Ct(C(p_utf)^0)
1521 local p_space = Ct((C(1-P(" ")^1) + P(" ")^1)^0)
1522
1523 function string.explode(str,symbol)
1524 if symbol == "" then
1525 return lpegmatch(p_split,str)
1526 elseif symbol then
1527 local a, b = lpegmatch(p_check,symbol)
1528 if b then
1529 return lpegmatch(tsplitat(P(a)^1),str)
1530 else
1531 return lpegmatch(tsplitat(a),str)
1532 end
1533 else
1534 return lpegmatch(p_space,str)
1535 end
1536 end
1537
1538 end
1539
1540
1541 do
1542
1543 local p_whitespace = patterns.whitespace^1
1544
1545 local cache = setmetatable({ }, { __index = function(t,k)
1546 local p = tsplitat(p_whitespace * P(k) * p_whitespace)
1547 local v = function(s)
1548 return lpegmatch(p,s)
1549 end
1550 t[k] = v
1551 return v
1552 end })
1553
1554 function string.wordsplitter(s)
1555 return cache[s]
1556 end
1557
1558 end
1559