Run local class option declarations

This commit is contained in:
gloamxun committed 2026-10-24 23:07:51 +08:00
1 parent 11cfa44c2b
commit 6d5a3eb686
5 files changed
+204 -6

No files matched your search

+166 -1
View File
@@ -435,7 +435,16 @@ fn expand_project_packages(source: &str, store: &projects::ProjectStore, id: &st
}
} else if trimmed.starts_with("\\documentclass") {
if let Some((options, name)) = documentclass_parts(trimmed) {
if let Some(text) = load_project_file(&name, "cls", store, id, &mut loaded, 1) {
let requested: Vec<String> = options
.trim_start_matches('[')
.trim_end_matches(']')
.split(',')
.map(str::trim)
.filter(|option| !option.is_empty())
.map(str::to_string)
.collect();
if let Some(text) = load_project_class(&name, &requested, store, id, &mut loaded, 1)
{
output.push_str(&format!("\\documentclass{}{{{}}}", options, "article"));
output.push('\n');
output.push_str(&text);
@@ -558,6 +567,133 @@ fn sanitize_package(source: &str) -> String {
.join("\n")
}
fn balanced_group_at(text: &str, start: usize) -> Option<(String, usize)> {
if !text[start..].starts_with('{') {
return None;
}
let mut depth = 0usize;
for (offset, character) in text[start..].char_indices() {
match character {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
return Some((
text[start + 1..start + offset].to_string(),
start + offset + 1,
));
}
}
_ => {}
}
}
None
}
/// Executes the `\DeclareOption` / `\ExecuteOptions` / `\ProcessOptions`
/// subset of a local class file. Options named by `\documentclass[...]` run
/// their declaration codes in declaration order, `\ExecuteOptions` supplies
/// defaults for options that were not requested, and `\DeclareOption*` runs
/// when an option has no declaration. The option machinery itself is removed
/// from the emitted class body.
fn apply_class_options(source: &str, requested: &[String]) -> String {
let mut declared: Vec<(Option<String>, String)> = Vec::new();
let mut active: Vec<String> = requested
.iter()
.filter(|option| !option.is_empty())
.cloned()
.collect();
let mut output = String::new();
let mut index = 0;
while index < source.len() {
let rest = &source[index..];
if let Some(after) = rest.strip_prefix("\\DeclareOption") {
let (default, after) = match after.strip_prefix('*') {
Some(tail) => (true, tail),
None => (false, after),
};
let after = after.trim_start();
if default {
if let Some((body, body_end)) = balanced_group_at(after, 0) {
let consumed = rest.len() - after[body_end..].len();
declared.push((None, body));
index += consumed;
continue;
}
} else if let Some((key, key_end)) = balanced_group_at(after, 0) {
let tail = after[key_end..].trim_start();
if let Some((body, body_end)) = balanced_group_at(tail, 0) {
let consumed = rest.len() - tail[body_end..].len();
declared.push((Some(key), body));
index += consumed;
continue;
}
}
}
if let Some(after) = rest.strip_prefix("\\ExecuteOptions") {
let after = after.trim_start();
if let Some((list, end)) = balanced_group_at(after, 0) {
for name in list.split(',') {
let name = name.trim();
if !name.is_empty() && !active.iter().any(|option| option == name) {
active.push(name.to_string());
}
}
index += rest.len() - after[end..].len();
continue;
}
}
if let Some(after) = rest.strip_prefix("\\ProcessOptions") {
let after = after.strip_prefix('*').unwrap_or(after);
let mut matched = vec![false; active.len()];
for (key, body) in &declared {
let Some(key) = key else {
continue;
};
for (position, option) in active.iter().enumerate() {
if option == key {
output.push_str(body);
output.push('\n');
matched[position] = true;
}
}
}
if matched.iter().any(|matched| !matched) {
for (key, body) in &declared {
if key.is_none() {
output.push_str(body);
output.push('\n');
}
}
}
index += rest.len() - after.len();
continue;
}
let character = rest.chars().next().expect("character");
output.push(character);
index += character.len_utf8();
}
output
}
fn load_project_class(
name: &str,
options: &[String],
store: &projects::ProjectStore,
id: &str,
loaded: &mut Vec<String>,
depth: usize,
) -> Option<String> {
if depth > 8 || loaded.iter().any(|loaded| loaded == name) {
return None;
}
let bytes = store.read_file(id, &format!("{name}.cls")).ok()?;
let text = String::from_utf8(bytes).ok()?;
loaded.push(name.to_string());
let expanded = expand_required_packages(&text, store, id, loaded, depth);
Some(sanitize_package(&apply_class_options(&expanded, options)))
}
fn route_d_cache_key(id: &str, source: &str) -> (String, u64) {
let mut hasher = DefaultHasher::new();
source.hash(&mut hasher);
@@ -979,3 +1115,32 @@ fn ascii_file_name(name: &str) -> String {
})
.collect()
}
#[cfg(test)]
mod class_option_tests {
use super::apply_class_options;
#[test]
fn declared_options_run_only_when_requested() {
let source = "\\DeclareOption{boxed}{BOX}\n\\DeclareOption*{DEFAULT}\n\\ProcessOptions";
assert_eq!(
apply_class_options(source, &["boxed".to_string()]).trim(),
"BOX"
);
assert_eq!(apply_class_options(source, &[]).trim(), "");
assert_eq!(
apply_class_options(source, &["other".to_string()]).trim(),
"DEFAULT"
);
}
#[test]
fn execute_options_supply_defaults() {
let source = "\\DeclareOption{plain}{PLAIN}\n\\DeclareOption{boxed}{BOX}\n\\ExecuteOptions{plain}\n\\ProcessOptions";
assert_eq!(apply_class_options(source, &[]).trim(), "PLAIN");
assert_eq!(
apply_class_options(source, &["boxed".to_string()]).trim(),
"PLAIN\nBOX"
);
}
}