luatex – Is it Possible to Use Lua to Obtain the Current Working Directory?

currfileluatex

Package currfile with the abspath option can obtain the absolute path of the current file. However, it relies on running pdflatex with the -recorder flag.
Would it be possible to achieve the same objective using lualatex?

Note that lualatex has the same set of command line flags as pdlflatex, so, naturally currfile would work in lualatex just as it would work in pdflatex.
The challenge is to use lua to extract the current folder information within the text without relying on the -recorder flag.

Best Answer

Peer pressure once again. :)

IIRC, pure Lua has no built-in way to find out the current working directory without resorting to trickery. Thankfully, LuaTeX is shipped with the amazing LuaFileSystem, which is a "library developed to complement the set of functions related to file systems offered by the standard Lua distribution."

The reference section of the LFS manual indicates a way of achieving what we want:

lfs.currentdir ()

Returns a string with the current working directory or nil plus an error string.

There we go! Now let's write our .tex file based on this idea:

\documentclass{article}

\edef\workingdir{\unexpanded\expandafter{\directlua{tex.write(lfs.currentdir())}}}

\begin{document}

Hello, I'm in \workingdir

\texttt{\meaning\workingdir}

\end{document}

Thanks to egreg for providing the \edef version instead of my original \newcommand approach; that way, it should avoid problems with special characters in the path, and if put in the preamble of the main document, the value won't change when \workingdir is used in an \input file.

Here's the sample output from my machine:

Quack

There we go! :)

Update: If we don't want to "freeze" the working directory value, I believe we can rely on my first attempt using \newcommand instead of using \edef:

\newcommand{\actualworkingdir}{%
\unexpanded\expandafter{\directlua{tex.write(lfs.currentdir())}}}

That way, lfs.currentdir() is always issued on demand. Please bear in mind that the difference of both approaches is quite substantial:

Quack

Related Question