[Tex/LaTex] In LuaLaTeX, how to pass the content of an environment to Lua verbatim

luatexverbatim

In LuaLaTeX, how would I go about capturing the content of an environment for (verbatim) processing by Lua? For example, consider something like

\begin{foobar}
  Hello {World}
\end{foobar}

I'd like to be able to take the content of the environment and pass it to Lua, as in

foobar("  Hello {World}\n")

(and Lua would then eventually pass the processed version back to LaTeX, but I can presumably handle that).

Best Answer

Start the "recording" mode when you enter \begin{foobar} and end it when you close the environment. That way you get the pure buffer contents.

\documentclass{article}
\usepackage{luacode}
\begin{luacode*}
do 
  local mybuf = ""
  function readbuf( buf )
    mybuf = mybuf .. buf .. "\n" 
  end
  function startrecording()
    luatexbase.add_to_callback('process_input_buffer', readbuf, 'readbuf')
  end

  function stoprecording()
    luatexbase.remove_from_callback('process_input_buffer', 'readbuf')
    local buf_without_end = mybuf:gsub("\\end{foobar}\n","")
    print(string.format("Lua: %q", buf_without_end))
  end
end
\end{luacode*}
\begin{document}
  \newenvironment{foobar}{\directlua{startrecording()}}{\directlua{stoprecording()}}
\begin{foobar}
    Hello {World}
\end{foobar}

\end{document}
Related Question