I'm playing around with luatex and learning about nodes and callbacks. What I'd like to do is be able to add some text via a particular callback. The type of callback that I'm interested in is one where the input is a node list (think hpack_filter) so I want to append the text in the form of a node list. This is simple enough if I have my text to append already stored as a node list (say stuff):
function appendStuff(h) local l = node.tail(h) l.next = node.copy_list(stuff) return h end The difficulty is in populating that node list in the first place.
What I'd like to do (because I'm lazy) is to specify a string, say hello world, pass it to TeX to convert it to a node list, and then save the resulting node list. I've figured out how to do this from the TeX side, see code below. What I'd like to do is do it entirely from the lua side. I realise that TeX will have to be involved at some point, but is there a proper way to do this? At the moment, my best guess is to have lua issue the relevant TeX commands via a tex.print(). Using hpack_filter as my callback (is there a better one?) I would have lua install the callback, issue the TeX command to create a box, then uninstall the callback (and, for cleanliness, destroy the box). That just feels cludgey. Is there a better way to accomplish this? If it helps, I can arrange it so that my strings don't need expansion (though, of course, it would be better if that was allowed).
Here's some code to play with:
\documentclass{article} \usepackage{filecontents} \usepackage{luatexbase} \begin{filecontents*}{texttonodes.lua} local stuff function saveNodeList(h) print("Saving box") stuff = h luatexbase.remove_from_callback('hpack_filter',"Save a box") end function saveNextBox() luatexbase.add_to_callback ( 'hpack_filter', saveNodeList, "Save a box" ) end function useLastBox() luatexbase.add_to_callback ( 'hpack_filter', useNodeList, "Use a box" ) end function useNodeList(h) if stuff then local l = node.tail(h) l.next = node.copy_list(stuff) end luatexbase.remove_from_callback('hpack_filter',"Use a box") return h end \end{filecontents*} \directlua{dofile('texttonodes.lua')} \newbox\mybox \newcommand\savetext[1]{% \directlua{saveNextBox()}% \setbox\mybox=\hbox{#1}% } \newcommand\usetext[1]{% \directlua{useLastBox()}% \setbox\mybox=\hbox{#1}% \unhbox\mybox } \begin{document} \savetext{hello world} \usetext{goodbye earth, } \end{document} 