3

I'd like to feed a lstlisting environment (from the listings package) with contents back to TeX from Lua, but the end of lstlisting is apparently not found. The same happens if lstlisting is replaced with verbatim. How do I fix this?

Note that I want luacode to feed lstlisting back to TeX, not a hack that works in this instance but doesn't do that.

\documentclass{article}

\usepackage{listings}
\usepackage{luacode,luatexbase}

\newcommand{\processfile}[1]{\directlua{processfile("#1")}}

\begin{luacode*}
function processfile(fn)
  tex.print("\\begin{lstlisting}\n")
  local f=assert(io.open(fn,"r"))
  local t= f:read("*all")
  f:close()
  tex.print(t)
  tex.print("\\end{lstlisting}\n")  
  end
\end{luacode*}

\begin{document}
\processfile{code.c}
\end{document}
5
  • 1
    Alternative: Write your changes to a file and use lstinputlisting (indirectly feeding it).
    – TeXnician
    Aug 3, 2017 at 18:09
  • 1
    Does tex.print("\\scantokens{\end{lstlisting}\n") help?
    – user31729
    Aug 3, 2017 at 18:11
  • Actually, I want to process the input in Lua and stick parts in lstlisting environments interspersed with LaTeX.
    – JPi
    Aug 3, 2017 at 18:11
  • @ChristianHupfer: nope
    – JPi
    Aug 3, 2017 at 18:15
  • @TeXnician: That's one I had actually thought of.... thanks, but no.
    – JPi
    Aug 3, 2017 at 18:16

1 Answer 1

2

The following seems to work. But I had to use the luacode-environment. So it not "pure" luacode but I didn't find a way to do the \detokenize on the lua-side. I also changed the processing to line-by-line to get the correct linebreak.

\documentclass{article}
\usepackage{listings}
\newcommand{\processfile}[1]{\directlua{processfilebyline("#1")}}
\usepackage{luacode}

\begin{luacode}
function processfilebyline(fn)
  tex.print("\\begin{lstlisting}")
  local f=assert(io.open(fn,"r"))
  while true do
      local line = f:read("*line")
      if line == nil then break end
      tex.print(line)
    end
  f:close()
  tex.print("\detokenize{\\end{lstlisting}}")
  end

\end{luacode}
 %
\begin{document}
\processfile{duck.tex}
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.