LuaTeX script that copies file, but inserts extra code if asked to

by Gaussler   Last Updated August 01, 2020 14:23 PM

I am aware of the many crazy callbacks in LuaTeX, but can they be used to solve the following problem?

I would like a LuaLaTeX script that works the following way. Suppose my LaTeX document is called myfile.tex. Then the script should do the following:

  1. The script creates a new file myfile_new.tex (this is easy, of course, and can be done using classical TeX.)
  2. While the document myfile.tex is being compiled, each line of this file is being copied to the file myfile_new.tex, so it becomes a copy of myfile.tex – but there is a twist:
  3. I want a TeX command \writetonewfile, taking one argument, which writes that argument to the file myfile_new.tex in the exact position where the command was found.

Let us see an example: Suppose this is my file myfile.tex:

\documentclass{article}

\directlua{ ... } % insert some Lua code

\newcommand\writetonewfile[1]{ ... } % insert appropriate Lua code

\newcommand\foo{This is foo.\writetonewfile{This was foo.}}

\newcommand\foobar[1]{This is foobar.\writetonewfile{This was #1.}}

\begin{document}

Hello World. \writetonewfile{And A Happy New Year.}

\foo

\foobar{Hello World}

\end{document}

After compiling this with LuaLaTeX, I would like myfile_new.tex to contain the following:

\documentclass{article}

\directlua{ ... } % insert some Lua code

\newcommand\writetonewfile[1]{ ... } % insert appropriate Lua code

\newcommand\foo{This is foo.\writetonewfile{This was foo.}}

\newcommand\foobar[1]{This is foobar.\writetonewfile{This was #1.}}

\begin{document}

Hello world. \writetonewfile{And A Happy New Year.}And A Happy New Year.

\fooThis was foo.

\foobar{Hello World}This was Hello World.

\end{document}

(Of course, if I actually compile this document, it will complain that \fooThis was never \def’ed, but you see the idea.)

A Lua script that just searches and replaces in the file will not suffice: What I want is an actual LaTeX command \writetonewfile. In particular, if I use expl3 and redefine the command as \mydoc_write_to_new_file:n, I should be able to define commands like \mydoc_write_to_new_file:x etc. and expand the code before it gets written to the new file.

Is this possible?

Tags : luatex


Related Questions



Problem printing LaTeX from lua in lualatex

Updated July 03, 2015 17:10 PM


luatexluaescape string and backslash

Updated May 03, 2015 00:10 AM