use std::collections::BTreeSet;
use std::path::PathBuf;
const MAX_DEPTH: usize = 4;
pub fn gathered(src: &str) -> String {
let mut out = String::from(src);
let mut seen = BTreeSet::new();
gather_into(src, 0, &mut seen, &mut out);
out
}
fn gather_into(src: &str, depth: usize, seen: &mut BTreeSet<PathBuf>, out: &mut String) {
if depth >= MAX_DEPTH {
return;
}
for name in named(src) {
let Some(path) = resolve(&name) else { continue };
if !seen.insert(path.clone()) {
continue;
}
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
out.push('\n');
out.push_str(&text);
gather_into(&text, depth + 1, seen, out);
}
}
pub fn named(src: &str) -> Vec<String> {
let mut out = Vec::new();
for command in ["\\input", "\\include"] {
let mut rest = src;
while let Some(at) = rest.find(command) {
let after = &rest[at + command.len()..];
rest = after;
if after.starts_with(|c: char| c.is_ascii_alphabetic()) {
continue;
}
let after = after.trim_start_matches([' ', '\t']);
let name = match after.strip_prefix('{') {
Some(body) => match body.find('}') {
Some(end) => body[..end].trim().to_string(),
None => continue,
},
None => after
.split(|c: char| c.is_whitespace())
.next()
.unwrap_or_default()
.to_string(),
};
if !name.is_empty() && !name.contains('\\') && !out.contains(&name) {
out.push(name);
}
}
}
out
}
fn resolve(name: &str) -> Option<PathBuf> {
let candidates = match std::path::Path::new(name).extension().is_some() {
true => vec![name.to_string()],
false => vec![format!("{name}.tex"), name.to_string()],
};
let mut dirs = vec![PathBuf::from(".")];
if let Ok(paths) = std::env::var("TEXINPUTS") {
dirs.extend(std::env::split_paths(&paths));
}
for dir in &dirs {
for candidate in &candidates {
let full = dir.join(candidate);
if full.is_file() {
return Some(full);
}
}
}
None
}
#[cfg(test)]
mod tests {
#[test]
fn both_spellings_of_input_and_include_are_names() {
let got = super::named("\\input{a}\n\\input b.tex\n\\include{c}\n");
assert_eq!(got, ["a", "b.tex", "c"]);
}
#[test]
fn a_longer_command_is_not_input_and_a_built_name_is_not_scanned() {
assert!(super::named("\\includegraphics{f.pdf}").is_empty());
assert!(super::named("\\input size1\\@ptsize.clo").is_empty());
}
}