diff --git a/crates/texrra-tex-core/src/resources.rs b/crates/texrra-tex-core/src/resources.rs index 8ce738e..21c573d 100644 --- a/crates/texrra-tex-core/src/resources.rs +++ b/crates/texrra-tex-core/src/resources.rs @@ -12,9 +12,10 @@ pub use project::{ProjectDefinition, ProjectSnapshot, ProjectVersion}; use sha2::{Digest, Sha256}; use std::{ collections::{BTreeMap, BTreeSet}, + ffi::{OsStr, OsString}, fs, path::{Path, PathBuf}, - sync::Arc, + sync::{Arc, OnceLock}, time::SystemTime, }; @@ -163,6 +164,9 @@ impl SearchPath { pub struct WorldConfig { pub cwd: PathBuf, pub input_policy: InputPolicy, + /// Look for a case-insensitive basename after an exact TeX path search. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub casefold_search: bool, pub texmf_roots: Vec, pub paths: BTreeMap>, pub max_index_entries: usize, @@ -180,6 +184,7 @@ impl WorldConfig { Self { cwd: cwd.into(), input_policy: InputPolicy::Tex, + casefold_search: cfg!(unix), texmf_roots: Vec::new(), paths: BTreeMap::new(), max_index_entries: 1_000_000, @@ -196,6 +201,10 @@ impl WorldConfig { } let mut config = Self::new(cwd); config.texmf_roots = roots; + if let Some(value) = std::env::var_os("texmf_casefold_search") { + config.casefold_search = cfg!(unix) + && !matches!(value.as_encoded_bytes().first(), Some(b'0' | b'f')); + } for kind in ResourceKind::ALL { match std::env::var(kind.environment()) { Ok(value) => { @@ -281,6 +290,8 @@ pub struct ResourceTrace { pub schema: u32, pub cwd: PathBuf, pub input_policy: InputPolicy, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub casefold_search: bool, pub texmf_roots: Vec, pub paths: BTreeMap>, pub lookups: Vec, @@ -328,8 +339,51 @@ struct DirectoryIndex { #[serde(default)] directory_aliases: BTreeMap, #[serde(with = "index_names")] - names: BTreeMap>, + names: BTreeMap>, + // A filesystem decides the order between multiple folded matches in one + // directory. Only such ties need an additional snapshot observation. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + casefold_ties: BTreeMap>, + #[serde(skip)] + folded_names: OnceLock, Vec>>, } + +impl DirectoryIndex { + fn matching_paths(&self, name: &OsStr, casefold: bool) -> Vec { + if !casefold { + return self.names.get(name).cloned().unwrap_or_default(); + } + let names = self.folded_names.get_or_init(|| { + let mut index = BTreeMap::, Vec>::new(); + for name in self.names.keys() { + index.entry(folded_basename(name)).or_default().push(name.clone()); + } + index + }); + names.get(&folded_basename(name)).into_iter().flatten() + .filter(|spelling| spelling.as_os_str() != name) + .flat_map(|spelling| self.names[spelling].iter().cloned()) + .collect() + } + + fn order_folded_paths(&self, paths: &mut [PathBuf]) { + paths.sort_by(|a, b| { + a.parent().cmp(&b.parent()).then_with(|| { + let ties = a.parent().and_then(|parent| self.casefold_ties.get(parent)); + let rank = |path: &Path| { + ties.and_then(|names| names.iter().position(|name| Some(name.as_os_str()) == path.file_name())) + .unwrap_or(usize::MAX) + }; + rank(a).cmp(&rank(b)).then_with(|| a.cmp(b)) + }) + }); + } +} + +fn folded_basename(name: &OsStr) -> Vec { + name.as_encoded_bytes().to_ascii_lowercase() +} + fn recursive_index() -> bool { true } @@ -699,6 +753,7 @@ impl FileWorld { schema: 1, cwd: config.cwd.clone(), input_policy: config.input_policy, + casefold_search: config.casefold_search, texmf_roots: config.texmf_roots.clone(), paths: config.paths.clone(), configuration_observations: observations, @@ -748,6 +803,7 @@ impl FileWorld { schema: 1, cwd: config.cwd.clone(), input_policy: config.input_policy, + casefold_search: config.casefold_search, texmf_roots: config.texmf_roots.clone(), paths: config.paths.clone(), project_version: Some(project.version().clone()), @@ -831,6 +887,7 @@ impl FileWorld { schema: 1, cwd: config.cwd.clone(), input_policy: config.input_policy, + casefold_search: config.casefold_search, texmf_roots: config.texmf_roots.clone(), paths: config.paths.clone(), project_version: snapshot.project.as_ref().map(|p| p.version().clone()), @@ -929,7 +986,9 @@ impl FileWorld { if self.pinned { if was_live || self.project.is_some() { let newly_protected = self.protected_paths.insert(resource.version.path.clone()); - if self.project.is_some() && (was_live || newly_protected) { + if self.project.as_ref().is_some_and(|project| { + was_live || (newly_protected && project.file(&resource.version.path).is_none()) + }) { self.current_project_indexes.clear(); } } @@ -1431,6 +1490,8 @@ impl FileWorld { directories: Vec::new(), directory_aliases: BTreeMap::new(), names: BTreeMap::new(), + casefold_ties: BTreeMap::new(), + folded_names: OnceLock::new(), }; let built = (|| -> Result<(), String> { let mut queue = vec![(root.to_owned(), Vec::::new())]; @@ -1463,6 +1524,18 @@ impl FileWorld { .map_err(|e| format!("resource directory {}: {e}", dir.display()))? .collect::, _>>() .map_err(|e| e.to_string())?; + if self.config.casefold_search && self.config.input_policy == InputPolicy::Tex { + let mut buckets = BTreeMap::, Vec>::new(); + for child in &children { + let name = child.file_name(); + buckets.entry(folded_basename(&name)).or_default().push(name); + } + let ties: Vec<_> = buckets.into_values() + .filter(|names| names.len() > 1).flatten().collect(); + if !ties.is_empty() { + index.casefold_ties.insert(dir.clone(), ties); + } + } children.sort_by_key(|e| e.file_name()); for child in children { count += 1; @@ -1510,6 +1583,69 @@ impl FileWorld { } Ok(&self.indexes[root]) } + fn indexed_paths( + &mut self, + root: &Path, + tail: &Path, + recursive: bool, + casefold: bool, + ) -> Result, String> { + let Some(name) = tail.file_name() else { return Ok(Vec::new()) }; + let parent = tail.parent().unwrap_or(Path::new("")); + let matches_tail = |candidate: &Path| { + if !casefold { + return candidate.ends_with(tail); + } + candidate.parent().is_some_and(|path| { + if recursive { path.ends_with(parent) } else { path == root } + }) && candidate.file_name().is_some_and(|spelling| { + spelling != name && spelling.as_encoded_bytes().eq_ignore_ascii_case(name.as_encoded_bytes()) + }) + }; + self.index_at(root, recursive)?; + let index = self.indexes[root].clone(); + let mut matches = index.matching_paths(name, casefold); + matches.retain(|path| matches_tail(path)); + for live in self.live_paths.union(&self.protected_paths) { + if live.starts_with(root) && matches_tail(live) { + matches.push(live.clone()); + } + for (logical, canonical) in &index.directory_aliases { + if let Ok(relative) = live.strip_prefix(canonical) { + let candidate = logical.join(relative); + if matches_tail(&candidate) + && self.directory_binding(&candidate).is_some_and(|(bound, _)| bound == *live) + { + matches.push(candidate); + } + } + } + } + if casefold { + index.order_folded_paths(&mut matches); + } else { + matches.sort(); + } + matches.dedup(); + Ok(matches) + } + + fn probe_casefolded( + &mut self, + root: &Path, + tail: &Path, + recursive: bool, + candidates: &mut Vec, + ) -> Result, String> { + for candidate in self.indexed_paths(root, tail, recursive, true)? { + candidates.push(candidate.clone()); + if let Some(path) = self.probe(&candidate)? { + return Ok(Some((path, candidate))); + } + } + Ok(None) + } + pub fn resolve( &mut self, kind: ResourceKind, @@ -1541,6 +1677,8 @@ impl FileWorld { let result = (|| { let paths = self.paths(kind, from); let mut found = None; + let casefold = self.config.casefold_search && self.config.input_policy == InputPolicy::Tex + && !deferred::directory_only(Path::new(name)); let requested = Path::new(name); if requested.is_absolute() || matches!( @@ -1559,6 +1697,19 @@ impl FileWorld { break; } } + if found.is_none() && casefold { + for variant in &variants { + let direct = self.config.cwd.join(variant); + let (Some(parent), Some(basename)) = (direct.parent(), direct.file_name()) else { continue }; + if let Some((path, selected)) = self.probe_casefolded(parent, Path::new(basename), false, &mut candidates)? { + if record_spelling { + spelling = Some(variant.with_file_name(selected.file_name().unwrap())); + } + found = Some(path); + break; + } + } + } } else { // TeX honors search-path priority before the suffix alternatives. // A recursive path is one entry: search all of it for .tex before @@ -1596,53 +1747,7 @@ impl FileWorld { } if *recursive { let tail = suffix.join(variant); - let roles: Vec<_> = self - .live_paths - .union(&self.protected_paths) - .cloned() - .collect(); - let (mut matches, projected) = { - let index = self.index(&root)?; - let matches = index - .names - .get(variant.file_name().ok_or("resource needs a filename")?) - .cloned() - .unwrap_or_default(); - let mut projected = Vec::new(); - for live in &roles { - for (logical, canonical) in &index.directory_aliases { - if let Ok(relative) = live.strip_prefix(canonical) { - let candidate = logical.join(relative); - if candidate.ends_with(&tail) { - projected.push((candidate, live.clone())); - } - } - } - } - (matches, projected) - }; - for live in &roles { - if live.starts_with(&root) - && live.ends_with(&tail) - && !matches.contains(live) - { - matches.push(live.clone()); - } - } - for (candidate, target) in projected { - if self - .directory_binding(&candidate) - .is_some_and(|(bound, _)| bound == target) - && !matches.contains(&candidate) - { - matches.push(candidate); - } - } - matches.sort(); - for candidate in matches { - if !candidate.ends_with(&tail) { - continue; - } + for candidate in self.indexed_paths(&root, &tail, true, false)? { candidates.push(candidate.clone()); if let Some(path) = self.probe(&candidate)? { if record_spelling { @@ -1654,6 +1759,25 @@ impl FileWorld { } } } + if casefold { + for variant in &variants { + let tail = suffix.join(variant); + let direct = root.join(&tail); + let (Some(parent), Some(basename)) = (direct.parent(), direct.file_name()) else { continue }; + let selected = if *recursive { + self.probe_casefolded(&root, &tail, true, &mut candidates)? + } else { + self.probe_casefolded(parent, Path::new(basename), false, &mut candidates)? + }; + if let Some((path, candidate)) = selected { + if record_spelling { + spelling = Some(lookup_name(&self.config.cwd, &candidate)); + } + found = Some(path); + break 'paths; + } + } + } } } Ok(found) diff --git a/crates/texrra-tex-core/src/resources/project.rs b/crates/texrra-tex-core/src/resources/project.rs index bbfb500..ade9590 100644 --- a/crates/texrra-tex-core/src/resources/project.rs +++ b/crates/texrra-tex-core/src/resources/project.rs @@ -482,6 +482,8 @@ impl ProjectSnapshot { directories: Vec::new(), directory_aliases: BTreeMap::new(), names: BTreeMap::new(), + casefold_ties: BTreeMap::new(), + folded_names: Default::default(), }; let mut pending = vec![(root.to_path_buf(), Vec::::new())]; let mut count = 0; diff --git a/crates/texrra-tex-core/tests/resource_projects.rs b/crates/texrra-tex-core/tests/resource_projects.rs index 88625ae..450edf0 100644 --- a/crates/texrra-tex-core/tests/resource_projects.rs +++ b/crates/texrra-tex-core/tests/resource_projects.rs @@ -34,6 +34,30 @@ fn file(d: &mut ProjectDefinition, path: PathBuf, data: &[u8]) { d.files.insert(path, Arc::from(data)); } +#[cfg(unix)] +#[test] +fn casefolded_project_lookups_use_the_current_immutable_namespace() { + let root = directory().canonicalize().unwrap(); + let requested = "chapter.tex"; + let upper = root.join("CHAPTER.TEX"); + let exact = root.join(requested); + let entry = root.join("main.tex"); + let mut seed = definition(&root); + file(&mut seed, upper.clone(), b"initial buffer"); + let snapshot = ProjectSnapshot::new(seed).unwrap(); + let mut first = FileWorld::from_project(snapshot.clone()).unwrap(); + assert!(!upper.exists()); + assert_eq!(first.read_tex_input(requested, &entry).unwrap().version.path, upper); + + let edited = snapshot.with_file_changes( + 2, [(exact.clone(), Some(Arc::from(b"exact buffer".as_slice())))].into() + ).unwrap(); + let mut next = FileWorld::from_project(edited).unwrap(); + assert_eq!(next.read_tex_input(requested, &entry).unwrap().version.path, exact); + assert_eq!(first.read_tex_input(requested, &entry).unwrap().version.path, upper); + fs::remove_dir_all(&root).unwrap(); +} + #[test] fn immutable_buffer_edits_match_a_rebuilt_project_and_revalidate_imports() { let p = directory(); diff --git a/crates/texrra-tex-core/tests/resources.rs b/crates/texrra-tex-core/tests/resources.rs index 780a15b..af15983 100644 --- a/crates/texrra-tex-core/tests/resources.rs +++ b/crates/texrra-tex-core/tests/resources.rs @@ -20,6 +20,64 @@ fn put(path: impl AsRef, data: impl AsRef<[u8]>) { fs::write(p, data).unwrap(); } +#[cfg(unix)] +#[test] +fn tex_casefold_uses_actual_basename_after_exact_search_and_replays_it() { + let root = directory().canonicalize().unwrap(); + let first = root.join("first"); + let second = root.join("second"); + let recursive = root.join("tree"); + let folded = first.join("SLICE.TEX"); + let exact_later = second.join("slice.tex"); + put(&folded, b"early folded"); + put(&exact_later, b"later exact"); + put(first.join("PREFERENCE.TeX"), b"folded suffix"); + put(first.join("preference"), b"exact bare"); + put(root.join("HEADER.STY"), b"explicit path"); + put(recursive.join("nest/Sub/RECURSE.TEX"), b"nested name"); + put(first.join("TIES.TEX"), b"tie A"); + put(first.join("TiEs.TeX"), b"tie B"); + + let dir_order = fs::read_dir(&first).unwrap().map(Result::unwrap) + .find(|entry| entry.file_name().as_encoded_bytes().eq_ignore_ascii_case(b"ties.tex")) + .unwrap().path(); + let mut config = WorldConfig::new(&root); + config.paths.insert(ResourceKind::Tex, vec![ + SearchPath::directory(&first, false), + SearchPath::directory(&second, false), + SearchPath::directory(&recursive, true), + ]); + let entry = root.join("main.tex"); + let mut world = FileWorld::new(config.clone()).unwrap(); + world.capture_inputs(); + world.capture_lookup_paths(); + for (requested, expected) in [ + ("slice.tex", folded.clone()), + ("preference", first.join("preference")), + ("./header.sty", root.join("HEADER.STY")), + ("Sub/recurse.tex", recursive.join("nest/Sub/RECURSE.TEX")), + ("ties.tex", dir_order.clone()), + ] { + let got = world.read_tex_input(requested, &entry).unwrap(); + assert_eq!(got.version.path, expected, "request {requested}"); + } + assert!(world.resolve_tex_input("sub/recurse.tex", &entry).unwrap().is_none()); + assert_eq!(world.trace().lookups[2].lookup_path.as_deref(), Some(Path::new("./HEADER.STY"))); + + let snapshot = serde_json::to_vec(world.input_snapshot().as_ref()).unwrap(); + fs::remove_file(&folded).unwrap(); + fs::remove_file(&dir_order).unwrap(); + let mut replay = FileWorld::from_snapshot(serde_json::from_slice(&snapshot).unwrap()).unwrap(); + assert_eq!(replay.read_tex_input("slice.tex", &entry).unwrap().data, b"early folded"); + assert_eq!(replay.read_tex_input("ties.tex", &entry).unwrap().version.path, dir_order); + + put(&folded, b"restored physical file"); + config.casefold_search = false; + let mut strict = FileWorld::new(config).unwrap(); + assert_eq!(strict.read_tex_input("slice.tex", &entry).unwrap().version.path, exact_later); + fs::remove_dir_all(&root).unwrap(); +} + #[test] fn file_modification_capture_replays_original_observation_after_file_edits() { use std::time::{Duration, SystemTime}; diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index bee8dea..c54672f 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,32 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 TeX 资源大小写查找与原样 Wiley 双栏 + +Unix 上的 TeX 资源查找按配置路径顺序,在每个路径项内尝试全部精确 +后缀,再回退至文件名的 ASCII 大小写匹配。目录名仍精确匹配。 +查找记录保留实际路径,物理文件系统同目录大小写冲突的遍历顺序可保存并重放。 +独立项目快照由已声明资源生成索引。新建同名精确文件后,会话能切换所用 +资源,与独立全量的 PDF、SVG 和来源映射一致,仅第二页变化。 +[Kpathsea 查找实现](https://github.com/TeX-Live/texlive-source/blob/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/kpathsea/pathsearch.c#L127-L177) + +五项定向检查和 release 构建通过。对照实际 pdfTeX 验证默认值、 +设置 texmf_casefold_search 为 0、false 和 no 的查找顺序。 +适用范围是引擎已配置的文件搜索路径。此次沿用全矩阵统一验收顺序。 + +Wiley 官方 Optimal Design 双栏模板原样交付包含大写 LETTERSP.STY, +两端记录均验证从小写请求解析到此文件。使用出版商随包交付的 bbl, +两端从空 aux 开始三轮收敛到 11 页,逐轮 aux 完全一致。 +52,488 条字形记录的标识和顺序一致,9,637 个提取词及其顺序一致。 +10 页的字形坐标、词框和 144 DPI 灰度像素一致。第 8 页有同一基线的 +58 个字形横向偏移至多 0.084 bp,1,285 个像素不同。随包 BibTeX +输入自行重建书目时返回错误,保留原日志。该项目先独立记录,准确率 +余项及组合出版矩阵仍待统一验收。 +[Wiley 官方模板](https://authors-sit.aws.wiley.com/author-resources/Journal-Authors/Prepare/latex-template.html) + +证据在 target/p3-wiley-casefold/,SHA256SUMS 指纹为 +10edf5c6478c81ebf659b991b597dc04a20f590b9bd76ea9005e7be2db3f4e94。 + ## 2026-11-29 pdfTeX 字符程序标签与原样 PLOS ONE pdfTeX profile 接入 `\pdfnoligatures` 和 `\tagcode`。整字体操作 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index af96cc2..75959f3 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -1319,6 +1319,22 @@ target/p3-new-publisher/plos-comparison.json 的 SHA-256 为 ee245cfb2599b02a795eaf8bd07de03c8a9481f7c488de78bf17fadae137c01e。 [字体标签阶段记录](P2_M1_PROGRESS.md#2026-11-29-pdftex-字符程序标签与原样-plos-one) +### 2026-11-29 Wiley Optimal Design 原样双栏 + +独立抽查 Wiley 当前交付包 WileyDesign.zip 的 Optimal-Design-layout.tex, +使用原始 USG 类的 ASNA,twocolumn 配置。40 个项目输入经字节核验, +保留官方字体、图像、样式和 bbl 的名称及内容。参考 pdfTeX 和 Route-D +都从空 aux 开始,三轮收敛至 11 页,逐轮 aux 相同,末轮无未定义引用。 +从空状态调用 BibTeX 重建书目时,官方 bst/bib 组合返回了错误, +完整日志在 historical/reference-from-empty/bibtex.log。 + +两端 52,488 条字形记录的标识与顺序相同,14 个嵌入字体条目涉及相同的八种 +字体。9,637 个提取词顺序相同。10 页的词框和 144 DPI 灰度像素完全一致。 +第 8 页同一基线 58 个字形的横坐标偏移至多 0.084 bp, +1,285 个灰度像素不同。此样稿独立留档,尚未加入统一矩阵脚本。 +结果和资源清单在 target/p3-wiley-casefold/。 +[Wiley 官方模板](https://authors-sit.aws.wiley.com/author-resources/Journal-Authors/Prepare/latex-template.html) · [阶段记录](P2_M1_PROGRESS.md#2026-11-29-tex-资源大小写查找与原样-wiley-双栏) + 单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、 双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源 与容差都不得为通过而替换。类 Typst 的编辑延迟另用同批原样项目分规模测量, diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 2699449..5c53696 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -544,6 +544,54 @@ fn resumed_suffix_reuses_search_for_unchanged_paragraphs() { } +#[cfg(unix)] +#[test] +fn exact_name_added_after_casefold_replaces_the_observed_input_in_a_live_job() { + let root = directory("casefold-case-change"); + let entry = root.join("main.tex"); + let folded = root.join("CHAPTER.TEX"); + let exact = root.join("chapter.tex"); + let body = r" +\shipout\hbox{Stable page} +\relax +\input chapter.tex +\shipout\hbox{\chaptertext} +\end +"; + let mut definition = atomic_definition(&root, 1, body); + definition.files.insert( + folded.clone(), Arc::from(br"\def\chaptertext{Folded input}".as_slice()), + ); + let project = ProjectSnapshot::new(definition).unwrap(); + let mut job = request(&root).with_project(project.clone()).observe_generated_initial(); + job.world = project.configuration(); + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + let before = session.compile(job.clone()).unwrap(); + let edited = project.with_file_changes( + 2, [(exact.clone(), Some(Arc::from(br"\def\chaptertext{Exact input}".as_slice())))].into(), + ).unwrap(); + let edited = job.with_project(edited); + let after = session.compile(edited.clone()).unwrap(); + let full = NativeCompiler::default().compile(edited).unwrap(); + let selected = |output: &CompiledDocument| { + output.resources.trace.lookups.iter().find(|lookup| { + lookup.name == "chapter.tex" && lookup.from == entry + }).and_then(|lookup| lookup.resolved.clone()) + }; + assert_eq!(selected(&before), Some(folded)); + assert_eq!(selected(&after), Some(exact)); + assert_eq!(after.preview_since(Some(before.revision())).unwrap() + .pages.into_iter().map(|page| page.index).collect::>(), [1]); + assert_eq!(after.pdf, full.pdf); + assert_ne!(before.pdf, after.pdf); + assert_eq!(after.pages, full.pages); + assert_eq!(after.source_map.pages, full.source_map.pages); + assert_eq!(after.source_map.sources, full.source_map.sources); + assert_eq!(after.resources.trace, full.resources.trace); + assert_eq!(after.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn child_checkpoints_reuse_only_the_validated_physical_prefix() { let root = directory("child-continuation");