Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
417 changes: 417 additions & 0 deletions claude-notes/plans/2026-10-27-lua-api-q1-parity-gh-939-942.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions crates/pampa/src/lua/constructors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1006,6 +1006,9 @@ pub fn register_pandoc_namespace(
// Document + meta constructors (pandoc.Pandoc, pandoc.Meta, pandoc.Meta*)
super::pandoc_doc::register_doc_constructors(lua, &pandoc)?;

// pandoc.types.Version (GH #942)
super::version::register_pandoc_types(lua, &pandoc)?;

// Set as global
lua.globals().set("pandoc", pandoc)?;

Expand Down
78 changes: 66 additions & 12 deletions crates/pampa/src/lua/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ pub enum LuaFilterError {
///
/// [`InvalidReturn`]: LuaFilterError::InvalidReturn
InvalidScriptReturn(String),
/// The filter called `os.exit(code)` (GH #941). Quarto 1 filters do
/// this to fail a render; here it fails this document only, like
/// `error()`, and the render goes on to the next one. The code is
/// reported, not propagated as the process status.
Exit {
filter: std::path::PathBuf,
code: i64,
},
}

impl std::fmt::Display for LuaFilterError {
Expand All @@ -66,6 +74,12 @@ impl std::fmt::Display for LuaFilterError {
LuaFilterError::LuaError(err) => write!(f, "Lua filter error: {}", err),
LuaFilterError::InvalidReturn(msg) => write!(f, "Invalid filter return: {}", msg),
LuaFilterError::InvalidScriptReturn(msg) => write!(f, "{}", msg),
LuaFilterError::Exit { filter, code } => write!(
f,
"Lua filter {} called os.exit({}); the document was not rendered",
filter.display(),
code
),
}
}
}
Expand Down Expand Up @@ -177,6 +191,10 @@ pub fn create_filter_environment_with(
#[cfg(not(target_arch = "wasm32"))]
let lua = Lua::new();

// os.exit fails the document, not the process (GH #941). On native this
// replaces the stdlib's libc exit; on WASM it extends the synthetic os.
super::os_exit::install_os_exit(&lua)?;

// Create mediabag for storing media items
// In the future, this could be pre-populated from the document or passed in
let mediabag = create_shared_mediabag();
Expand Down Expand Up @@ -208,6 +226,9 @@ pub fn create_filter_environment_with(
// Register quarto.doc namespace (is_format, add_html_dependency, etc.)
super::quarto_doc::register_quarto_doc(&lua)?;

// quarto.project and the host's environment for os.getenv (GH #939).
super::host_context::register_host_context(&lua, &options.host)?;

// Push script dir for quarto.utils.resolve_path
let script_dir = script_path
.parent()
Expand All @@ -220,20 +241,19 @@ pub fn create_filter_environment_with(
// FORMAT - the target output format (html, latex, etc.)
lua.globals().set("FORMAT", target_format)?;

// PANDOC_VERSION - version of Pandoc (we emulate 3.x behavior)
// Set as a table with numeric indices for version components
let version_table = lua.create_table()?;
version_table.set(1, 3)?;
version_table.set(2, 0)?;
version_table.set(3, 0)?;
lua.globals().set("PANDOC_VERSION", version_table)?;
// PANDOC_VERSION - version of Pandoc (we emulate 3.x behavior), as a
// pandoc.types.Version so `PANDOC_VERSION < pandoc.types.Version(...)`
// and `PANDOC_VERSION:must_be_at_least(...)` work (GH #942).
lua.globals().set(
"PANDOC_VERSION",
super::version::create_version(&lua, &[3, 0, 0])?,
)?;

// PANDOC_API_VERSION - version of the pandoc-types API
let api_version_table = lua.create_table()?;
api_version_table.set(1, 1)?;
api_version_table.set(2, 23)?;
api_version_table.set(3, 1)?;
lua.globals().set("PANDOC_API_VERSION", api_version_table)?;
lua.globals().set(
"PANDOC_API_VERSION",
super::version::create_version(&lua, &[1, 23, 1])?,
)?;

// PANDOC_SCRIPT_FILE - path to the current filter script
lua.globals().set(
Expand Down Expand Up @@ -294,6 +314,40 @@ pub async fn apply_lua_filter_with(
runtime: Arc<dyn SystemRuntime>,
attribution: Option<Arc<dyn crate::attribution::AttributionLookup>>,
options: &crate::lua_options::LuaOptions,
) -> FilterResult<FilterOutput> {
let result = apply_lua_filter_inner(
pandoc,
context,
filter_path,
target_format,
runtime,
attribution,
options,
)
.await;
// `os.exit` surfaces as a Lua error wrapping `LuaExit`, whether it was
// raised while the script loaded or inside a handler (GH #941). Name
// it as what it is rather than printing the wrapped error chain.
match result {
Err(LuaFilterError::LuaError(err)) => match super::os_exit::requested_exit(&err) {
Some(code) => Err(LuaFilterError::Exit {
filter: filter_path.to_path_buf(),
code,
}),
None => Err(LuaFilterError::LuaError(err)),
},
other => other,
}
}

async fn apply_lua_filter_inner(
pandoc: &Pandoc,
context: &ASTContext,
filter_path: &Path,
target_format: &str,
runtime: Arc<dyn SystemRuntime>,
attribution: Option<Arc<dyn crate::attribution::AttributionLookup>>,
options: &crate::lua_options::LuaOptions,
) -> FilterResult<FilterOutput> {
// Read filter file via runtime (supports VFS on WASM)
let filter_bytes = runtime.file_read(filter_path).map_err(|e| {
Expand Down
266 changes: 266 additions & 0 deletions crates/pampa/src/lua/host_context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
/*
* lua/host_context.rs
* Copyright (c) 2026 Posit, PBC
*
* What a Lua script learns about where it is running, from the host's
* `HostContext` (GH #939, #940):
*
* - `quarto.project` — `directory`, `offset`, `output_directory`,
* `profile`, with Quarto 1's shape (nil paths outside a project, the
* profile list always present);
* - `os.getenv` — answered from the host's environment snapshot when it
* supplied one, so the stdlib's libc `getenv` never runs on a filter
* worker thread and `--profile` is visible as `QUARTO_PROFILE`;
* - `quarto.doc.input_file` / `quarto.doc.output_file` — the absolute
* paths Quarto 1 gave, and the minimal `PANDOC_STATE` (`input_files`,
* `output_file`) built from the same two values.
*
* Registered after `quarto` and `os` exist, in both the filter and the
* shortcode environments.
*/

use mlua::{Lua, Result, Table, Value};

use crate::lua_options::HostContext;

/// Register everything the host context contributes to the environment.
pub fn register_host_context(lua: &Lua, host: &HostContext) -> Result<()> {
register_quarto_project(lua, host)?;
register_quarto_doc_paths(lua, host)?;
register_pandoc_state(lua, host)?;
install_os_getenv(lua, host)?;
Ok(())
}

/// `quarto.doc.input_file` / `quarto.doc.output_file`: absolute paths, as
/// in Quarto 1 (`init.lua`'s `inputFile()` / `outputFile()`). Absent (nil)
/// without a host, never a relative or placeholder path.
fn register_quarto_doc_paths(lua: &Lua, host: &HostContext) -> Result<()> {
let quarto: Table = lua.globals().get("quarto")?;
let doc: Table = quarto.get("doc")?;
if let Some(input) = &host.input_file {
doc.set("input_file", input.to_string_lossy().to_string())?;
}
if let Some(output) = &host.output_file {
doc.set("output_file", output.to_string_lossy().to_string())?;
}
Ok(())
}

/// The minimal `PANDOC_STATE`: `input_files` (a `pandoc.List` of the one
/// input, empty without a host) and `output_file`. Pandoc's `output_file`
/// is the writer's output *name* as given on its command line; Quarto 1
/// joined it with the output directory before any filter saw it
/// (`init.lua`'s `outputFile()`), so the absolute path is what Q1 filters
/// ended up with. The other pandoc fields (`resource_path`, `source_url`,
/// `user_data_dir`, `request_headers`, `verbosity`, `log`, `trace`) have
/// no q2 equivalent and stay nil, so a filter that needs one fails at its
/// own line rather than reading a plausible wrong default.
fn register_pandoc_state(lua: &Lua, host: &HostContext) -> Result<()> {
let state = lua.create_table()?;
let inputs: Vec<String> = host
.input_file
.iter()
.map(|p| p.to_string_lossy().to_string())
.collect();
state.set(
"input_files",
super::list::create_string_list_table(lua, &inputs)?,
)?;
if let Some(output) = &host.output_file {
state.set("output_file", output.to_string_lossy().to_string())?;
}
lua.globals().set("PANDOC_STATE", state)?;
Ok(())
}

/// `quarto.project`: Quarto 1's table, with nils where Q1 had them.
///
/// `profile` is a `pandoc.List` so Q1 code can call `:includes("drafts")`
/// on it; it is present (possibly empty) even outside a project, as in Q1
/// where it came from a filter param rather than the project.
fn register_quarto_project(lua: &Lua, host: &HostContext) -> Result<()> {
let quarto: Table = lua.globals().get("quarto")?;
let project = lua.create_table()?;
if let Some(p) = &host.project {
project.set("directory", p.directory.to_string_lossy().to_string())?;
project.set("offset", p.offset.as_str())?;
project.set(
"output_directory",
p.output_directory.to_string_lossy().to_string(),
)?;
}
project.set(
"profile",
super::list::create_string_list_table(lua, &host.profiles)?,
)?;
quarto.set("project", project)?;
Ok(())
}

/// Replace `os.getenv` with a lookup in the host's snapshot. Without a
/// snapshot the table is left alone: the stdlib function on native, the
/// runtime-backed one `os_wasm` installs on WASM.
fn install_os_getenv(lua: &Lua, host: &HostContext) -> Result<()> {
let Some(env) = host.env.clone() else {
return Ok(());
};
let os: Table = match lua.globals().get::<Value>("os")? {
Value::Table(t) => t,
_ => return Ok(()),
};
os.set(
"getenv",
lua.create_function(move |_, name: String| Ok(env.get(&name).cloned()))?,
)?;
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
use crate::lua_options::HostProject;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

fn lua_with(host: &HostContext) -> Lua {
let lua = Lua::new();
let runtime: Arc<dyn crate::lua::runtime::SystemRuntime> =
Arc::new(crate::lua::runtime::NativeRuntime::new());
super::super::constructors::register_pandoc_namespace(
&lua,
runtime,
super::super::mediabag::create_shared_mediabag(),
)
.unwrap();
super::super::quarto_api::register_quarto_api(&lua).unwrap();
// Production order: quarto.doc exists before the host context
// adds its path fields to it.
super::super::quarto_doc::register_quarto_doc(&lua).unwrap();
register_host_context(&lua, host).unwrap();
lua
}

fn eval<T: mlua::FromLua>(lua: &Lua, src: &str) -> T {
lua.load(src).eval().unwrap()
}

#[test]
fn quarto_project_outside_a_project_has_q1_nils_and_an_empty_profile_list() {
let lua = lua_with(&HostContext::default());
assert!(eval::<bool>(&lua, "return quarto.project.directory == nil"));
assert!(eval::<bool>(&lua, "return quarto.project.offset == nil"));
assert!(eval::<bool>(
&lua,
"return quarto.project.output_directory == nil"
));
assert_eq!(eval::<i64>(&lua, "return #quarto.project.profile"), 0);
assert_eq!(
eval::<String>(&lua, "return pandoc.utils.type(quarto.project.profile)"),
"List"
);
}

#[test]
fn quarto_project_inside_a_project() {
let dir = PathBuf::from("/proj");
let host = HostContext {
project: Some(HostProject {
directory: dir.clone(),
output_directory: dir.join("_site"),
offset: "..".to_string(),
}),
profiles: vec!["drafts".to_string(), "release".to_string()],
..Default::default()
};
let lua = lua_with(&host);
assert_eq!(
eval::<String>(&lua, "return quarto.project.directory"),
dir.to_string_lossy()
);
assert_eq!(eval::<String>(&lua, "return quarto.project.offset"), "..");
assert_eq!(
eval::<String>(&lua, "return quarto.project.output_directory"),
dir.join("_site").to_string_lossy()
);
assert!(eval::<bool>(
&lua,
"return quarto.project.profile:includes('drafts') and #quarto.project.profile == 2"
));
}

#[test]
fn doc_paths_and_pandoc_state_without_a_host() {
let lua = lua_with(&HostContext::default());
assert!(eval::<bool>(&lua, "return quarto.doc.input_file == nil"));
assert!(eval::<bool>(&lua, "return quarto.doc.output_file == nil"));
assert_eq!(eval::<i64>(&lua, "return #PANDOC_STATE.input_files"), 0);
assert!(eval::<bool>(&lua, "return PANDOC_STATE.output_file == nil"));
}

#[test]
fn doc_paths_and_pandoc_state_with_a_host() {
let input = PathBuf::from("/proj").join("sub").join("page.qmd");
let output = PathBuf::from("/proj")
.join("_site")
.join("sub")
.join("page.html");
let host = HostContext {
input_file: Some(input.clone()),
output_file: Some(output.clone()),
..Default::default()
};
let lua = lua_with(&host);
assert_eq!(
eval::<String>(&lua, "return quarto.doc.input_file"),
input.to_string_lossy()
);
assert_eq!(
eval::<String>(&lua, "return quarto.doc.output_file"),
output.to_string_lossy()
);
assert!(eval::<bool>(
&lua,
"return #PANDOC_STATE.input_files == 1 and PANDOC_STATE.input_files[1] == quarto.doc.input_file"
));
assert!(eval::<bool>(
&lua,
"return PANDOC_STATE.output_file == quarto.doc.output_file"
));
assert_eq!(
eval::<String>(&lua, "return pandoc.utils.type(PANDOC_STATE.input_files)"),
"List"
);
}

#[test]
fn os_getenv_reads_the_snapshot_only() {
let mut env = HashMap::new();
env.insert("QUARTO_PROFILE".to_string(), "drafts,release".to_string());
env.insert("FROM_FILE".to_string(), "yes".to_string());
let host = HostContext {
env: Some(Arc::new(env)),
..Default::default()
};
let lua = lua_with(&host);
assert_eq!(
eval::<String>(&lua, "return os.getenv('QUARTO_PROFILE')"),
"drafts,release"
);
assert_eq!(eval::<String>(&lua, "return os.getenv('FROM_FILE')"), "yes");
// Not in the snapshot means not visible, even when the real
// process has it: the snapshot is the whole environment.
assert!(eval::<bool>(&lua, "return os.getenv('PATH') == nil"));
}

#[test]
fn os_getenv_without_a_snapshot_is_the_stdlib() {
let lua = lua_with(&HostContext::default());
// PATH is set in every environment the test suite runs under.
assert!(eval::<bool>(
&lua,
"return type(os.getenv('PATH')) == 'string'"
));
}
}
Loading
Loading