Skip to main content

latexml/
main_tex.rs

1//! Main `.tex` discovery for directory inputs.
2//!
3//! Equivalent to the binary's `--whatsin=directory` mode: given a
4//! source directory, return the path of the file the converter should
5//! treat as the top-level entrypoint. Lifted from
6//! `bin/latexml_oxide.rs` so embedders (e.g. `ar5iv-editor`,
7//! `cortex_worker`) can run the same heuristic without shelling out.
8//!
9//! Detection order:
10//!  1. `00README.json` "sources" entry with `usage == "toplevel"` (modern arXiv format).
11//!  2. `00README.XXX` line tagged `toplevelfile` (legacy arXiv). Lines tagged `ignore` exclude the
12//!     named file from later heuristic scanning (Perl `Pack.pm::detect_source` `unlink`s them; we
13//!     filter the candidate list instead — safer if the directory isn't a sandbox).
14//!  3. Pack.pm-derived likelihood scoring across every `.tex` / `.txt` / `.ltx` (and, as a
15//!     fallback, every long-extensioned or extension-less file). Files vetoed by `\input` /
16//!     `\include` references are excluded; `\documentclass` / `\documentstyle` and Mac-classic
17//!     markers boost the score; bibtex / metafont / %auto-ignore / withdrawal sentinels disqualify.
18//!
19//! Returns the absolute path of the chosen entry as a `PathBuf`. The
20//! `Err` arm carries a Perl-canonical `Fatal:invalid:not_tex_source`
21//! style message (matching what the binary printed before this lift).
22
23use std::{
24  path::{Path, PathBuf},
25  sync::LazyLock,
26};
27
28use regex::Regex;
29
30/// Discover the main `.tex` file inside `dir`, mirroring the binary's
31/// `--whatsin=directory` heuristic. The returned path is rooted at
32/// `dir`. Errors carry a human-readable diagnostic on `Fatal:` failure
33/// modes (PDF mis-named as TeX, only `%auto-ignore` files, no TeX at
34/// all). `confined` is whether the conversion will read confined (OXIDIZED_DESIGN_DIVERGENCES #1183: an archive input,
35/// `--paranoid-input`, the cortex worker): then only a file that opens inside `dir` is a candidate or a `.bbl`, and a
36/// link leading out of it counts for nothing; unconfined, a link is followed, as Perl's detection does.
37pub fn find_main_tex(dir: &Path, confined: bool) -> Result<PathBuf, String> {
38  main_tex_in(dir, true, confined)
39}
40
41/// [`find_main_tex`]; `report` warns of a `00README` entry outside `dir` ([`readme_entry`]) — the language server's
42/// detection passes false, as its warnings would only pile up unreported.
43pub fn main_tex_in(dir: &Path, report: bool, confined: bool) -> Result<PathBuf, String> {
44  // Phase I.1: Check 00README.json (2025 arXiv format)
45  // Format: { "sources": [{"filename": "main.tex", "usage": "toplevel"}, ...] }
46  if let Some(main_path) =
47    parse_readme_json(dir, confined).and_then(|name| entry_in(dir, &name, report))
48  {
49    return Ok(main_path);
50  }
51
52  // Phase I.1.2: Check 00README.XXX (legacy arXiv format).
53  // Two directive kinds supported (Perl Pack.pm L82-97):
54  //   `<name> toplevelfile` → shortcut, return directly.
55  //   `<name> ignore`       → exclude `<name>` from heuristic
56  //                            candidate scanning below.
57  // Perl additionally `unlink`s the ignored path; we instead carry
58  // the names through as a Phase-I.2 filter set — safer (no
59  // filesystem mutation in case the directory isn't a sandbox).
60  let mut ignored_names: rustc_hash::FxHashSet<PathBuf> = rustc_hash::FxHashSet::default();
61  if let Some(content) = readme_text(dir, "00README.XXX", confined) {
62    for line in content.lines() {
63      let parts: Vec<&str> = line.split_whitespace().collect();
64      if parts.len() < 2 {
65        continue;
66      }
67      match parts[1] {
68        "toplevelfile" => {
69          if let Some(main_path) = entry_in(dir, parts[0], report) {
70            return Ok(main_path);
71          }
72        },
73        "ignore" => {
74          ignored_names.insert(dir.join(parts[0]));
75        },
76        _ => {},
77      }
78    }
79  }
80
81  // Phase I.2: Heuristic detection (ported from arXiv::FileGuess via Pack.pm)
82  let mut tex_files: Vec<PathBuf> = Vec::new();
83  collect_tex_files(dir, &mut tex_files, false, confined);
84  if !ignored_names.is_empty() {
85    tex_files.retain(|p| !ignored_names.contains(p));
86  }
87  let candidates_before_pdf_filter = tex_files.len();
88  tex_files.retain(|p| !is_pdf_magic(p));
89  if tex_files.is_empty() && candidates_before_pdf_filter > 0 {
90    return Err(s(
91      "Fatal:invalid:not_tex_source PDF magic detected in source file (no TeX-format files in archive)",
92    ));
93  }
94  if tex_files.is_empty() {
95    collect_tex_files(dir, &mut tex_files, true, confined);
96    tex_files.retain(|p| !is_pdf_magic(p));
97    if !ignored_names.is_empty() {
98      tex_files.retain(|p| !ignored_names.contains(p));
99    }
100  }
101  if tex_files.is_empty() {
102    return Err(s("No .tex files found in directory"));
103  }
104
105  // Score each file: likelihood 0-3 (Perl: Main_TeX_likelihood)
106  let mut likelihood: rustc_hash::FxHashMap<PathBuf, f32> = rustc_hash::FxHashMap::default();
107  // (vetoed_path, vetoer_path) — the veto is honored at filtering
108  // time only when the vetoer's score >= the vetee's. Prevents a
109  // 2-line wrapper file (e.g. `\input{main}`) from removing the
110  // documentclass-bearing main.tex. Witness 2307.13586.
111  let mut vetoed: Vec<(PathBuf, PathBuf)> = Vec::new();
112  // The files with a `\begin{document}` line: a driver whose veto holds whatever the scores, as Perl's every veto does
113  // (Pack.pm:180-182) — its `\input{preamble}` names the `\documentclass` file, which outscores it (1402.3465,
114  // 2503.12837, 1505.07539, hep-th0609123: the preamble was converted, Fatal `Document:Malformed`). The wrapper of
115  // 2307.13586 has none. Guard `tests::driver_vetoes_the_preamble_it_inputs`.
116  let mut drivers: rustc_hash::FxHashSet<PathBuf> = rustc_hash::FxHashSet::default();
117  let mut had_auto_ignore = false;
118
119  for tex_file in &tex_files {
120    if !tex_file.exists() {
121      continue;
122    }
123    let Ok(raw) = std::fs::read(tex_file) else {
124      continue;
125    };
126    let content = String::from_utf8_lossy(&raw);
127    let mut maybe_tex = false;
128    let mut maybe_tex_priority = false;
129    let mut maybe_tex_priority2 = false;
130    let mut determined = false;
131
132    for (lineno, raw_line) in content.lines().enumerate() {
133      let lineno1 = lineno + 1;
134      // Perl L117-120: early-line checks (first 10-12 lines)
135      if lineno1 <= 10
136        && (RE_AUTOIGNORE.is_match(raw_line)
137          || RE_TEXINFO.is_match(raw_line)
138          || RE_AUTOINCLUDE.is_match(raw_line))
139      {
140        likelihood.insert(tex_file.clone(), 0.0);
141        if RE_AUTOIGNORE.is_match(raw_line) {
142          had_auto_ignore = true;
143        }
144        determined = true;
145        break;
146      }
147      if lineno1 <= 12
148        && let Some(cap) = RE_FORMAT_HINT.captures(raw_line)
149      {
150        let fmt = &cap[1];
151        if fmt == "latex209" || fmt == "biglatex" || fmt == "latex" || fmt == "LaTeX" {
152          likelihood.insert(tex_file.clone(), 3.0);
153        } else {
154          likelihood.insert(tex_file.clone(), 1.0);
155        }
156        determined = true;
157        break;
158      }
159      // Perl L128: strip ONE `%`-comment up to the next `\r`. `\r`-aware
160      // so bare-`\r` line-ended files (read as one big "line" in Perl
161      // because `$/=\n`) preserve subsequent `\r\documentclass` chunks.
162      let stripped: std::borrow::Cow<str> = RE_STRIP_COMMENT.replacen(raw_line, 1, "");
163      let line: &str = &stripped;
164
165      if RE_DOCCLASS.is_match(line) {
166        likelihood.insert(tex_file.clone(), 3.0);
167        determined = true;
168        break;
169      }
170      if RE_MAYBE_TEX.is_match(line) {
171        maybe_tex = true;
172      }
173      if RE_BEGIN_DOCUMENT.is_match(line) {
174        drivers.insert(tex_file.clone());
175      }
176      // Perl L133-148: \input/\include → veto the included file
177      if let Some(cap) = RE_INPUT_INCLUDE.captures(line) {
178        maybe_tex = true;
179        let mut vetoed_name = cap[1].to_string();
180        if RE_AMSTEX.is_match(&vetoed_name) {
181          likelihood.insert(tex_file.clone(), 2.0);
182          determined = true;
183          break;
184        }
185        if !vetoed_name.contains('.') {
186          vetoed_name = vetoed_name.trim_end().to_string() + ".tex";
187        }
188        let base_dir = tex_file.parent().unwrap_or(dir);
189        vetoed.push((base_dir.join(&vetoed_name), tex_file.clone()));
190      }
191      if RE_END_BYE.is_match(line) {
192        maybe_tex_priority = true;
193      }
194      if RE_END_BYE2.is_match(line) {
195        maybe_tex_priority2 = true;
196      }
197      if RE_MAC_TEX.is_match(line) {
198        likelihood.insert(tex_file.clone(), 1.0);
199        determined = true;
200        break;
201      }
202      if RE_METAFONT.is_match(line) {
203        likelihood.insert(tex_file.clone(), 0.0);
204        determined = true;
205        break;
206      }
207      if RE_BIBTEX.is_match(raw_line) {
208        likelihood.insert(tex_file.clone(), 0.0);
209        determined = true;
210        break;
211      }
212      if RE_UUENCODE.is_match(raw_line) {
213        if maybe_tex_priority {
214          likelihood.insert(tex_file.clone(), 2.0);
215        } else if maybe_tex {
216          likelihood.insert(tex_file.clone(), 1.0);
217        } else {
218          likelihood.insert(tex_file.clone(), 0.0);
219        }
220        determined = true;
221        break;
222      }
223      if RE_WITHDRAWN.is_match(line) {
224        likelihood.insert(tex_file.clone(), 0.0);
225        determined = true;
226        break;
227      }
228    }
229    if !determined {
230      let score = if maybe_tex_priority {
231        2.0
232      } else if maybe_tex_priority2 {
233        1.5
234      } else if maybe_tex {
235        1.0
236      } else {
237        0.0
238      };
239      likelihood.insert(tex_file.clone(), score);
240    }
241  }
242
243  for (vetee, vetoer) in &vetoed {
244    let vetee_score = likelihood.get(vetee).copied().unwrap_or(0.0);
245    let vetoer_score = likelihood.get(vetoer).copied().unwrap_or(0.0);
246    if vetoer_score >= vetee_score || drivers.contains(vetoer) {
247      likelihood.remove(vetee);
248    }
249  }
250
251  let mut candidates: Vec<PathBuf> = likelihood
252    .keys()
253    .filter(|f| likelihood[*f] > 0.0)
254    .cloned()
255    .collect();
256  candidates.sort_by(|a, b| likelihood[b].partial_cmp(&likelihood[a]).unwrap());
257
258  if candidates.is_empty() {
259    if had_auto_ignore {
260      // Perl-faithful: process %auto-ignore sources as normal (the
261      // `%` is a comment, the rest is empty → empty XML output, no
262      // Fatal). Witness: 2307.10758 (12-byte `%auto-ignore` source) —
263      // Perl reports "Conversion complete: No obvious problems"; the
264      // old Rust path turned 90 wp4 corpus entries into hard
265      // failures. Cortex_worker has a sibling fix; both must stay in
266      // sync. Prefer the dirname-matching .tex (arxiv convention
267      // `<id>/<id>.tex`), else the first available.
268      let dir_name = dir.file_name().and_then(|s| s.to_str()).unwrap_or_default();
269      let auto_ignore_main = tex_files
270        .iter()
271        .find(|p| {
272          p.file_stem()
273            .and_then(|s| s.to_str())
274            .is_some_and(|stem| stem == dir_name)
275        })
276        .cloned()
277        .or_else(|| tex_files.first().cloned());
278      if let Some(p) = auto_ignore_main {
279        return Ok(p);
280      }
281    }
282    return Err(s("No viable .tex files found in directory"));
283  }
284
285  let max_score = likelihood[&candidates[0]];
286  candidates.retain(|f| (likelihood[f] - max_score).abs() < f32::EPSILON);
287
288  if candidates.len() > 1 {
289    let min_depth = candidates
290      .iter()
291      .map(|f| f.strip_prefix(dir).unwrap_or(f).components().count())
292      .min()
293      .unwrap_or(0);
294    candidates.retain(|f| f.strip_prefix(dir).unwrap_or(f).components().count() == min_depth);
295  }
296
297  // OXIDIZED_DESIGN #132 (surpass-perl): the `.bbl`-sibling heuristic runs
298  // BEFORE the pdf-`\includegraphics` heuristic — Perl (Pack.pm L197-204)
299  // runs them in the opposite order. arXiv requires the compiled `<main>.bbl`
300  // to be bundled (BibTeX is not re-run), so a candidate with a matching
301  // `.bbl` is the single strongest fingerprint of the real top-level file.
302  // Perl's pdf heuristic, run first, silently eliminates a true main that
303  // delegates all its figures to `\input`-ed section files (hence carries no
304  // direct `\includegraphics`) whenever a shipped class template / how-to /
305  // supplement DOES contain an example `\includegraphics{fig.png}`; the `.bbl`
306  // tie-break that would have rescued it never gets to run. Ordering `.bbl`
307  // first fixes that class. Witnesses (all SHARED-FAILURE vs production Perl,
308  // html_feedback autotex issues): 2407.05010 (#1721, IEEEtran how-to),
309  // 2409.06957 (#6100, ICLR template), 2409.02543 (#5867, supp.tex),
310  // 2406.08688 (#5476, IEEEtran template), 2310.02368 (#4156, IEEE template),
311  // 2505.05625 (#4067, supplementary.tex), 2410.12672 (#2369, ICLR template),
312  // 2410.01562 (#2224, ICASSP template), 2401.17263 (#442, ICML example_paper),
313  // 2403.17719 (#859, rebuttal.tex). When >1 candidate carries a `.bbl` (e.g.
314  // 2506.05564, 2401.07129) the set survives and the later heuristics
315  // (pdf-include, common-name, alphabetical) still discriminate as before.
316  if candidates.len() > 1 {
317    let bbl_candidates: Vec<PathBuf> = candidates
318      .iter()
319      .filter(|f| has_bbl(f, dir, confined))
320      .cloned()
321      .collect();
322    if !bbl_candidates.is_empty() {
323      candidates = bbl_candidates;
324    }
325  }
326
327  if candidates.len() > 1 {
328    let pdf_candidates: Vec<PathBuf> = candidates
329      .iter()
330      .filter(|f| has_pdftex_marker(f))
331      .cloned()
332      .collect();
333    if !pdf_candidates.is_empty() {
334      candidates = pdf_candidates;
335    }
336  }
337
338  if candidates.len() > 1 {
339    let common: Vec<PathBuf> = candidates
340      .iter()
341      .filter(|f| {
342        f.file_name().is_some_and(|n| {
343          let n = n.to_str().unwrap_or("");
344          n == "main.tex" || n == "ms.tex" || n == "paper.tex"
345        })
346      })
347      .cloned()
348      .collect();
349    if !common.is_empty() {
350      candidates = common;
351    }
352  }
353
354  candidates.sort();
355  Ok(
356    candidates
357      .into_iter()
358      .next()
359      .expect("non-empty after filtering"),
360  )
361}
362
363/// Ordered list of top-level `.tex` files: the main document first, then any
364/// **Supplementary-Material** documents that ship alongside it. `find_main_tex`
365/// returns element 0 of this list; embedders that want to convert the whole
366/// submission (main + supplements, appended in order — arXiv's multi-top-level
367/// model, [`submit_legacy_differences`]) drive off the full list.
368///
369/// Detection is deliberately **precision-first / template-safe**. A supplement
370/// is admitted only when it is a `\documentclass` file that (a) ships its own
371/// matching `.bbl` — arXiv's canonical `ms.tex`+`ms.bbl` / `supplement.tex`+
372/// `supplement.bbl` fingerprint, which bundled class *templates* do not have —
373/// and (b) self-identifies as supplementary by `\title` or filename
374/// (`supplement`/`supporting`/`supplemental`/`appendix`/`SI`/`SM`). Both gates
375/// together keep a messy bundle's template from ever being mistaken for a
376/// second document. An explicit `00README` listing two or more top-level files
377/// overrides the heuristic (author intent), still ordered main-first.
378///
379/// Conservative residual: a supplement bundled *without* its own `.bbl`, or one
380/// that does not self-identify, is not auto-detected.
381///
382/// [`submit_legacy_differences`]: https://info.arxiv.org/help/submit_legacy_differences.html
383/// `confined` as for [`find_main_tex`].
384pub fn find_top_level_texs(dir: &Path, confined: bool) -> Result<Vec<PathBuf>, String> {
385  // An explicit multi-file 00README designation wins over the heuristic.
386  let explicit = explicit_top_levels(dir, confined);
387  if explicit.len() >= 2 {
388    return Ok(order_main_first(explicit, dir));
389  }
390  // `explicit_top_levels` has warned of every `00README` entry outside `dir` already.
391  let main = main_tex_in(dir, false, confined)?;
392  // The set of `.bbl`-backed top-level documents at the main's depth — arXiv's
393  // multi-top-level fingerprint. Include `main` even if it ships no `.bbl`
394  // (inline bibliography) so a `.bbl`-backed supplement can still attach to it.
395  let mut set = top_level_bbl_docs(dir, &main, confined);
396  if !set.contains(&main) {
397    set.push(main.clone());
398  }
399  // Split into the single true main (the lone non-supplement) and supplements.
400  // This is done over the whole set rather than trusting `find_main_tex`'s
401  // alphabetical tie-break, which can pick a supplement (e.g. `Appendix.tex`
402  // sorts before `Note.tex`) when two `.bbl` documents are otherwise level.
403  let (mut supps, mains): (Vec<PathBuf>, Vec<PathBuf>) =
404    set.into_iter().partition(|f| is_supplement(f));
405  if mains.len() == 1 && !supps.is_empty() {
406    supps.sort();
407    supps.dedup();
408    let mut tops = mains;
409    tops.extend(supps);
410    return Ok(tops);
411  }
412  // No clean 1-main + supplements split → single-file (unchanged behavior).
413  Ok(vec![main])
414}
415
416// ---------------------------------------------------------------------------
417// Internal helpers.
418// ---------------------------------------------------------------------------
419
420fn s(msg: &str) -> String { msg.to_string() }
421
422/// The file `name` a `00README` marks top-level, inside `dir`; `None` when it is not a file (`.`, a folder), or, with a
423/// `Warning:archive:path`, when `name` is absolute, has a `..` or resolves outside `dir` (Perl `Util/Pack.pm`
424/// `detect_source` L78, L93; OXIDIZED_DESIGN_DIVERGENCES #1166).
425pub fn readme_entry(dir: &Path, name: &str) -> Option<PathBuf> { entry_in(dir, name, true) }
426
427/// [`readme_entry`], warning only when `report`.
428fn entry_in(dir: &Path, name: &str, report: bool) -> Option<PathBuf> {
429  use std::path::Component;
430  let climbs = Path::new(name).components().any(|c| {
431    matches!(
432      c,
433      Component::ParentDir | Component::RootDir | Component::Prefix(_)
434    )
435  });
436  let path = dir.join(name);
437  if !climbs && !path.is_file() {
438    return None;
439  }
440  let inside = !climbs && latexml_core::util::pathname::opens_inside(&path, dir) == Some(true);
441  if inside {
442    return Some(path);
443  }
444  if report {
445    latexml_core::common::error::warn_at_session_start(
446      "archive",
447      "path",
448      format!(
449        "the 00README names '{name}' as a top-level file outside the source directory; ignored"
450      ),
451    );
452  }
453  None
454}
455
456/// All files a `00README.json`/`00README.XXX` explicitly marks as top-level, in
457/// listed order, restricted to those that exist (main-first ordering applied by
458/// the caller). Empty when there is no explicit designation.
459fn explicit_top_levels(dir: &Path, confined: bool) -> Vec<PathBuf> {
460  let mut out: Vec<PathBuf> = Vec::new();
461  for name in parse_readme_json_all(dir, confined) {
462    if let Some(p) = readme_entry(dir, &name)
463      && !out.contains(&p)
464    {
465      out.push(p);
466    }
467  }
468  if let Some(content) = readme_text(dir, "00README.XXX", confined) {
469    for line in content.lines() {
470      let parts: Vec<&str> = line.split_whitespace().collect();
471      if parts.len() >= 2
472        && parts[1] == "toplevelfile"
473        && let Some(p) = readme_entry(dir, parts[0])
474        && !out.contains(&p)
475      {
476        out.push(p);
477      }
478    }
479  }
480  out
481}
482
483/// The set of `.bbl`-backed top-level documents at `main`'s depth: `\document`-
484/// class files that carry their own sibling `.bbl` (arXiv's own top-level
485/// fingerprint, which bundled templates lack), excluding `%auto-ignore` and
486/// `00README` `ignore` files. `main` itself is included when it qualifies.
487fn top_level_bbl_docs(dir: &Path, main: &Path, confined: bool) -> Vec<PathBuf> {
488  let main_depth = main.strip_prefix(dir).unwrap_or(main).components().count();
489  let ignored = readme_ignored(dir, confined);
490  let mut tex_files: Vec<PathBuf> = Vec::new();
491  collect_tex_files(dir, &mut tex_files, false, confined);
492  tex_files
493    .into_iter()
494    .filter(|f| f.strip_prefix(dir).unwrap_or(f).components().count() == main_depth)
495    .filter(|f| !ignored.contains(f))
496    .filter(|f| !has_auto_ignore(f))
497    .filter(|f| has_bbl(f, dir, confined))
498    .filter(|f| file_has_documentclass(f))
499    .collect()
500}
501
502/// Files a `00README.XXX` marks `ignore` (Perl `Pack.pm` `unlink`s them; we
503/// exclude by set — see `find_main_tex`).
504fn readme_ignored(dir: &Path, confined: bool) -> rustc_hash::FxHashSet<PathBuf> {
505  let mut ignored = rustc_hash::FxHashSet::default();
506  if let Some(content) = readme_text(dir, "00README.XXX", confined) {
507    for line in content.lines() {
508      let parts: Vec<&str> = line.split_whitespace().collect();
509      if parts.len() >= 2 && parts[1] == "ignore" {
510        ignored.insert(dir.join(parts[0]));
511      }
512    }
513  }
514  ignored
515}
516
517/// Whether one of the file's first 10 lines carries the `%auto-ignore` marker
518/// (arXiv: keep in the bundle, do not process — `submit_legacy_differences`).
519fn has_auto_ignore(path: &Path) -> bool {
520  let Ok(raw) = std::fs::read(path) else {
521    return false;
522  };
523  String::from_utf8_lossy(&raw)
524    .lines()
525    .take(10)
526    .any(|l| RE_AUTOIGNORE.is_match(l))
527}
528
529/// Order a set of top-level files main-first: any file that looks like a
530/// supplement goes last (arXiv-alphanumeric within each group); among the
531/// non-supplements a `main`/`ms`/`paper` common name is promoted to the front.
532fn order_main_first(mut files: Vec<PathBuf>, _dir: &Path) -> Vec<PathBuf> {
533  files.sort();
534  files.dedup();
535  let (supps, mut mains): (Vec<PathBuf>, Vec<PathBuf>) =
536    files.into_iter().partition(|f| is_supplement(f));
537  if let Some(pos) = mains.iter().position(|f| is_common_main_name(f)) {
538    let m = mains.remove(pos);
539    mains.insert(0, m);
540  }
541  mains.extend(supps);
542  mains
543}
544
545/// Whether the file names itself `main.tex` / `ms.tex` / `paper.tex` (the same
546/// common-name set the single-file heuristic prefers).
547fn is_common_main_name(path: &Path) -> bool {
548  path
549    .file_name()
550    .and_then(|n| n.to_str())
551    .is_some_and(|n| n == "main.tex" || n == "ms.tex" || n == "paper.tex")
552}
553
554/// A top-level `.tex` reads as Supplementary Material when its filename or its
555/// `\title` announces it (`supplement`/`supporting`/`supplemental`/`appendix`/
556/// delimited `SI`/`SM`). Used only among *already* `.bbl`-backed sibling
557/// documents, so this classifies main-vs-supplement; it never promotes a
558/// template into a document.
559fn is_supplement(path: &Path) -> bool {
560  if let Some(stem) = path.file_stem().and_then(|s| s.to_str())
561    && RE_SUPP_NAME.is_match(stem)
562  {
563    return true;
564  }
565  if let Some(title) = first_title(path)
566    && RE_SUPP_TITLE.is_match(&title)
567  {
568    return true;
569  }
570  false
571}
572
573/// True when the file defines a `\documentclass`/`\documentstyle` (i.e. is a
574/// top-level document, not an `\input`-ed fragment).
575fn file_has_documentclass(path: &Path) -> bool {
576  let Ok(raw) = std::fs::read(path) else {
577    return false;
578  };
579  let content = String::from_utf8_lossy(&raw);
580  content.lines().any(|l| {
581    let stripped = RE_STRIP_COMMENT.replacen(l, 1, "");
582    RE_DOCCLASS.is_match(&stripped)
583  })
584}
585
586/// The text of the first non-commented `\title{…}` / `\icmltitle{…}` in the
587/// file (up to ~120 chars), for supplement classification.
588fn first_title(path: &Path) -> Option<String> {
589  let raw = std::fs::read(path).ok()?;
590  let content = String::from_utf8_lossy(&raw);
591  // Strip `%`-comments line-by-line so a commented template placeholder title
592  // (`%% \title{Title}`) does not count. Witness 2402.13498 (elsarticle).
593  let stripped: String = content
594    .lines()
595    .map(|l| RE_STRIP_COMMENT.replacen(l, 1, "").into_owned())
596    .collect::<Vec<_>>()
597    .join("\n");
598  RE_TITLE_ARG
599    .captures(&stripped)
600    .map(|c| c[1].chars().take(120).collect())
601}
602
603/// Parse `00README.json` and return the filenames of **every** `usage ==
604/// "toplevel"` source, in document order. `parse_readme_json` returns only the
605/// first; this drives multi-top-level detection.
606fn parse_readme_json_all(dir: &Path, confined: bool) -> Vec<String> {
607  let mut out = Vec::new();
608  let Some(content) = readme_text(dir, "00README.json", confined) else {
609    return out;
610  };
611  let Some(sources_start) = content.find("\"sources\"") else {
612    return out;
613  };
614  let rest = &content[sources_start..];
615  let (Some(arr_start), Some(arr_end)) = (rest.find('['), rest.find(']')) else {
616    return out;
617  };
618  let arr = &rest[arr_start + 1..arr_end];
619  for obj_str in arr.split('}') {
620    if !obj_str.contains("\"toplevel\"") {
621      continue;
622    }
623    if let Some(fn_pos) = obj_str.find("\"filename\"") {
624      let after = obj_str[fn_pos + 10..].trim_start();
625      if let Some(after) = after.strip_prefix(':') {
626        let after = after.trim_start();
627        if let Some(after) = after.strip_prefix('"') {
628          let name: String = after
629            .chars()
630            .take_while(|&c| c != '"')
631            .filter(|&c| c != '\\')
632            .collect();
633          if !name.is_empty() {
634            out.push(name);
635          }
636        }
637      }
638    }
639  }
640  out
641}
642
643// Perl Pack.pm L25 TEX_EXT = qr/\.(?:[tT](:?[eE][xX]|[xX][tT])|ltx|LTX)$/
644// → .tex, .txt, .ltx (case-insensitive). The `fallback` arm matches Perl
645// Pack/Dir.pm L47: `!/\./ || /\.[^.]{4,}$/` — extension-less or extension
646// ≥4 chars, used when nothing TeX-shaped surfaces in the strict pass.
647/// The candidate files under `dir`; `confined`, those that open inside it: a link leading out of the source directory
648/// is no candidate, as a `00README` entry outside it is none ([`entry_in`]), so a top-level guess never reads outside.
649fn collect_tex_files(dir: &Path, files: &mut Vec<PathBuf>, fallback: bool, confined: bool) {
650  let mut found = Vec::new();
651  collect_tex_files_under(dir, &mut found, fallback);
652  files.extend(
653    found
654      .into_iter()
655      .filter(|file| opens_in(file, dir, confined)),
656  );
657}
658
659/// Whether `file` may be read for the detection: always unconfined, else when it opens inside `dir`.
660fn opens_in(file: &Path, dir: &Path, confined: bool) -> bool {
661  !confined || latexml_core::util::pathname::opens_inside(file, dir) == Some(true)
662}
663
664/// Whether `file` ships its sibling `.bbl`; `confined`, one that opens inside `dir`, so that the existence of a file
665/// outside it never picks the main file.
666fn has_bbl(file: &Path, dir: &Path, confined: bool) -> bool {
667  let bbl = file.with_extension("bbl");
668  if confined {
669    opens_in(&bbl, dir, true)
670  } else {
671    bbl.exists()
672  }
673}
674
675/// The text of the `00README` file `name` in `dir`; `confined`, only when it opens inside it (as `collect_tex_files`
676/// keeps a file).
677pub fn readme_text(dir: &Path, name: &str, confined: bool) -> Option<String> {
678  let path = dir.join(name);
679  opens_in(&path, dir, confined)
680    .then(|| std::fs::read_to_string(&path).ok())
681    .flatten()
682}
683
684fn collect_tex_files_under(dir: &Path, files: &mut Vec<PathBuf>, fallback: bool) {
685  if let Ok(entries) = std::fs::read_dir(dir) {
686    for entry in entries.flatten() {
687      let path = entry.path();
688      // Recurse into real directories only, as Perl's walk does (Util/Pack/Dir.pm:45, File::Find without `follow`):
689      // a link to a directory (an archive's `a -> .`) would cycle without end.
690      if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
691        collect_tex_files_under(&path, files, fallback);
692      } else if path.is_dir() {
693        continue;
694      } else if !fallback {
695        if path.extension().is_some_and(|e| {
696          let e = e.to_ascii_lowercase();
697          e == "tex" || e == "txt" || e == "ltx"
698        }) {
699          files.push(path);
700        }
701      } else {
702        let ext_opt = path.extension().and_then(|e| e.to_str());
703        let keep = match ext_opt {
704          None => true,
705          Some(ext) => ext.len() >= 4,
706        };
707        if keep {
708          files.push(path);
709        }
710      }
711    }
712  }
713}
714
715// Faithful port of Perl `Pack.pm::heuristic_check_for_pdftex` (L222-241):
716// a file counts as a pdf-include candidate only when some line carries
717// `\includegraphics{...ext}` with the raster/pdf extension INSIDE the
718// argument (`\includegraphics[^%]*\.(?:pdf|png|gif|jpg)\s?\}`, case-insensitive,
719// not preceded by a `%`), or a `\pdfoutput=1` marker. Perl's `$pdfoutput_checks`
720// counter clamps at 0, so its `>= 0` guard is always true and the `\pdfoutput`
721// probe effectively scans every line — we mirror that (no first-N-lines cap).
722//
723// The earlier Rust port used a loose whole-file
724// `contains("\\includegraphics") && contains(".png"|".pdf"|".jpg")`, which
725// FALSE-POSITIVES on class templates whose `\includegraphics` examples are
726// extensionless (`{icml_numpapers}`) or `.eps` (`{egfigure.eps}`) yet mention
727// a raster extension elsewhere (prose/comments). Because the pdf heuristic runs
728// before the `.bbl` tie-break, that false positive eliminated the true
729// figure-delegating `main.tex`: 2401.17263 (#442, example_paper.tex) and
730// 2403.17719 (#859, rebuttal.tex) were mis-picked by Rust though Perl picks
731// their `main.tex`. Argument-anchoring restores parity.
732fn has_pdftex_marker(path: &Path) -> bool {
733  let Ok(raw) = std::fs::read(path) else {
734    return false;
735  };
736  let content = String::from_utf8_lossy(&raw);
737  content
738    .lines()
739    .any(|line| RE_PDF_INCLUDE.is_match(line) || RE_PDFOUTPUT.is_match(line))
740}
741
742// Skip files whose magic bytes identify them as PDF (e.g. arXiv source
743// archives that contain a PDF mis-named with a `.tex` extension).
744pub fn is_pdf_magic(path: &Path) -> bool {
745  let mut buf = [0u8; 5];
746  if let Ok(mut f) = std::fs::File::open(path) {
747    use std::io::Read;
748    if f.read(&mut buf).is_ok_and(|n| n == 5) {
749      return &buf == b"%PDF-";
750    }
751  }
752  false
753}
754
755/// Parse `00README.json` in `dir` and return the "filename" of the
756/// toplevel source. Perl Pack.pm L68-80: scans `sources[]` for the
757/// entry tagged `usage == "toplevel"`. Minimal hand-rolled JSON
758/// scanner — we don't pull a full JSON dep just for this.
759fn parse_readme_json(dir: &Path, confined: bool) -> Option<String> {
760  parse_readme_json_all(dir, confined).into_iter().next()
761}
762
763// ---------------------------------------------------------------------------
764// Pre-compiled regexes used by `find_main_tex`. Parking these as module-
765// level `LazyLock<Regex>` keeps a single instance per process and avoids the
766// per-call recompile that nesting them inside the function caused.
767// ---------------------------------------------------------------------------
768
769static RE_AUTOIGNORE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"%auto-ignore").unwrap());
770static RE_TEXINFO: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\\input texinfo").unwrap());
771static RE_AUTOINCLUDE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"%auto-include").unwrap());
772static RE_FORMAT_HINT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\r?%&(\S+)").unwrap());
773static RE_DOCCLASS: LazyLock<Regex> =
774  LazyLock::new(|| Regex::new(r"(?:^|\r)\s*\\document(?:style|class)").unwrap());
775static RE_MAYBE_TEX: LazyLock<Regex> = LazyLock::new(|| {
776  Regex::new(r"(?:^|\r)\s*\\(?:font|magnification|input|def|special|baselineskip|begin)").unwrap()
777});
778static RE_INPUT_INCLUDE: LazyLock<Regex> =
779  LazyLock::new(|| Regex::new(r"\\(?:input|include)(?:\s+|\{)([^ \}]+)").unwrap());
780static RE_END_BYE: LazyLock<Regex> =
781  LazyLock::new(|| Regex::new(r"(?:^|\r)\s*\\(?:end|bye)(?:\s|$)").unwrap());
782static RE_END_BYE2: LazyLock<Regex> =
783  LazyLock::new(|| Regex::new(r"\\(?:end|bye)(?:\s|$)").unwrap());
784static RE_BEGIN_DOCUMENT: LazyLock<Regex> =
785  LazyLock::new(|| Regex::new(r"\\begin\s*\{document\}").unwrap());
786static RE_MAC_TEX: LazyLock<Regex> =
787  LazyLock::new(|| Regex::new(r"\\input *(?:harv|lanl)mac|\\input\s+phyzzx").unwrap());
788static RE_METAFONT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"beginchar\(").unwrap());
789static RE_BIBTEX: LazyLock<Regex> =
790  LazyLock::new(|| Regex::new(r"(?i)(?:^|\r)@(?:book|article|inbook|unpublished)\{").unwrap());
791static RE_UUENCODE: LazyLock<Regex> =
792  LazyLock::new(|| Regex::new(r"^begin \d{1,4}\s+\S+\r?$").unwrap());
793static RE_WITHDRAWN: LazyLock<Regex> =
794  LazyLock::new(|| Regex::new(r"paper deliberately replaced by what little").unwrap());
795static RE_AMSTEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^amstex$").unwrap());
796// Perl `heuristic_check_for_pdftex` pdf-include probe: an `\includegraphics`
797// whose argument names a raster/pdf image (case-insensitive), not behind a `%`.
798static RE_PDF_INCLUDE: LazyLock<Regex> = LazyLock::new(|| {
799  Regex::new(r"(?i)^[^%]*\\includegraphics[^%]*\.(?:pdf|png|gif|jpg)\s?\}").unwrap()
800});
801// Perl `\pdfoutput(?:\s+)?=(?:\s+)?1` marker, not behind a `%`.
802static RE_PDFOUTPUT: LazyLock<Regex> =
803  LazyLock::new(|| Regex::new(r"^[^%]*\\pdfoutput\s*=\s*1").unwrap());
804// Supplementary-Material detection (find_top_level_texs). Filename tokens
805// (`paper_SI`, `supplement`, `z_SI_renamed`, `Supplemental_Materials`) — the
806// short `si`/`sm` forms only as delimited tokens so they can't match a substring.
807static RE_SUPP_NAME: LazyLock<Regex> = LazyLock::new(|| {
808  Regex::new(r"(?i)(^|[_-])(supp(lement(ary|al)?)?|supporting|supplemental|appendix|si|sm)([_-]|$)")
809    .unwrap()
810});
811// Supplement `\title` text ("Supplementary Information for …", "SUPPLEMENTAL
812// MATERIALS", "Supporting Information", "Supplemental Materials for:").
813static RE_SUPP_TITLE: LazyLock<Regex> = LazyLock::new(|| {
814  Regex::new(r"(?i)(supplement|supporting\s+information|supplemental|appendix)").unwrap()
815});
816// First braced argument of a `\title`/`\icmltitle` (comments already stripped).
817static RE_TITLE_ARG: LazyLock<Regex> =
818  LazyLock::new(|| Regex::new(r"\\(?:icml)?title\s*(?:\[[^\]]*\])?\s*\{([^}]*)").unwrap());
819// Strip a single `%`-comment, stopping at the next `\r` so bare-`\r`
820// line-ended files (Mac classic) preserve post-comment `\documentclass`.
821static RE_STRIP_COMMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"%[^\r]*").unwrap());
822
823#[cfg(test)]
824mod tests {
825  use tempfile::tempdir;
826
827  use super::*;
828
829  fn write(dir: &Path, name: &str, body: &str) { std::fs::write(dir.join(name), body).unwrap(); }
830
831  #[test]
832  fn picks_documentclass_over_input_only_file() {
833    let d = tempdir().unwrap();
834    write(
835      d.path(),
836      "main.tex",
837      "\\documentclass{article}\n\\begin{document}x\\end{document}",
838    );
839    write(d.path(), "intro.tex", "\\input{intro_body}\n");
840    let pick = find_main_tex(d.path(), false).unwrap();
841    assert_eq!(pick.file_name().unwrap(), "main.tex");
842  }
843
844  // Pack.pm:180-182 vetoes every `\input` argument; a driver with `\begin{document}` vetoes the `\documentclass` preamble
845  // it inputs although the preamble scores higher (1402.3465, 2503.12837, 1505.07539, hep-th0609123), while a wrapper
846  // without one keeps the score gate (2307.13586).
847  #[test]
848  fn driver_vetoes_the_preamble_it_inputs() {
849    let d = tempdir().unwrap();
850    write(
851      d.path(),
852      "paper.tex",
853      "\\input{preamble}\n\\begin{document}\nMain body text.\n\\end{document}\n",
854    );
855    write(
856      d.path(),
857      "preamble.tex",
858      "\\documentclass{article}\n\\usepackage{amsmath}\n",
859    );
860    let pick = find_main_tex(d.path(), false).unwrap();
861    assert_eq!(pick.file_name().unwrap(), "paper.tex");
862  }
863
864  #[test]
865  fn wrapper_without_begin_document_keeps_its_main() {
866    let d = tempdir().unwrap();
867    write(d.path(), "wrapper.tex", "%\n\\input{main}\n");
868    write(
869      d.path(),
870      "main.tex",
871      "\\documentclass{article}\n\\begin{document}x\\end{document}\n",
872    );
873    let pick = find_main_tex(d.path(), false).unwrap();
874    assert_eq!(pick.file_name().unwrap(), "main.tex");
875  }
876
877  #[test]
878  fn errors_when_directory_has_no_tex() {
879    let d = tempdir().unwrap();
880    let err = find_main_tex(d.path(), false).unwrap_err();
881    assert!(err.contains("No .tex files"));
882  }
883
884  #[test]
885  fn prefers_main_over_other_documentclass_files() {
886    let d = tempdir().unwrap();
887    write(d.path(), "draft.tex", "\\documentclass{article}\n");
888    write(d.path(), "main.tex", "\\documentclass{article}\n");
889    let pick = find_main_tex(d.path(), false).unwrap();
890    assert_eq!(pick.file_name().unwrap(), "main.tex");
891  }
892
893  #[test]
894  fn readme_xxx_toplevelfile_directive_short_circuits() {
895    let d = tempdir().unwrap();
896    // Two candidate documents — main.tex would normally win,
897    // but the 00README directive points at draft.tex.
898    write(d.path(), "draft.tex", "\\documentclass{article}\n");
899    write(d.path(), "main.tex", "\\documentclass{article}\n");
900    write(d.path(), "00README.XXX", "draft.tex toplevelfile\n");
901    let pick = find_main_tex(d.path(), false).unwrap();
902    assert_eq!(pick.file_name().unwrap(), "draft.tex");
903  }
904
905  #[test]
906  fn readme_xxx_ignore_directive_excludes_candidate() {
907    let d = tempdir().unwrap();
908    // Without a directive, `main.tex` would tie with `old.tex`
909    // and the "common name" heuristic prefers `main.tex`. With
910    // an `ignore` directive on main.tex, the heuristic falls back
911    // to `old.tex`.
912    write(d.path(), "old.tex", "\\documentclass{article}\n");
913    write(d.path(), "main.tex", "\\documentclass{article}\n");
914    write(d.path(), "00README.XXX", "main.tex ignore\n");
915    let pick = find_main_tex(d.path(), false).unwrap();
916    assert_eq!(pick.file_name().unwrap(), "old.tex");
917  }
918
919  #[test]
920  fn readme_xxx_mixed_directives() {
921    let d = tempdir().unwrap();
922    write(d.path(), "intro.tex", "\\documentclass{article}\n");
923    write(d.path(), "paper.tex", "\\documentclass{article}\n");
924    write(d.path(), "junk.tex", "\\documentclass{article}\n");
925    // `paper.tex toplevelfile` short-circuits the heuristic; the
926    // ignore line is unreachable in this test but exercises the
927    // parser's multi-line/multi-kind handling.
928    write(
929      d.path(),
930      "00README.XXX",
931      "junk.tex ignore\npaper.tex toplevelfile\n",
932    );
933    let pick = find_main_tex(d.path(), false).unwrap();
934    assert_eq!(pick.file_name().unwrap(), "paper.tex");
935  }
936
937  // OXIDIZED_DESIGN #132: a matching `.bbl` sibling outranks the pdf-include
938  // heuristic. Models the witness class (2407.05010 #1721 et al.): the true
939  // main delegates its figures (no direct `\includegraphics`) but ships a
940  // `main.bbl`, while a class how-to/template carries an example
941  // `\includegraphics{fig.png}`. Perl's pdf-before-bbl order (and our old port)
942  // picked the template; bbl-first recovers the real main.
943  #[test]
944  fn bbl_sibling_outranks_pdf_include_marker() {
945    let d = tempdir().unwrap();
946    write(
947      d.path(),
948      "main.tex",
949      "\\documentclass{IEEEtran}\n\\input{sections/intro}\n\\begin{document}\\title{Real}\\end{document}",
950    );
951    write(
952      d.path(),
953      "New_IEEEtran_how-to.tex",
954      "\\documentclass{IEEEtran}\n\\includegraphics[width=1in]{fig1.png}\n\\begin{document}How to.\\end{document}",
955    );
956    write(
957      d.path(),
958      "main.bbl",
959      "\\begin{thebibliography}{1}\\end{thebibliography}\n",
960    );
961    let pick = find_main_tex(d.path(), false).unwrap();
962    assert_eq!(pick.file_name().unwrap(), "main.tex");
963  }
964
965  // Reorder must not swallow the later common-name tie-break: when >1 candidate
966  // carries a `.bbl` (2506.05564, 2401.07129), the `.bbl` set survives and
967  // main/ms/paper still wins over an alphabetically-earlier sibling.
968  #[test]
969  fn reorder_preserves_common_name_when_multiple_bbl() {
970    let d = tempdir().unwrap();
971    write(
972      d.path(),
973      "aaa.tex",
974      "\\documentclass{article}\n\\includegraphics{x.png}\n",
975    );
976    write(
977      d.path(),
978      "main.tex",
979      "\\documentclass{article}\n\\includegraphics{y.png}\n",
980    );
981    write(d.path(), "aaa.bbl", "");
982    write(d.path(), "main.bbl", "");
983    let pick = find_main_tex(d.path(), false).unwrap();
984    assert_eq!(pick.file_name().unwrap(), "main.tex");
985  }
986
987  // Parity fix (Perl `heuristic_check_for_pdftex`): the extension must sit
988  // INSIDE the `\includegraphics{…}` argument. The old loose whole-file
989  // `contains` false-positived on templates whose examples are extensionless
990  // (2401.17263 #442 `{icml_numpapers}`) or `.eps` (2403.17719 #859
991  // `{egfigure.eps}`) yet mention a raster extension elsewhere.
992  #[test]
993  fn strict_pdf_marker_rejects_extensionless_eps_and_comments() {
994    let d = tempdir().unwrap();
995    // extensionless arg + an unrelated `.png` mention in prose → not a marker
996    write(
997      d.path(),
998      "example_paper.tex",
999      "\\centerline{\\includegraphics[width=\\columnwidth]{icml_numpapers}}\nResults saved as results.png.\n",
1000    );
1001    // `.eps` extension is not in the raster/pdf set
1002    write(
1003      d.path(),
1004      "rebuttal.tex",
1005      "\\includegraphics[width=0.8\\linewidth]{egfigure.eps}\n",
1006    );
1007    // commented-out include must not count (behind `%`)
1008    write(d.path(), "commented.tex", "%\\includegraphics{fig.png}\n");
1009    assert!(!has_pdftex_marker(&d.path().join("example_paper.tex")));
1010    assert!(!has_pdftex_marker(&d.path().join("rebuttal.tex")));
1011    assert!(!has_pdftex_marker(&d.path().join("commented.tex")));
1012  }
1013
1014  #[test]
1015  fn strict_pdf_marker_accepts_arg_extension_and_pdfoutput() {
1016    let d = tempdir().unwrap();
1017    write(
1018      d.path(),
1019      "fig.tex",
1020      "\\includegraphics[width=2in]{diagram.pdf}\n",
1021    );
1022    write(d.path(), "gif.tex", "\\includegraphics{anim.gif}\n"); // Perl includes gif
1023    write(
1024      d.path(),
1025      "pdfout.tex",
1026      "\\pdfoutput=1\n\\includegraphics{noext}\n",
1027    );
1028    assert!(has_pdftex_marker(&d.path().join("fig.tex")));
1029    assert!(has_pdftex_marker(&d.path().join("gif.tex")));
1030    assert!(has_pdftex_marker(&d.path().join("pdfout.tex")));
1031  }
1032
1033  // Multi-top-level detection (find_top_level_texs). Models the real
1034  // main+supplement pattern (2408.13687, 2401.07129, …): both documents carry
1035  // their own `.bbl`; the supplement self-identifies by title/filename.
1036  #[test]
1037  fn top_level_texs_appends_supplement() {
1038    let d = tempdir().unwrap();
1039    write(
1040      d.path(),
1041      "main.tex",
1042      "\\documentclass{article}\n\\title{Quantum error correction}\n",
1043    );
1044    write(
1045      d.path(),
1046      "supplement.tex",
1047      "\\documentclass{article}\n\\title{Supplementary Information for Quantum error correction}\n",
1048    );
1049    write(d.path(), "main.bbl", "");
1050    write(d.path(), "supplement.bbl", "");
1051    let tops = find_top_level_texs(d.path(), false).unwrap();
1052    let names: Vec<_> = tops
1053      .iter()
1054      .map(|p| p.file_name().unwrap().to_str().unwrap())
1055      .collect();
1056    assert_eq!(names, vec!["main.tex", "supplement.tex"]);
1057    // `find_main_tex` stays the first entry.
1058    assert_eq!(find_main_tex(d.path(), false).unwrap(), tops[0]);
1059  }
1060
1061  // Main first even when the supplement sorts alphabetically before it
1062  // (2506.05564: `Note.tex` main + `Appendix.tex` supplement).
1063  #[test]
1064  fn top_level_texs_orders_main_first_despite_alpha() {
1065    let d = tempdir().unwrap();
1066    write(
1067      d.path(),
1068      "Note.tex",
1069      "\\documentclass{article}\n\\title{Bayesian Inference of the Landau Parameter}\n",
1070    );
1071    write(
1072      d.path(),
1073      "Appendix.tex",
1074      "\\documentclass{article}\n\\title{SUPPLEMENTAL MATERIALS}\n",
1075    );
1076    write(d.path(), "Note.bbl", "");
1077    write(d.path(), "Appendix.bbl", "");
1078    let tops = find_top_level_texs(d.path(), false).unwrap();
1079    let names: Vec<_> = tops
1080      .iter()
1081      .map(|p| p.file_name().unwrap().to_str().unwrap())
1082      .collect();
1083    assert_eq!(names, vec!["Note.tex", "Appendix.tex"]);
1084  }
1085
1086  // Template safety: a bundled template (no `.bbl`, does not self-identify as a
1087  // supplement) is never appended, even when it carries example graphics.
1088  #[test]
1089  fn top_level_texs_excludes_template_without_bbl() {
1090    let d = tempdir().unwrap();
1091    write(
1092      d.path(),
1093      "main.tex",
1094      "\\documentclass{IEEEtran}\n\\input{sec}\n\\title{Real Paper}\n",
1095    );
1096    write(
1097      d.path(),
1098      "New_IEEEtran_how-to.tex",
1099      "\\documentclass{IEEEtran}\n\\includegraphics{fig1.png}\n\\title{How to Use the IEEEtran Templates}\n",
1100    );
1101    write(d.path(), "main.bbl", "");
1102    let tops = find_top_level_texs(d.path(), false).unwrap();
1103    let names: Vec<_> = tops
1104      .iter()
1105      .map(|p| p.file_name().unwrap().to_str().unwrap())
1106      .collect();
1107    assert_eq!(names, vec!["main.tex"]);
1108  }
1109
1110  // Precision: a supplement-titled document WITHOUT its own `.bbl` is not
1111  // auto-detected (conservative residual).
1112  #[test]
1113  fn supplement_without_bbl_is_not_detected() {
1114    let d = tempdir().unwrap();
1115    write(
1116      d.path(),
1117      "main.tex",
1118      "\\documentclass{article}\n\\title{Real Paper}\n",
1119    );
1120    write(
1121      d.path(),
1122      "supp.tex",
1123      "\\documentclass{article}\n\\title{Supplementary Information}\n",
1124    );
1125    write(d.path(), "main.bbl", "");
1126    let tops = find_top_level_texs(d.path(), false).unwrap();
1127    assert_eq!(tops.len(), 1);
1128    assert_eq!(tops[0].file_name().unwrap(), "main.tex");
1129  }
1130
1131  // Explicit 00README with two toplevelfile lines → both, main-first even when
1132  // listed supplement-first.
1133  #[test]
1134  fn readme_two_toplevelfiles_ordered_main_first() {
1135    let d = tempdir().unwrap();
1136    write(
1137      d.path(),
1138      "main.tex",
1139      "\\documentclass{article}\n\\title{Paper}\n",
1140    );
1141    write(
1142      d.path(),
1143      "si.tex",
1144      "\\documentclass{article}\n\\title{Supporting Information}\n",
1145    );
1146    write(
1147      d.path(),
1148      "00README.XXX",
1149      "si.tex toplevelfile\nmain.tex toplevelfile\n",
1150    );
1151    let tops = find_top_level_texs(d.path(), false).unwrap();
1152    let names: Vec<_> = tops
1153      .iter()
1154      .map(|p| p.file_name().unwrap().to_str().unwrap())
1155      .collect();
1156    assert_eq!(names, vec!["main.tex", "si.tex"]);
1157  }
1158
1159  /// A `00README` top-level entry outside the source directory (absolute, `..`, a link out) is ignored with one
1160  /// `Warning:archive:path` and the heuristic picks the archive's own main; an entry inside it is kept, unwarned.
1161  #[test]
1162  fn readme_entries_outside_the_source_directory_are_ignored() {
1163    use latexml_core::common::error::{LogStatus, get_status, log_session_warnings};
1164    let root = tempdir().unwrap();
1165    let (src, out) = (root.path().join("src"), root.path().join("x"));
1166    std::fs::create_dir_all(src.join("sub")).unwrap();
1167    std::fs::create_dir_all(&out).unwrap();
1168    let canary = out.join("canary.tex");
1169    write(&out, "canary.tex", "\\documentclass{article}\n");
1170    let abs = canary.to_string_lossy().into_owned();
1171    #[cfg(unix)]
1172    std::os::unix::fs::symlink(&canary, src.join("link.tex")).unwrap();
1173    let json =
1174      |name: &str| format!(r#"{{"sources":[{{"filename":"{name}","usage":"toplevel"}}]}}"#);
1175    let mut rows: Vec<(&str, String, &str, usize)> = vec![
1176      ("00README.json", json("../x/canary.tex"), "main.tex", 1),
1177      ("00README.json", json(&abs), "main.tex", 1),
1178      (
1179        "00README.XXX",
1180        "../x/canary.tex toplevelfile\n".into(),
1181        "main.tex",
1182        1,
1183      ),
1184      (
1185        "00README.XXX",
1186        format!("{abs} toplevelfile\n"),
1187        "main.tex",
1188        1,
1189      ),
1190      ("00README.json", json("sub/../sub/paper.tex"), "main.tex", 1),
1191      ("00README.json", json("sub/paper.tex"), "sub/paper.tex", 0),
1192      ("00README.json", json("absent.tex"), "main.tex", 0),
1193      ("00README.XXX", ". toplevelfile\n".into(), "main.tex", 0),
1194      ("00README.json", json("sub"), "main.tex", 0),
1195    ];
1196    #[cfg(unix)]
1197    rows.push((
1198      "00README.XXX",
1199      "link.tex toplevelfile\n".into(),
1200      "main.tex",
1201      1,
1202    ));
1203    #[cfg(windows)]
1204    rows.push((
1205      "00README.XXX",
1206      "..\\x\\canary.tex toplevelfile\n".into(),
1207      "main.tex",
1208      1,
1209    ));
1210    // A short source directory and an entry whose path passes 260 characters, which Windows canonicalizes to another
1211    // form: both sides are compared in one.
1212    let deep = [
1213      "d".repeat(60),
1214      "e".repeat(60),
1215      "f".repeat(60),
1216      "g".repeat(60),
1217    ]
1218    .join("/");
1219    std::fs::create_dir_all(src.join(&deep)).unwrap();
1220    write(&src.join(&deep), "paper.tex", "\\input{x}\n");
1221    let deep = format!("{deep}/paper.tex");
1222    rows.push(("00README.json", json(&deep), deep.as_str(), 0));
1223    for (readme, body, pick, warnings) in rows {
1224      for name in ["00README.json", "00README.XXX"] {
1225        let _ = std::fs::remove_file(src.join(name));
1226      }
1227      write(
1228        &src,
1229        "main.tex",
1230        "\\documentclass{article}\n\\begin{document}x\\end{document}\n",
1231      );
1232      write(&src.join("sub"), "paper.tex", "\\input{x}\n");
1233      write(&src, readme, &body);
1234      let before = get_status(LogStatus::Warning);
1235      let main = find_main_tex(&src, true).unwrap();
1236      // `find_top_level_texs` reads the entries twice and warns once.
1237      let tops = find_top_level_texs(&src, true).unwrap();
1238      log_session_warnings();
1239      assert_eq!(main, src.join(pick), "{readme}: {body}");
1240      assert_eq!(tops, vec![main], "{readme}: {body}");
1241      assert_eq!(
1242        get_status(LogStatus::Warning) - before,
1243        2 * warnings,
1244        "{readme}: {body}"
1245      );
1246    }
1247  }
1248}