local a=require'pl.utils'local b,c,d,e,f=table.insert,string.format,string.sub,string.find,string.gsub;local g="\n__R_size = __R_size + 1; __R_table[__R_size] = "local function h(i,j,k,l)local m=1;for n,o,p in j:gmatch(k)do o='('..d(o,2,-2)..')'b(i,g..c("%q",d(j,m,n-1)))b(i,g..c("__tostring(%s or '')",o))m=p end;local q;if l then q=c("%q",f(d(j,m),"\n",""))else q=c("%q",d(j,m))end;if q~='""'then b(i,g..q)end end;local function r(j,s,t,u,l)local k="()"..s.."(%b"..t..")()"local v=u.."+([^\n]*\n?)"local w,x="^"..v,"\n"..v;local i,m={"return function()\nlocal __R_size, __R_table, __tostring = 0, {}, __tostring",n=1},1;while true do local y,p,z=e(j,w,m)if not p then local A;A,p,z=e(j,x,m)h(i,d(j,m,A),k,l)if not p then break end end;if d(z,-1,-1)=="\n"then z=d(z,1,-2)end;b(i,"\n"..z)m=p+1 end;b(i,"\nreturn __R_table\nend")local B=false;if#i==3 and i[2]:find(g,1,true)==1 then i={"return "..i[2]:sub(#g+1,-1)}B=true end;return table.concat(i),B end;local C={}function C.substitute(D,E)E=E or{}local F,G=C.compile(D,{chunk_name=rawget(E,"_chunk_name"),escape=rawget(E,"_escape"),inline_escape=rawget(E,"_inline_escape"),inline_brackets=rawget(E,"_brackets"),newline=nil,debug=rawget(E,"_debug")})if not F then return F,G end;return F:render(E,rawget(E,"_parent"),rawget(E,"_debug"))end;local H=function(self,E,I,J)E=E or{}if I then setmetatable(E,{__index=I})end;setmetatable(self.env,{__index=E})local K,L=xpcall(self.fn,debug.traceback)if not K then if self.code and J then print(self.code)end;return nil,L,self.code end;return table.concat(L),nil,self.code end;function C.compile(D,M)M=M or{}local N=M.chunk_name or'TMP'local O=M.escape or'#'local s=M.inline_escape or'$'local P=M.inline_brackets or'()'local Q,B=r(D,s,P,O,M.newline)local E={__tostring=tostring}local R,G=a.load(Q,N,'t',E)if not R then return nil,G,Q end;if B then local S=R()return{fn=R(),env=E,render=function(self)return S,nil,self.code end,code=M.debug and Q or nil}end;return{fn=R(),env=E,render=H,code=M.debug and Q or nil}end;return C