aboutsummaryrefslogtreecommitdiff
path: root/arabluatex.lua
diff options
context:
space:
mode:
authorRobert Alessi <alessi@robertalessi.net>2018-05-13 16:50:40 +0200
committerRobert Alessi <alessi@robertalessi.net>2018-05-13 16:50:40 +0200
commitdcfb140839149a07bbc230412dfc4eb1a054f41f (patch)
tree6410e999a8775be23baaa4c2f6c2b8d7ccb24709 /arabluatex.lua
parenta2c09fa2736279ed2eec00177f2b0215dd19cd22 (diff)
downloadarabluatex-dcfb140839149a07bbc230412dfc4eb1a054f41f.tar.gz
Extending Lua's string.gsub function with LPeg patterns
Diffstat (limited to 'arabluatex.lua')
-rw-r--r--arabluatex.lua52
1 files changed, 52 insertions, 0 deletions
diff --git a/arabluatex.lua b/arabluatex.lua
index 8105311..e83206f 100644
--- a/arabluatex.lua
+++ b/arabluatex.lua
@@ -27,6 +27,58 @@ require("arabluatex_fullvoc")
27require("arabluatex_novoc") 27require("arabluatex_novoc")
28require("arabluatex_trans") 28require("arabluatex_trans")
29 29
30-- arabluatex now uses lpeg
31local original_gsub = string.gsub
32function string.gsub(s, patt, repl)
33 if lpeg.type(patt) ~= "pattern" then
34 -- If patt isn't an LPEG pattern, revert to the normal gsub
35 return original_gsub(s, patt, repl)
36 else
37 -- Standardise repl to a function which takes the whole match
38 -- as the first argument, and then subsequent matches (if
39 -- there were any).
40 local typ = type(repl)
41 if typ == "table" then
42 local t = repl
43 repl = function(all, ...)
44 if select('#', ...) == 0 then
45 return t[all]
46 else
47 return t[...]
48 end
49 end
50 elseif typ == "string" then
51 local s = repl
52 repl = function(...)
53 local matches = {...}
54 return s:gsub("%%([0-9%%])", function(c)
55 if c == "%" then
56 return "%"
57 else
58 return matches[tonumber(c) + 1]
59 end
60 end)
61 end
62 elseif typ == "function" then
63 local f = repl
64 repl = function(all, ...)
65 if select('#', ...) == 0 then
66 return f(all)
67 else
68 return f(...)
69 end
70 end
71 else
72 error("Expected table / string / function")
73 end
74 return lpeg.Cs{
75 (lpeg.C(patt) / repl + 1) * lpeg.V(1) + true
76 }:match(s)
77 end
78end
79
80P = lpeg.P
81
30local function protectarb(str) 82local function protectarb(str)
31 str = string.gsub(str, "(\\arb.?)(%[.-%])(%b{})", "\\@arb%2%3") 83 str = string.gsub(str, "(\\arb.?)(%[.-%])(%b{})", "\\@arb%2%3")
32 str = string.gsub(str, "(\\begin.?)(%b{})(%b[])", "\\@@begin{%2%3}") 84 str = string.gsub(str, "(\\begin.?)(%b{})(%b[])", "\\@@begin{%2%3}")