Expand input and include files in project previews

Project previews now expand \input{...} and \include{...} from the
project store (adding a .tex suffix when needed) before route-D parses
the source. Unknown paths and cycles leave the directive as literal
text.
This commit is contained in:
gloamxun committed 2026-10-24 20:56:54 +08:00
1 parent 67eb719cbd
commit 9599436447
6 files changed
+109 -5

No files matched your search

+63
View File
@@ -1034,6 +1034,53 @@ fn skip_glue(rest: &str) -> Option<(i64, i64, i64)> {
Some((width?, stretch, shrink))
}
/// Expand `\input{...}` and `\include{...}` from project files.
///
/// The reader returns the file contents for a path, or `None` when the file
/// is unknown; unknown directives stay in the source so the preview still
/// renders them as text. Recursion is capped to avoid include cycles.
pub fn expand_inputs<F>(source: &str, read: F) -> String
where
F: Fn(&str) -> Option<String>,
{
expand_inputs_at(source, &read, 0)
}
fn expand_inputs_at<F>(source: &str, read: &F, depth: usize) -> String
where
F: Fn(&str) -> Option<String>,
{
const COMMANDS: [&str; 2] = ["\\input{", "\\include{"];
let mut expanded = String::new();
let mut rest = source;
loop {
let next = COMMANDS
.iter()
.filter_map(|command| rest.find(command).map(|index| (index, *command)))
.min_by_key(|(index, _)| *index);
let Some((index, command)) = next else {
expanded.push_str(rest);
break;
};
expanded.push_str(&rest[..index]);
let after = &rest[index + command.len()..];
let Some(close) = after.find('}') else {
expanded.push_str(rest);
break;
};
let name = after[..close].trim();
let directive = &rest[index..index + command.len() + close + 1];
match read(name) {
Some(text) if depth < 8 => {
expanded.push_str(&expand_inputs_at(&text, read, depth + 1));
}
_ => expanded.push_str(directive),
}
rest = &after[close + 1..];
}
expanded
}
fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
let paragraphs: Vec<&str> = source
.split("\n\n")
@@ -3699,6 +3746,22 @@ A definition.
plain_y
);
}
#[test]
fn input_directives_expand_from_the_reader() {
let source = "Before \\input{section} after \\input{nested}";
let expanded = expand_inputs(source, |name| match name {
"section" => Some("Included.".to_string()),
"nested" => Some("\\input{deep}".to_string()),
"deep" => Some("Deep.".to_string()),
_ => None,
});
assert_eq!(expanded, "Before Included. after Deep.");
assert_eq!(
expand_inputs("\\input{missing}", |_| None),
"\\input{missing}"
);
}
#[test]
fn paragraphs_read_vertical_skip_commands() {
let source = "Alpha.\n\n\\medskip\n\nBeta.\n\n\\bigskip\n\nGamma.\n\n\\vskip 5pt plus 2pt minus 1pt\n\nDelta.";