'Read file from project root directory in Lua (for Quarto/Pandoc)
I have a book that I am moving from the Bookdown toolchain to Quarto. Very simply, both tools generate a book from flavoured markdown using Pandoc. Pandoc allows Lua scripts to be used to systematically modify content; I have several of these, and they are essential to the workflow.
One of these scripts automatically generates glossary references whenever it identifies a term in the glossary. The script (glossary.lua) loads a list of terms (from glossary.yml) to do this.
The directory structure is as follows:
.
├── glossary.yml
├── index.qmd
├── ...
├── scripts
│ ├── glossary.lua
│ └── ...
└── contents
├── preface.qmd
├── section1
│ ├── file1.qmd
│ └── ...
├── section2
└── ...
The key bits of the glossary.lua:
glossary_file = "glossary.yml"
-- Load glossary file
local function loadGlossary(filename)
file = io.open(filename, "rb")
if not file then
error("Cannot find the glossary file")
else
local glossary = file:read("*all")
return glossary
end
end
local glossary = exports.eval(loadGlossary(glossary_file))
Previously (in Bookdown) this worked because (as far as I can tell) the script was called from the root directory each time, and the glossary would load without issue. In Quarto however, it seems the script is called from the directory of the file that is being processed, and so fails after loading the index.qmd
.
This can be demonstrated by adding:
cwd = debug.getinfo(1).short_src;
print(cwd)
Calling Quarto from the command line in the book root directory then fails after processing the index file:
[1/5] index.qmd
scripts/glossary.lua
[2/5] content\preface.qmd
../scripts/glossary.lua
Error running filter ../scripts/glossary.lua:
../scripts/glossary.lua:600: Cannot find the glossary file
How can I force Lua to read the glossary file from the root directory each time?
Solution 1:[1]
In project mode, quarto will set the environment variable QUARTO_PROJECT_DIR
, which you can get in lua via
os.getenv("QUARTO_PROJECT_DIR")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Carlos Scheidegger |