views:

398

answers:

1

Hi all,

Bumped into a somewhat weird problem... I want to turn the string:

a\left(b_{d}\right)

into

a \left( b_{d} \right)

in Scite using a Lua script.

So, I made the following Lua script for Scite:


function SpaceTexEquations()
  editor:BeginUndoAction()
    local sel = editor:GetSelText()

    local cln3 = string.gsub(sel, "\\left(", " \\left( ")
    local cln4 = string.gsub(cln3, "\\right)", " \\right) ")

    editor:ReplaceSel(cln4)
  editor:EndUndoAction()
end

The cln3 line works fine, however, cln4 crashes with:

 /home/user/sciteLuaFunctions.lua:49: invalid pattern capture
 >Lua: error occurred while processing command

I think this is because bracket characters () are reserved characters in Lua; but then, how come the cln3 line works without escaping? By the way I also tried:

-- using backslash \ as escape char:
local cln4 = string.gsub(cln3, "\\right\)", " \\right) ") -- crashes all the same

-- using percentage sign % as escape chare
local cln4 = string.gsub(cln3, "\\right%)", " \\right) ") -- does not crash, but does not match either

Could anyone tell me what would be the correct way to do this?

Thanks,

Cheers!

+3  A: 

The correct escape character in Lua is %, so what you tried should work, I just tried

local sel = [[a\left(b_{d}\right)]]
local cln3 = string.gsub(sel, "\\left%(", " \\left( ")
local cln4 = string.gsub(cln3, "\\right%)", " \\right) ")
print (cln4)

and got

a \left( b_{d} \right) 

so, this worked for me when I tried it, what did you get as a match when you tried %

Fraser Graham
Hi Fraser, Thanks so much for the quick response! With % as escape, in my first attempt, it didn't match at all (i.e. the cln4/"right" part was not spaced at all). After you wrote, I tried it again, and then it generated an error. And then I finally decided to restart Scite and then it started working :) ...
sdaau
... The thing is, I had set the option ext.lua.auto.reload=1 in Scite properties, so that whenever a lua script is changed+saved, it "reloads" without having to restart Scite. It worked for me for the most part, but apparently it coughed up at error during my first unescaped "\\right)" attempt, and then kept on generating errors even if I used % to escape.. Any case, glad to have it solved. And just for reference, no need for a new variable up there, can also do it like: ...
sdaau
... function SpaceTexEquations() editor:BeginUndoAction() local sel = editor:GetSelText() local clnd = sel clnd = string.gsub(clnd, "\\left%(", " \\left( ") clnd = string.gsub(clnd, "\\right%)", " \\right) ") editor:ReplaceSel(clnd) editor:EndUndoAction() endSo, seems to be Scite refresh/reload Lua script problem.. Thanks again - cheers!
sdaau
Ah, makes sense. I just tested the code in straight Lua without Scite (although coincidently I do use Scite as my editor for Lua scripts)
Fraser Graham