Using LuaTeX to run tools and utilities installed on Overleaf’s servers

By Graham Douglas

Overleaf’s servers: running and executing software

Overleaf’s powerful servers compile your project in a sandbox based on Docker’s Linux container technology. Every project gets its own sandbox, which ensures that any code we execute as part of compiling the project is isolated from other projects—and this is the first of several layers of protection that we use to compile projects safely. For TeX users, this means you can safely access and use a wealth of tools and utilities contained on our servers—but how?

In this short post we show how to use a Lua script (via LuaTeX) to execute an external program and capture any text that would usually be output to a terminal window. For example, suppose you are interested to convert some DVI files into SVG using the dvisvgm utility but you can’t recall the various command-line options? Wouldn’t it be nice to quickly typeset a list of them to refresh your memory? If so, read on—but if you prefer to see this in action, hop over to this gallery project example to see how it’s done.

Using LuaTeX to run an external program via a Lua script

Because LuaTeX has the Lua scripting language embedded into the TeX engine it becomes almost trivial to write a short script that not only executes an external program but also captures, and saves to a file, any text which that program would otherwise output to a terminal window. Once that text is saved to a file you can use the verbatim package to import it into your main TeX document. Here is the entire code needed to do this with LuaTeX:

function runcommand(cmd)
  local fout = assert(io.popen(cmd, 'r'))
  local str = assert(fout:read('*a'))
  return str

local sout=runcommand("dvisvgm --help")
local marg = assert("command.txt","w"))

The key line in the above code is local sout=runcommand("dvisvgm --help") which executes dvisvgm with the command-line option --help to instruct dvisvgm to list all of its command-line options. The help text is captured and saved to a text file called command.txt.

After the Lua code within \directlua{...} has finished executing, the content of command.txt is inserted into the main TeX document using \verbatiminput{command.txt}. It is important that you insert any captured text as verbatim material because characters such as $, #, \, _, ^ etc. might be present within the imported text.

Feel free to amend the code in runcommand("dvisvgm --help") and explore executing other programs—such as GhostScript—or any TeX Live software you might be interested to use.

Graham Douglas

Graham Douglas

Content Development Editor

I've worked in scientific/technical publishing for over 20 years (Senior Publisher, book/journal production, and programming). Now relishing the opportunity to combine my interests in publishing and TeXnology. I work from home, ably assisted by our two delightfully inquisitive Bengal cats: Oscar and Alfie.