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


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

  Hello {World}

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.

  local mybuf = ""
  function readbuf( buf )
    mybuf = mybuf .. buf .. "\n" 
  function startrecording()
    luatexbase.add_to_callback('process_input_buffer', readbuf, 'readbuf')

  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))
    Hello {World}