Spring til indhold

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 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.

Screenshot of an Overleaf project


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:

 
\documentclass{article} 
\usepackage{verbatim} 
\begin{document} 
\directlua{ 
function runcommand(cmd) 
local fout = assert(io.popen(cmd, 'r')) 
local str = assert(fout:read('*a')) 
fout:close() 
return str 
end 

local sout=runcommand("dvisvgm --help") 
local marg = assert(io.open("command.txt","w")) 
marg:write(sout) 
marg:flush() 
marg:close() 
} 
\verbatiminput{command.txt} 
\end{document}

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.

Overleaf guides

LaTeX Basics

Mathematics

Figures and tables

References and Citations

Languages

Document structure

Formatting

Fonts

Presentations

Commands

Field specific

Class files

Advanced TeX/LaTeX