From dcfb140839149a07bbc230412dfc4eb1a054f41f Mon Sep 17 00:00:00 2001 From: Robert Alessi Date: Sun, 13 May 2018 16:50:40 +0200 Subject: Extending Lua's string.gsub function with LPeg patterns --- arabluatex.lua | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) (limited to 'arabluatex.lua') 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") require("arabluatex_novoc") require("arabluatex_trans") +-- arabluatex now uses lpeg +local original_gsub = string.gsub +function string.gsub(s, patt, repl) + if lpeg.type(patt) ~= "pattern" then + -- If patt isn't an LPEG pattern, revert to the normal gsub + return original_gsub(s, patt, repl) + else + -- Standardise repl to a function which takes the whole match + -- as the first argument, and then subsequent matches (if + -- there were any). + local typ = type(repl) + if typ == "table" then + local t = repl + repl = function(all, ...) + if select('#', ...) == 0 then + return t[all] + else + return t[...] + end + end + elseif typ == "string" then + local s = repl + repl = function(...) + local matches = {...} + return s:gsub("%%([0-9%%])", function(c) + if c == "%" then + return "%" + else + return matches[tonumber(c) + 1] + end + end) + end + elseif typ == "function" then + local f = repl + repl = function(all, ...) + if select('#', ...) == 0 then + return f(all) + else + return f(...) + end + end + else + error("Expected table / string / function") + end + return lpeg.Cs{ + (lpeg.C(patt) / repl + 1) * lpeg.V(1) + true + }:match(s) + end +end + +P = lpeg.P + local function protectarb(str) str = string.gsub(str, "(\\arb.?)(%[.-%])(%b{})", "\\@arb%2%3") str = string.gsub(str, "(\\begin.?)(%b{})(%b[])", "\\@@begin{%2%3}") -- cgit v1.2.3