Skip to main content

latexml_core/util/
pathname.rs

1#[cfg(feature = "kpathsea")]
2use std::sync::Mutex;
3use std::{
4  env,
5  path::{Path, PathBuf},
6  sync::{LazyLock, OnceLock},
7};
8
9#[cfg(feature = "kpathsea")]
10use kpathsea::Kpaths;
11use regex::Regex;
12
13mod confinement;
14pub use confinement::{
15  ConfinementGuard, ConfinementSnapshot, InputConfinement, confine, confinement_snapshot,
16  cwd_allowed, is_confined, is_kpse_path_var, own_behalf, probing, read_allowed, read_roots,
17  refuse, refused_exists, refused_inside, requested_as, resume, search_dir_allowed,
18};
19
20/// configuration for filesystem search.
21/// Mirrors Perl `LaTeXML::Util::Pathname::pathname_find`'s named-arg options;
22/// kpsewhich-fallback is NOT one of them — that lives in higher-level
23/// `LaTeXML::Package::FindFile_aux`, which calls `pathname_kpsewhich` after
24/// `pathname_find` returns empty. Keep this struct directory-search-only
25/// for parity.
26#[derive(Debug, Clone, Default)]
27pub struct PathnameFindOptions {
28  /// the allowed/requested paths to search in
29  pub paths:               Option<Vec<String>>,
30  /// the file extensions to search for
31  pub extensions:          Option<Vec<String>>,
32  /// the location of the installation subdirectory (deprecated?)
33  pub installation_subdir: Option<String>,
34}
35
36static LITERAL_PROTOCOL: &str = "literal:";
37static HOME_TILDE: &str = "~";
38// `HOME` first (Unix, and set by some Windows shells), then Windows'
39// native `USERPROFILE`, so `~` expansion works on both platforms.
40static HOME_PATH: LazyLock<String> =
41  LazyLock::new(
42    || match env::var_os("HOME").or_else(|| env::var_os("USERPROFILE")) {
43      Some(val) => val.to_string_lossy().into_owned(),
44      _ => s!("~"),
45    },
46  );
47static PROTOCOL_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(https|http|ftp):").unwrap());
48// The characters for which a confined conversion never asks kpathsea for a name (`confinement::kpse_name_ok`: it
49// expands `$VAR`). The file finder has no such filter, as Perl's FindFile has none: a name with commas, parens,
50// `>` or `|` is looked for as pdflatex looks for it (`\input{5-Ack,terms}`, 2308.13679; `\input{a>b/part}`).
51static PATHNAME_IS_NASTY_RE: LazyLock<Regex> =
52  LazyLock::new(|| Regex::new(r#"[`$;|<>"\x00\n\r]"#).unwrap());
53// TODO: This is very pragmatic for now, we ought to use a real URL path library long-term
54static URL_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\w+://(.+)/([^/]+)$").unwrap());
55// Perl `pathname_is_url` is `$pathname =~ /^($PROTOCOL_RE)/` — the protocol is
56// ANCHORED at the start. The previous `is_url` used `URL_RE` (`^\w+://…`),
57// whose leading `\w+` (which includes `_`) matches a filename PREFIX like
58// `myers_http`, so a JabRef `\bibAnnoteFile{myers_http://…/welcome.html_2014}`
59// key (a filename, NOT a URL) read as a URL → `find_file` returned "exists" →
60// `\IfFileExists` took its true branch → the `_` in the key got typeset in
61// text mode ("Script _ can only appear in math mode"; witness 1509.01434).
62// Match Perl: only `http`/`https`/`ftp` followed by `:` at the very start.
63static URL_PREFIX_RE: LazyLock<Regex> =
64  LazyLock::new(|| Regex::new(r"^(?:https|http|ftp):").unwrap());
65
66/// Process-global kpathsea handle (cross-thread shared, NOT
67/// `thread_local!`).
68///
69/// **Why an exception to the project's no-`Mutex` rule:**
70/// `kpathsea-rs` wraps a C library that maintains process-wide global
71/// state. Calling `Kpaths::new()` more than once per process (as the
72/// per-thread `thread_local!` pattern would do) re-runs the C-side
73/// init and can corrupt internal tables / leak file descriptors;
74/// concretely on systems without TeXLive installed, the second init
75/// fails with "Can't get directory of program name" and previously
76/// crashed `06_cluster_regressions`. The Mutex here is necessary to
77/// guarantee single-init AND single-active-call semantics for the
78/// underlying non-thread-safe C API. Same class of carve-out as
79/// `latexml_core::watchdog::PRE_EXIT_HOOK`. See
80/// `feedback_no_mutex_use_thread_local` in user memory for the
81/// general rule.
82#[cfg(feature = "kpathsea")]
83static KPSE: LazyLock<Mutex<Option<Kpaths>>> = LazyLock::new(|| Mutex::new(select_kpaths()));
84
85/// Which kpathsea backend this process resolved. Reported by
86/// [`kpathsea_backend`] so a host-resolution problem is diagnosable from the
87/// log instead of surfacing only as indistinguishable "can't find file" errors.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum KpathseaBackend {
90  /// Linked libkpathsea, resolved in-process (the fast path).
91  InProcess,
92  /// Delegating to the host's `kpsewhich` executable.
93  Subprocess,
94  /// No backend could be constructed — EVERY file lookup returns `None`.
95  Unavailable,
96}
97
98impl KpathseaBackend {
99  /// Short label, for the per-conversion log line.
100  pub fn as_str(self) -> &'static str {
101    match self {
102      Self::InProcess => "in-process",
103      Self::Subprocess => "subprocess kpsewhich",
104      Self::Unavailable => "unavailable",
105    }
106  }
107}
108
109/// The resolved backend and why, recorded by `select_kpaths`.
110#[cfg(feature = "kpathsea")]
111static BACKEND: OnceLock<(KpathseaBackend, &'static str)> = OnceLock::new();
112
113/// The backend this process resolved, with a short reason. Forces the `KPSE`
114/// initialization so the answer is always the real one.
115#[cfg(feature = "kpathsea")]
116pub fn kpathsea_backend() -> (KpathseaBackend, &'static str) {
117  drop(KPSE.lock().unwrap());
118  *BACKEND
119    .get()
120    .unwrap_or(&(KpathseaBackend::Unavailable, "not initialized"))
121}
122
123/// Without the `kpathsea` feature there is no backend at all.
124#[cfg(not(feature = "kpathsea"))]
125pub fn kpathsea_backend() -> (KpathseaBackend, &'static str) {
126  (
127    KpathseaBackend::Unavailable,
128    "built without the kpathsea feature",
129  )
130}
131
132/// The backend-selection policy, with its effects injected so every branch is
133/// testable without a MiKTeX (or TeX-less) host.
134///
135/// The in-process (statically linked) backend is the fast path — it resolves
136/// against the host `ls-R` with no subprocess per lookup, ~0.5 s/conversion
137/// cheaper than shelling out — so it is preferred wherever it actually works,
138/// with the subprocess backend as the portable fallback. Net: TeX Live keeps
139/// the in-process speed, MiKTeX works with no configuration, one binary.
140#[cfg(feature = "kpathsea")]
141fn choose_kpaths(
142  banner: Option<&str>,
143  new_in_process: impl FnOnce() -> Result<Kpaths, &'static str>,
144  new_subprocess: impl Fn() -> Result<Kpaths, &'static str>,
145  can_resolve: impl FnOnce(&Kpaths) -> bool,
146  same_tree_as_ambient: impl FnOnce(&Kpaths) -> bool,
147) -> (Option<Kpaths>, KpathseaBackend, &'static str) {
148  // MiKTeX stores its file database in an MPM `fndb` that a statically-linked
149  // libkpathsea cannot read (MiKTeX ships no `ls-R`), so the in-process backend
150  // resolves nothing there. Detecting it from the `kpsewhich --version` banner
151  // BEFORE any `Kpaths::new()` also avoids the C library's "configuration file
152  // texmf.cnf not found" warning while it fails to anchor on the MiKTeX tree.
153  if banner.is_some_and(|b| b.contains("MiKTeX"))
154    && let Ok(subprocess) = new_subprocess()
155  {
156    return (Some(subprocess), KpathseaBackend::Subprocess, "MiKTeX host");
157  }
158  match new_in_process() {
159    // Sentinel backstop for any OTHER distro whose tree the linked lib can't
160    // read. `new_subprocess()` is pure Rust (no C-side re-init), so this second
161    // construction is safe next to the Mutex carve-out documented above.
162    Ok(kpse) if kpse.is_in_process() && !can_resolve(&kpse) => match new_subprocess() {
163      Ok(subprocess) => (
164        Some(subprocess),
165        KpathseaBackend::Subprocess,
166        "linked libkpathsea resolved no host files",
167      ),
168      // Keep the in-process handle: degraded beats nothing.
169      Err(_) => (
170        Some(kpse),
171        KpathseaBackend::InProcess,
172        "linked libkpathsea resolves no host files, and no kpsewhich to fall back to",
173      ),
174    },
175    // Dual-TL guard: the linked library anchors on its COMPILE-TIME distro
176    // tree, while dump-year detection follows the PATH `kpsewhich`
177    // (SELFAUTOPARENT). On a host with both (vendor TL on PATH + distro TL in
178    // /usr/share/texlive) the two silently disagree — raw kernel sources
179    // (latex.ltx / expl3-code.tex / every .sty) then come from a DIFFERENT
180    // TeX Live than the one the embedded dump was labeled and built for
181    // (caught 2026-08-31: a "2025" dump carrying TL2023 expl3, and
182    // `\g__pdf_backend_object_int already defined` clashes when the fresh
183    // dump met the old tree). File resolution must agree with the ambient
184    // kpsewhich, so fall back to the subprocess backend, which follows PATH.
185    // TEXMF* env overrides re-anchor the linked lib, so a pinned environment
186    // (tools/make_formats.sh, perfect-kernel harness) keeps the fast path.
187    Ok(kpse) if kpse.is_in_process() && !same_tree_as_ambient(&kpse) => match new_subprocess() {
188      Ok(subprocess) => (
189        Some(subprocess),
190        KpathseaBackend::Subprocess,
191        "linked libkpathsea anchors a different TeX tree than the PATH kpsewhich",
192      ),
193      Err(_) => (
194        Some(kpse),
195        KpathseaBackend::InProcess,
196        "linked libkpathsea anchors a different TeX tree, and no kpsewhich to fall back to",
197      ),
198    },
199    Ok(kpse) if kpse.is_in_process() => (Some(kpse), KpathseaBackend::InProcess, "linked"),
200    Ok(kpse) => (
201      Some(kpse),
202      KpathseaBackend::Subprocess,
203      "no linked libkpathsea",
204    ),
205    // Never give up without trying the other backend: this is the only path
206    // that would otherwise disable file resolution entirely, and it used to do
207    // so silently (`Kpaths::new().ok()?`).
208    Err(_) => match new_subprocess() {
209      Ok(subprocess) => (
210        Some(subprocess),
211        KpathseaBackend::Subprocess,
212        "libkpathsea unavailable",
213      ),
214      Err(_) => (
215        None,
216        KpathseaBackend::Unavailable,
217        "no usable libkpathsea and no kpsewhich executable",
218      ),
219    },
220  }
221}
222
223#[cfg(feature = "kpathsea")]
224pub use kpathsea::{TEXMF_ROOT_VARS, TrimmedRoot, trim_texmf_root};
225
226/// The kpathsea crate's TEXMF root variables (0.3.6), for a build without it.
227#[cfg(not(feature = "kpathsea"))]
228pub const TEXMF_ROOT_VARS: [&str; 9] = [
229  "TEXMFROOT",
230  "TEXMFDIST",
231  "TEXMFMAIN",
232  "TEXMFLOCAL",
233  "TEXMFSYSVAR",
234  "TEXMFSYSCONFIG",
235  "TEXMFHOME",
236  "TEXMFVAR",
237  "TEXMFCONFIG",
238];
239
240/// The kpathsea crate's `trim_texmf_root` (0.3.6), for a build without it: `value` without its trailing separators,
241/// `None` when there are none; path lists, brace lists and file-system or drive roots stay (issue #950).
242#[cfg(not(feature = "kpathsea"))]
243pub fn trim_texmf_root(value: &str) -> Option<String> {
244  let (separators, list_separator): (&[char], char) = if cfg!(windows) {
245    (&['/', '\\'], ';')
246  } else {
247    (&['/'], ':')
248  };
249  if value.contains([list_separator, ',', '{']) {
250    return None;
251  }
252  let stem = value.trim_end_matches(separators);
253  let is_drive = cfg!(windows) && stem.len() == 2 && stem.ends_with(':');
254  let keep = if stem.is_empty() || is_drive {
255    stem.len() + 1
256  } else {
257    stem.len()
258  };
259  (keep < value.len()).then(|| value[..keep].to_string())
260}
261
262/// The TEXMF root variables whose trailing separator the kpathsea crate trimmed (>= 0.3.6, issue #950), for the
263/// conversion log. Forces the kpathsea initialization, like [`kpathsea_backend`].
264#[cfg(feature = "kpathsea")]
265pub fn trimmed_texmf_roots() -> &'static [TrimmedRoot] {
266  drop(
267    KPSE
268      .lock()
269      .unwrap_or_else(std::sync::PoisonError::into_inner),
270  );
271  kpathsea::trimmed_texmf_roots()
272}
273
274/// Without the `kpathsea` feature nothing reads the TEXMF roots.
275#[cfg(not(feature = "kpathsea"))]
276pub fn trimmed_texmf_roots() -> &'static [TrimmedRoot] { &[] }
277
278/// The kpathsea crate's `TrimmedRoot`, for a build without it.
279#[cfg(not(feature = "kpathsea"))]
280#[derive(Debug, Clone, PartialEq, Eq)]
281pub struct TrimmedRoot {
282  /// The variable, one of [`TEXMF_ROOT_VARS`].
283  pub var:   &'static str,
284  /// Its value as given.
285  pub given: String,
286  /// The value used.
287  pub used:  String,
288}
289
290/// The TEXMF root variables set now with a trailing separator, each with its trimmed value (issue #950): what a
291/// spawned TeX tool must be given, as the kpathsea crate gives the linked library and its own `kpsewhich` spawns.
292pub fn texmf_root_env() -> Vec<(&'static str, String)> {
293  TEXMF_ROOT_VARS
294    .iter()
295    .filter_map(|&var| Some((var, trim_texmf_root(&env::var(var).ok()?)?)))
296    .collect()
297}
298
299/// A command for a TeX tool (`kpsewhich`, `pdflatex`, `texlua`, …) given [`texmf_root_env`]: a root ending in `/`
300/// would make it walk the whole tree and resolve nothing (issue #950). Sets nothing when no root has one.
301pub fn tex_tool_command(program: impl AsRef<std::ffi::OsStr>) -> std::process::Command {
302  let mut command = std::process::Command::new(program);
303  command.envs(texmf_root_env());
304  command
305}
306
307/// Pick the kpathsea backend that can actually resolve host files, and record
308/// the choice for [`kpathsea_backend`].
309#[cfg(feature = "kpathsea")]
310fn select_kpaths() -> Option<Kpaths> {
311  // Re-anchor the linked libkpathsea to the ambient TeX Live tree before
312  // construction if TEXMFROOT is not already set. In-process libkpathsea checks
313  // $TEXMFROOT in texmf.cnf, avoiding a fallback to the slow subprocess backend
314  // on dual-TL hosts (e.g. system libkpathsea in /usr/share/texlive vs vendor TL on PATH).
315  if env::var_os("TEXMFROOT").is_none()
316    && let Some(root) = ambient_texlive_root()
317  {
318    unsafe {
319      env::set_var("TEXMFROOT", root);
320    }
321  }
322  let (kpse, backend, why) = choose_kpaths(
323    ambient_kpsewhich_version(),
324    Kpaths::new,
325    Kpaths::new_subprocess,
326    // `cmr10.tfm` is present in every TeX distribution, and the probe returns
327    // `None` fast on MiKTeX — no directory walk.
328    |kpse| kpse.find_file("cmr10.tfm").is_some(),
329    // Dual-TL agreement probe: when the ambient kpsewhich names a real
330    // year-rooted TeX Live (SELFAUTOPARENT with a texmf-dist), the linked
331    // library must resolve the kernel from under it. `latex.ltx` is the
332    // signature file — it is what the dump-year label is about. Hosts where
333    // SELFAUTOPARENT is unusable (Debian: /usr; Homebrew Cellar; MiKTeX)
334    // yield `None` and the check is a no-op.
335    |kpse| match ambient_texlive_root() {
336      None => true,
337      Some(root) => kpse
338        .find_file("latex.ltx")
339        .is_none_or(|p| path_is_under(&p, root)),
340    },
341  );
342  let _ = BACKEND.set((backend, why));
343  kpse
344}
345
346/// Whether `path` lies under the directory `root`, as the file system compares names: on Windows without regard to
347/// letter case or `\` vs `/`. kpsewhich there names the root `C:/texlive/2026` (SELFAUTOPARENT) while the linked
348/// library resolves `c:/texlive/2026/texmf-dist/…/latex.ltx`, so a plain prefix test called the one tree two, and every
349/// conversion fell back to the subprocess backend (~270 ms a lookup, `docs/performance/WINDOWS_PERFORMANCE.md`).
350#[cfg(feature = "kpathsea")]
351fn path_is_under(path: &str, root: &str) -> bool {
352  let fold = |s: &str| {
353    if cfg!(windows) {
354      s.replace('\\', "/").to_ascii_lowercase()
355    } else {
356      s.to_string()
357    }
358  };
359  let (path, root) = (fold(path), fold(root));
360  let root = root.trim_end_matches('/');
361  path
362    .strip_prefix(root)
363    .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
364}
365
366/// The ambient `kpsewhich -var-value=SELFAUTOPARENT`, memoized, validated to
367/// be a directory containing `texmf-dist` (i.e. a real TeX Live root —
368/// Debian's `/usr` and other yearless layouts return `None`). Shared by the
369/// kpathsea backend agreement probe above; `latexml_engine::dump_paths` keys
370/// its dump-year detection off the same variable.
371/// The ambient `kpsewhich -var-value=SELFAUTOPARENT` output, memoized for the
372/// process so `select_kpaths` and `latexml_engine::dump_paths` share one spawn.
373///
374/// NOT gated on the `kpathsea` feature: it is a plain subprocess probe (no C
375/// library), matching [`ambient_kpsewhich_version`].
376pub fn ambient_kpsewhich_selfautoparent() -> Option<&'static str> {
377  static SELF_AUTO_PARENT: OnceLock<Option<String>> = OnceLock::new();
378  SELF_AUTO_PARENT
379    .get_or_init(|| {
380      let out = tex_tool_command("kpsewhich")
381        .args(["-var-value=SELFAUTOPARENT"])
382        .output()
383        .ok()?;
384      if !out.status.success() {
385        return None;
386      }
387      let root = String::from_utf8(out.stdout).ok()?.trim().to_string();
388      if root.is_empty() { None } else { Some(root) }
389    })
390    .as_deref()
391}
392
393#[cfg(feature = "kpathsea")]
394fn ambient_texlive_root() -> Option<&'static str> {
395  let root = ambient_kpsewhich_selfautoparent()?;
396  Path::new(root).join("texmf-dist").is_dir().then_some(root)
397}
398
399/// The ambient `kpsewhich --version` banner (full stdout), memoized for the
400/// process. It is a global property of the host TeX install, and several
401/// consumers read it — kpathsea backend selection (`select_kpaths`) and
402/// ambient-year detection (in `latexml_engine`; the year-based latex-dump
403/// staleness check in turn consumes that detected year) — so `kpsewhich` is
404/// spawned at most once. Returns `None` if kpsewhich is absent or the call
405/// fails.
406///
407/// NOT gated on the `kpathsea` feature: it is a plain subprocess probe (no C
408/// library), so the year/stamp logic can share it even in the host-side codegen
409/// build. Lives here — the lowest crate that constructs `Kpaths` — so both the
410/// backend choice and `latexml_engine` resolve the same single spawn.
411pub fn ambient_kpsewhich_version() -> Option<&'static str> {
412  static BANNER: OnceLock<Option<String>> = OnceLock::new();
413  BANNER
414    .get_or_init(|| {
415      let out = tex_tool_command("kpsewhich")
416        .arg("--version")
417        .output()
418        .ok()?;
419      if !out.status.success() {
420        return None;
421      }
422      String::from_utf8(out.stdout).ok()
423    })
424    .as_deref()
425}
426
427/// Force-initialize the kpathsea global state and warm up the per-
428/// format suffix tables.
429///
430/// **Why:** `Kpaths::find_file` lazily inits the kpse format-info
431/// table for each format type the first time a matching filename is
432/// looked up. The chain is
433/// `find_file → guess_format_from_filename → kpathsea_init_format →
434/// kpathsea_init_db → kpathsea_cnf_get → hash_insert_normalized`,
435/// taking ~30-40 ms total across the first dozen lookups. Profile
436/// data on 1910.01256 attributes ~3.5% of wall to that chain.
437///
438/// **What this does:** acquires the `KPSE` mutex once and runs a
439/// single `find_file` probe per common file format. Each probe
440/// guarantees `kpathsea_init_format` runs for that format type, so
441/// every subsequent real lookup hits the post-init fast path.
442///
443/// **Concurrency:** safe to invoke on a background thread spawned at
444/// process start **only after [`init_kpathsea`] has run on the spawning
445/// thread** — see there. `KPSE` is process-global (`LazyLock<Mutex<…>>`), so
446/// the init done on a background thread is visible to the main thread.
447/// The Mutex briefly serializes the prewarm against the main thread's
448/// first real lookup, but dump load + arg parsing take >50 ms before
449/// digest reaches its first package resolution, by which point the
450/// prewarm is usually finished. Idempotent: re-entry while in flight
451/// is a no-op (lock contention only).
452#[cfg(feature = "kpathsea")]
453pub fn prewarm_kpathsea() {
454  // Run exactly once per process: libkpathsea's format-info tables are
455  // process-global, so warming them once is enough. The `Once` also lets the
456  // CLI's early background prewarm and the shared `Converter::initialize_session`
457  // call coordinate — whichever runs first warms; any other caller blocks here
458  // until it completes (guaranteeing warm-before-first-lookup) instead of
459  // re-taking the `KPSE` mutex and re-probing 11 sentinels on every session.
460  static PREWARM_ONCE: std::sync::Once = std::sync::Once::new();
461  PREWARM_ONCE.call_once(|| {
462    let kpse_guard = KPSE.lock().unwrap();
463    let Some(ref kpse) = *kpse_guard else {
464      return;
465    };
466    // Subprocess backend (kpathsea 0.3, hosts without libkpathsea — e.g.
467    // MacTeX): there is no in-process format-info table to warm, and each
468    // sentinel would cost a real `kpsewhich` subprocess invocation
469    // (~10-20 ms × 11). The backend builds its own ls-R cache lazily on
470    // the first real lookup instead.
471    if !kpse.is_in_process() {
472      return;
473    }
474    for sentinel in &[
475      "warmup_lxoxide.tex",
476      "warmup_lxoxide.sty",
477      "warmup_lxoxide.cls",
478      "warmup_lxoxide.def",
479      "warmup_lxoxide.bst",
480      "warmup_lxoxide.fmt",
481      "warmup_lxoxide.afm",
482      "warmup_lxoxide.tfm",
483      "warmup_lxoxide.pfb",
484      "warmup_lxoxide.enc",
485      "warmup_lxoxide.map",
486    ] {
487      // catch_unwind defends against kpathsea-0.2.3 overflow bug (see
488      // kpsewhich docs).
489      let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kpse.find_file(sentinel)));
490    }
491  });
492}
493
494/// No-op when built without the `kpathsea` feature (e.g. the host-side
495/// proc-macro build, which never resolves TeX files).
496#[cfg(not(feature = "kpathsea"))]
497pub fn prewarm_kpathsea() {}
498
499/// Construct the process-wide kpathsea handle NOW, on the calling thread,
500/// before any other thread exists that might read the environment.
501///
502/// `Kpaths::new` runs libkpathsea's `kpathsea_set_program_name`, which
503/// `putenv`s `SELFAUTOLOC`/`SELFAUTODIR`/`SELFAUTOPARENT`/
504/// `SELFAUTOGRANDPARENT` (progname.c). glibc's `putenv` of a new name
505/// reallocates the `environ` array and frees the old one; a concurrent
506/// `getenv` on another thread — `std::env::var`, chrono's `TZ` read inside
507/// `localtime_r`, the logger's `NO_COLOR` probe — walks the freed array.
508/// That is undefined behaviour with no lock to take: glibc's `getenv` is
509/// lock-free by contract, so the only sound ordering is "all `putenv`
510/// before any second thread". The CLI used to run this construction on
511/// the prewarm thread while the worker thread parsed options: sweep #35
512/// (release build, 2374 docs) caught one general-protection fault in
513/// `getenv+0x56` (`traps: latexml_oxide.s[1711120] general protection
514/// fault … in libc.so.6`, pstool/pstool at 1.1 s, unreproducible in 9
515/// reruns — a race, not a document).
516///
517/// Cost: ~0.1 ms for the construction plus the two memoized `kpsewhich`
518/// probes (`--version`, `-var-value=SELFAUTOPARENT`) that pick the
519/// backend. The expensive part of kpathsea start-up — `kpathsea_init_db`
520/// on the first lookup — is read-only with respect to the environment and
521/// stays on the [`prewarm_kpathsea`] background thread.
522#[cfg(feature = "kpathsea")]
523pub fn init_kpathsea() {
524  // Forces the `LazyLock` (= `select_kpaths()`); the guard is released at once.
525  drop(
526    KPSE
527      .lock()
528      .unwrap_or_else(std::sync::PoisonError::into_inner),
529  );
530}
531
532#[cfg(not(feature = "kpathsea"))]
533pub fn init_kpathsea() {}
534
535// Perl: $pathname =~ s|^($PROTOCOL_RE//[^/]*)/|/|
536static CANONICAL_URL_RE: LazyLock<Regex> =
537  LazyLock::new(|| Regex::new(r"^((?:https|http|ftp)://[^/]*)").unwrap());
538
539// static ref INSTALLDIRS : Vec<String> = match env::current_exe() {
540//     Ok(exe_path) => {
541//       match exe_path.as_path().parent() {
542//         Some(_) => Vec::new(),
543//         // Some(p) => vec![
544//         //                 p.to_string_lossy().to_string() + ".",
545//         //                 p.to_string_lossy().to_string() + "./..",
546//         //                 p.to_string_lossy().to_string() + "./../..",
547//         //                 p.to_string_lossy().to_string() + "./../../..",
548//         //                 p.to_string_lossy().to_string() + "./../../../.."],
549
550// TODO: HACK, see note on INSTALLDIRS further down
551//         None => Vec::new()
552//       }
553//     },
554//     _ => Vec::new()
555//   };
556
557// TODO:
558// grep { (-f "$_.pm") && (-d $_) }
559// map { pathname_canonical($_ . $SEP . 'LaTeXML') } @INC;    # [CONSTANT]
560
561/// checks if the path is a conforming URL string
562pub fn is_url(path: &str) -> bool { URL_PREFIX_RE.is_match(path) }
563/// checks if the path starts with the "literal:" protocol
564pub fn is_literaldata(data: &str) -> bool { data.starts_with(LITERAL_PROTOCOL) }
565
566/// check whether a pathname is reloadable as a TeX definition
567pub fn is_reloadable(pathname: &str) -> bool {
568  let (_dir, _name, ext) = split(pathname);
569  // babel.sty exception:
570  // we know the same .ldf file may be reloaded with a different option,
571  // to load an adjacently defined language, so allow that.
572  ext == "ldf"
573}
574/// Check whether a pathname is a raw TeX source or definition file.
575/// Perl: pathname_is_raw
576pub fn is_raw(pathname: &str) -> bool {
577  matches!(
578    extension(pathname).as_str(),
579    "tex" | "pool" | "sty" | "cls" | "clo" | "cnf" | "cfg" | "ldf" | "def" | "dfu"
580  )
581}
582
583/// Whether `path`, canonical (a leading `~` expanded), is absolute: Perl `pathname_is_absolute`, File::Spec's
584/// `file_name_is_absolute`. On Windows a rooted path without a drive (`/figs`, `\\figs`) counts, as
585/// `File::Spec::Win32` counts it, where `Path::is_absolute` asks for a drive; a drive-relative `C:figs` does not.
586pub fn is_absolute(path: &str) -> bool {
587  let canonical = canonical(path);
588  let path = Path::new(&canonical);
589  path.is_absolute() || path.has_root()
590}
591/// convert a (possibly relative) file path to an absolute one
592///
593/// `std::fs::canonicalize` requires the path to exist; many callers hand
594/// us paths that haven't been resolved yet (e.g. `\import{subdir}{f.sty}`
595/// constructs `subdir/f.sty` before `find_file` probes other dirs).
596/// Mirror Perl's `Cwd::abs_path`-style behavior: produce a lexically
597/// absolute path joined against `current_dir()` when the input is
598/// relative, then run it through our `canonical()` to collapse `.`/`..`
599/// components.
600///
601/// Panics only if `current_dir()` itself fails — that means the cwd was
602/// deleted out from under us, which we cannot safely resolve a relative
603/// path against (and silently returning the input could let a relative
604/// file reference target an attacker-controlled path).
605pub fn absolute(path: &str) -> String {
606  let p = Path::new(path);
607  let joined: PathBuf = if p.is_absolute() {
608    p.to_path_buf()
609  } else {
610    let cwd = env::current_dir().expect("cannot make path absolute: current_dir() failed");
611    cwd.join(p)
612  };
613  canonical(&joined.to_string_lossy())
614}
615
616/// Split the pathname into components (dir,name,type).
617/// If pathname is absolute, dir starts with volume or '/'
618pub fn split(pathname: &str) -> (String, String, String) {
619  let canonical_pathname = canonical(pathname);
620  let canonical_path = Path::new(&canonical_pathname);
621  let pathdir = match canonical_path.parent() {
622    Some(dir) => dir.to_string_lossy().to_string(),
623    None => String::new(),
624  };
625  let name = match canonical_path.file_stem() {
626    Some(n) => n.to_string_lossy().to_string(),
627    None => String::new(),
628  };
629  // Perl pathname_split preserves case: `$name =~ s/\.([^\.]+)$//`
630  let pathname_ext = match canonical_path.extension() {
631    Some(e) => e.to_string_lossy().to_string(),
632    None => String::new(),
633  };
634  (pathdir, name, pathname_ext)
635}
636
637///  Simple logic for splitting a URL into protocol://base/path
638pub fn url_split(url: &str) -> (&str, &str) {
639  if let Some(caps) = URL_RE.captures(url) {
640    (
641      caps.get(1).map_or("", |m| m.as_str()),
642      caps.get(2).map_or("", |m| m.as_str()),
643    )
644  } else {
645    (url, "index.tex") // Well, what other default makes sense?
646  }
647}
648
649/// The verbatim prefix Windows' `canonicalize` puts before a path (`\\?\C:\…`), and its forward-slash spelling once the
650/// separators are normalised (`//?/C:/…`). A path prefix, not a TeX token: the kernel token-spelling pin counts it here, once.
651pub const WINDOWS_VERBATIM_PREFIXES: [&str; 2] = [r"\\?\", "//?/"];
652
653/// `path` without a leading Windows verbatim prefix (either spelling), for display.
654pub fn strip_windows_verbatim_prefix(path: &str) -> &str {
655  WINDOWS_VERBATIM_PREFIXES
656    .iter()
657    .find_map(|prefix| path.strip_prefix(prefix))
658    .unwrap_or(path)
659}
660
661/// `std::fs::canonicalize` as a path the rest of the system can read: on Windows std returns the verbatim form
662/// (`\\?\C:\dir\f.tex`), which is dropped back to `C:\dir\f.tex` when that names the same file (a drive path; a
663/// `\\?\UNC\…` share or an over-long path keeps it). Kept verbatim, the prefix reached the source directory and every
664/// path built from it — `\graphicspath` entries `\\?\C:\…\tmp/figs/` that matched no file, EPS candidates listed twice,
665/// locators printed as `//?/C:/…`.
666pub fn canonicalize(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
667  let canonical = std::fs::canonicalize(path)?;
668  if cfg!(windows)
669    && let Some(s) = canonical.to_str()
670    && let Some(rest) = s.strip_prefix(WINDOWS_VERBATIM_PREFIXES[0])
671    && rest.as_bytes().get(1) == Some(&b':')
672    && rest.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
673    && rest.len() < 260
674  {
675    return Ok(PathBuf::from(rest));
676  }
677  Ok(canonical)
678}
679
680/// Canonicalize a pathname by simplifying redundant separators, `.` and `..` components.
681/// Matches Perl's pathname_canonical from Pathname.pm.
682pub fn canonical(pathname: &str) -> String {
683  if is_literaldata(pathname) {
684    return pathname.to_owned();
685  }
686  // Don't call is_absolute, etc, here, cause THEY call US!
687  let home_path: &str = &HOME_PATH;
688
689  let mut pathname = if pathname.starts_with(HOME_TILDE) {
690    pathname.replacen(HOME_TILDE, home_path, 1)
691  } else {
692    pathname.to_string()
693  };
694
695  // Windows: the whole string-pathname layer speaks `/`, faithful to Perl
696  // (whose Windows pathname_canonical likewise sees mostly `/`; kpsewhich
697  // on TL-Windows returns `C:/texlive/...`). OS-originated strings
698  // (std::env::temp_dir, current_dir, PathBuf displays) arrive
699  // `\`-separated, so normalize here — the single choke point every
700  // pathname_* helper funnels through. Unix is untouched: `\` is a legal
701  // filename byte there.
702  #[cfg(windows)]
703  {
704    if pathname.contains('\\') {
705      pathname = pathname.replace('\\', "/");
706    }
707  }
708
709  // Handle URL prefix: strip protocol://host before normalizing path
710  let url_prefix = if let Some(caps) = CANONICAL_URL_RE.captures(&pathname) {
711    let prefix = caps.get(1).unwrap().as_str().to_string();
712    pathname = pathname[prefix.len()..].to_string();
713    Some(prefix)
714  } else {
715    None
716  };
717
718  // Perl: $pathname =~ s|/\./|/|g;
719  while pathname.contains("/./") {
720    pathname = pathname.replace("/./", "/");
721  }
722  // Perl: while ($pathname =~ s|/(?!\.\./)[^/]+/\.\.(/|$)|$1|) { }
723  // Collapse /foo/.. patterns but not /../..
724  // Implemented without lookahead since the regex crate doesn't support it.
725  loop {
726    // The first /component/.. whose component is a directory: neither ".." nor a leading "." (`./../../x` is
727    // `../../x`, as Perl and TeX read it).
728    let collapsed = pathname.match_indices("/..").find_map(|(dotdot_pos, _)| {
729      let after = dotdot_pos + 3;
730      if dotdot_pos == 0 || (after < pathname.len() && pathname.as_bytes()[after] != b'/') {
731        return None;
732      }
733      let (prefix, trail) = (&pathname[..dotdot_pos], &pathname[after..]);
734      match prefix.rfind('/') {
735        Some(slash_pos) => {
736          let component = &prefix[slash_pos + 1..];
737          (component != ".." && !component.is_empty()).then(|| match &pathname[..slash_pos] {
738            // (`/a/..` is the root)
739            "" if trail.is_empty() => "/".to_string(),
740            head => format!("{head}{trail}"),
741          })
742        },
743        // No leading slash, e.g. "foo/.." (and `foo/..//x` is the relative `x`)
744        None => (prefix != ".." && prefix != ".").then(|| {
745          let rest = trail.trim_start_matches('/');
746          if rest.is_empty() {
747            ".".to_string()
748          } else {
749            rest.to_string()
750          }
751        }),
752      }
753    });
754    match collapsed {
755      Some(shorter) => pathname = shorter,
756      None => break,
757    }
758  }
759  // Perl: $pathname =~ s|^\./(.)|$1|; — reduce ./foo to foo, but preserve ./. A relative name stays relative:
760  // `.//x` (and `././/x`, `y/..//x`) is TeX's `./x`, where Perl reads `/x` (KNOWN_PERL_ERRORS #1343).
761  if let Some(rest) = pathname.strip_prefix("./")
762    && !rest.is_empty()
763  {
764    pathname = match rest.trim_start_matches('/') {
765      "" => "./".to_string(),
766      rest => rest.to_string(),
767    };
768  }
769  match url_prefix {
770    Some(prefix) => format!("{}{}", prefix, pathname),
771    None => pathname,
772  }
773}
774
775/// Note that this returns ONLY recognized protocols!
776pub fn protocol(pathname: &str) -> String {
777  if let Some(cap) = PROTOCOL_RE.captures(pathname) {
778    cap.get(1).map_or(String::new(), |m| m.as_str().to_string())
779  } else if is_literaldata(pathname) {
780    "literal".to_string()
781  } else {
782    "file".to_string()
783  }
784}
785
786/// combine a directory and a base name into a full path
787pub fn concat(dir: &str, file: &str) -> String {
788  if dir.is_empty() {
789    file.to_owned()
790  } else if file.is_empty() || file == "." {
791    dir.to_owned()
792  } else {
793    // Join with a literal '/', as Perl's pathname_concat does — the
794    // string-pathname layer is '/'-separated on every platform. (The
795    // previous PathBuf::push produced '\' on Windows, which the
796    // Perl-faithful string logic in `canonical` cannot normalize.)
797    canonical(&format!("{dir}/{file}"))
798  }
799}
800
801/// Expand a directory for the kpsewhich `//` recursive-search convention: the
802/// directory itself, followed by every subdirectory beneath it. Traversal is
803/// breadth-first and each level is sorted, so shallower directories take search
804/// precedence and the result is deterministic. Hidden (dot-prefixed)
805/// subdirectories are skipped, as kpsewhich does. Returns just `[base]` if the
806/// tree cannot be read.
807fn expand_recursive_dirs(base: &str) -> Vec<String> {
808  let mut out = vec![base.to_string()];
809  // Cycle guard: a symlinked directory can point back at an ancestor. Dedupe on
810  // the CANONICAL path so a symlink loop can't make the walk run forever.
811  let mut visited = std::collections::HashSet::new();
812  if let Ok(canon) = std::fs::canonicalize(base) {
813    visited.insert(canon);
814  }
815  let mut queue = std::collections::VecDeque::from([PathBuf::from(base)]);
816  while let Some(dir) = queue.pop_front() {
817    let Ok(entries) = std::fs::read_dir(&dir) else {
818      continue;
819    };
820    let mut children: Vec<PathBuf> = entries
821      .flatten()
822      .map(|e| e.path())
823      .filter(|p| p.is_dir())
824      .filter(|p| {
825        // Skip hidden dot-directories (.git, .svn, …), matching kpsewhich.
826        p.file_name()
827          .and_then(|n| n.to_str())
828          .is_none_or(|n| !n.starts_with('.'))
829      })
830      .collect();
831    children.sort();
832    for child in children {
833      // Skip any directory (reached directly or via symlink) already walked.
834      if let Ok(canon) = std::fs::canonicalize(&child)
835        && !visited.insert(canon)
836      {
837        continue;
838      }
839      if let Some(s) = child.to_str() {
840        // Keep the `/`-separator convention the pathname layer speaks.
841        out.push(s.replace('\\', "/"));
842        queue.push_back(child);
843      }
844    }
845  }
846  out
847}
848
849/// `.//x` (and `././/x`) as TeX opens it: `x`, relative to the working directory, as [`canonical`] reads it, where
850/// Perl's `pathname_canonical` reads the absolute `/x` (KNOWN_PERL_ERRORS #1343; 1801.09240's `\input{\djfolder /dj}`).
851pub fn dot_relative(pathname: &str) -> &str {
852  let Some(mut rest) = pathname.strip_prefix("./") else {
853    return pathname;
854  };
855  let mut doubled = false;
856  loop {
857    if let Some(shorter) = rest.strip_prefix('/') {
858      (rest, doubled) = (shorter, true);
859    } else if let Some(shorter) = rest.strip_prefix("./") {
860      rest = shorter;
861    } else {
862      break;
863    }
864  }
865  if doubled && !rest.is_empty() {
866    rest
867  } else {
868    pathname
869  }
870}
871
872/// It's presumably cheep to concatinate all the pathnames,
873/// relative to the cost of testing for files,
874/// and this simplifies overall.
875pub fn candidate_pathnames(pathname: &str, options: PathnameFindOptions) -> Vec<String> {
876  candidates(pathname, options, false)
877}
878
879/// The candidates `as_written`: the name as the system opens it under each search directory, not [`canonical`], so
880/// that `sub/../x` climbs only through a real `sub`.
881fn candidates(pathname: &str, options: PathnameFindOptions, as_written: bool) -> Vec<String> {
882  let mut dirs: Vec<String> = Vec::new();
883  let pathname = dot_relative(pathname);
884  let canonical_pathname = if pathname != "*" {
885    canonical(pathname)
886  } else {
887    pathname.to_owned()
888  };
889
890  let (pathdir, name_stem, pathname_ext) = split(&canonical_pathname);
891  // Perl: $name .= '.' . $type if (defined $type) && ($type ne '');
892  // Re-attach the extension to the name, as Perl does after split
893  let name = if !pathname_ext.is_empty() {
894    format!("{}.{}", name_stem, pathname_ext)
895  } else {
896    name_stem
897  };
898
899  let cwd = cwd();
900
901  // generate the set of search paths we'll use.
902  let written: &str = if pathname.starts_with('~') {
903    &canonical_pathname
904  } else {
905    pathname
906  };
907  if is_absolute(&canonical_pathname) {
908    dirs.push(if as_written {
909      String::new()
910    } else {
911      pathdir.clone()
912    });
913  } else if let Some(paths) = options.paths {
914    for p in paths {
915      // kpsewhich convention: a search path ending in `//` is searched
916      // RECURSIVELY (the directory and its whole subtree). Split the marker off
917      // first, then resolve the base to an absolute directory.
918      let (base, recursive) = match p.strip_suffix("//") {
919        Some(b) => (b.trim_end_matches('/'), true),
920        None => (p.as_str(), false),
921      };
922      // Complete the search paths by prepending current dir to relative paths,
923      let pp_base = if is_absolute(base) {
924        canonical(base)
925      } else {
926        concat(&cwd, base)
927      };
928      // Expand the recursive marker to `[base, ...every subdirectory]`; a plain
929      // path stays a single directory.
930      let roots = if recursive {
931        expand_recursive_dirs(&pp_base)
932      } else {
933        vec![pp_base]
934      };
935      for root in roots {
936        let pp = if as_written {
937          root
938        } else {
939          concat(&root, &pathdir)
940        };
941        // but only include each dir ONCE
942        if !dirs.contains(&pp) {
943          dirs.push(pp);
944        }
945      }
946    }
947  }
948  // Perl: push(@dirs, pathname_concat($cwd, $pathdir)) unless @dirs;
949  // Only add cwd if no search paths were given (fallback)
950  if dirs.is_empty() {
951    let from_cwd = if as_written {
952      cwd.clone()
953    } else {
954      concat(&cwd, &pathdir)
955    };
956    if !dirs.contains(&from_cwd) {
957      dirs.push(from_cwd);
958    }
959  }
960
961  // TODO: The use of INSTALLDIRS should be rethought entirely, as Rust currently doesn't have a
962  // native concept of "installing" a crate and its resources there either needs to be a
963  // more sophisticated build process, OR, a compile step that translates all model/binding
964  // dependencies into rust code. which would allow bundling them side-by-side with the
965  // main application.
966
967  // And, if installation dir specified, append it.
968  if let Some(subdir) = options.installation_subdir {
969    // dirs.extend((*INSTALLDIRS).iter().map(|dir| concat(dir, &subdir)));
970    let full_subdir = concat(&cwd, &subdir);
971    if Path::new(&full_subdir).exists() {
972      dirs.push(full_subdir);
973    } else {
974      let full_subdir_oneup = concat(&s!("{}/..", cwd), &subdir);
975      if Path::new(&full_subdir_oneup).exists() {
976        dirs.push(full_subdir_oneup);
977      }
978    }
979  }
980  // extract the desired extensions.
981  // Perl: the extensions from `types` option are applied to the already-reassembled name.
982  // Since name already has its extension, matching an existing extension pushes '' (exact match).
983  let mut exts = Vec::new();
984  if let Some(ext_vec) = options.extensions {
985    for ext in ext_vec {
986      if ext.is_empty() {
987        exts.push(String::new());
988      } else if ext == "*" {
989        exts.push(s!(".*"));
990        exts.push(String::new());
991      } else if !pathname_ext.is_empty() && pathname_ext.eq_ignore_ascii_case(&ext) {
992        // Perl Pathname.pm L353: `if ($pathname =~ /\.\Q$ext\E$/i)` — /i
993        // makes this a case-insensitive extension match; either case of
994        // file extension matches either case of requested type.
995        exts.push(String::new());
996        // Also push the extension itself (Perl pushes both)
997        exts.push(format!(".{}", ext));
998      } else {
999        exts.push(format!(".{}", ext));
1000      }
1001    }
1002  }
1003  if exts.is_empty() {
1004    exts.push(String::new());
1005  }
1006
1007  let mut paths = Vec::new();
1008  // Now, combine; precedence to leading directories.
1009  for dir in &dirs {
1010    for ext in &exts {
1011      if name == "*" {
1012        // TODO: wildcard directory listing support
1013      } else if as_written {
1014        paths.push(match dir.as_str() {
1015          "" => format!("{written}{ext}"),
1016          dir => format!("{dir}/{written}{ext}"),
1017        });
1018      } else {
1019        paths.push(concat(dir, &(name.clone() + ext)));
1020      }
1021    }
1022  }
1023  paths
1024}
1025
1026mod nocase_dir_cache {
1027  use std::{
1028    cell::RefCell,
1029    fs::{self, Metadata},
1030    path::{Path, PathBuf},
1031    time::SystemTime,
1032  };
1033
1034  use rustc_hash::FxHashMap;
1035
1036  use super::is_readable_file;
1037
1038  const MAX_CACHED_DIRS: usize = 256;
1039
1040  #[derive(Clone, PartialEq, Eq)]
1041  struct DirStamp {
1042    modified: Option<SystemTime>,
1043    #[cfg(unix)]
1044    dev:      u64,
1045    #[cfg(unix)]
1046    ino:      u64,
1047    #[cfg(unix)]
1048    ctime:    i64,
1049    #[cfg(unix)]
1050    ctime_ns: i64,
1051    #[cfg(unix)]
1052    nlink:    u64,
1053    #[cfg(not(unix))]
1054    len:      u64,
1055  }
1056
1057  impl DirStamp {
1058    fn from_meta(m: &Metadata) -> Self {
1059      #[cfg(unix)]
1060      {
1061        use std::os::unix::fs::MetadataExt;
1062        Self {
1063          modified: m.modified().ok(),
1064          dev:      m.dev(),
1065          ino:      m.ino(),
1066          ctime:    m.ctime(),
1067          ctime_ns: m.ctime_nsec(),
1068          nlink:    m.nlink(),
1069        }
1070      }
1071      #[cfg(not(unix))]
1072      {
1073        Self {
1074          modified: m.modified().ok(),
1075          len:      m.len(),
1076        }
1077      }
1078    }
1079  }
1080
1081  struct DirIndex {
1082    stamp:   DirStamp,
1083    entries: FxHashMap<String, String>,
1084  }
1085
1086  thread_local! {
1087    static CACHE: RefCell<FxHashMap<PathBuf, DirIndex>> = RefCell::new(FxHashMap::default());
1088  }
1089
1090  pub(super) fn clear() { CACHE.with(|cell| cell.borrow_mut().clear()); }
1091
1092  fn build_index(dir: &Path, stamp: DirStamp) -> Option<DirIndex> {
1093    let rd = fs::read_dir(dir).ok()?;
1094    let mut entries = FxHashMap::default();
1095    for entry in rd.flatten() {
1096      let file_name = entry.file_name();
1097      let Some(name) = file_name.to_str() else {
1098        continue;
1099      };
1100      // Skip subdirectories without extra `stat` syscalls when `d_type` knows;
1101      // follow symlinks via `is_dir()` only when the entry is a symlink or unknown.
1102      let is_dir = match entry.file_type() {
1103        Ok(ft) if ft.is_dir() => true,
1104        Ok(ft) if ft.is_file() => false,
1105        _ => entry.path().is_dir(),
1106      };
1107      if is_dir {
1108        continue;
1109      }
1110      entries
1111        .entry(name.to_ascii_lowercase())
1112        .or_insert_with(|| name.to_string());
1113    }
1114    Some(DirIndex { stamp, entries })
1115  }
1116
1117  /// Find a readable non-directory entry in `dir` matching `target`
1118  /// ASCII-case-insensitively, using a directory-stamp-validated listing cache
1119  /// so repeated missing lookups do not re-read large search directories.
1120  pub(super) fn lookup(dir: &Path, target: &str) -> Option<String> {
1121    let meta = fs::metadata(dir).ok()?;
1122    if !meta.is_dir() {
1123      return None;
1124    }
1125    let stamp = DirStamp::from_meta(&meta);
1126    let target_lower = target.to_ascii_lowercase();
1127
1128    // On non-Unix (no dev/ino), skip caching relative paths in case cwd changes.
1129    #[cfg(not(unix))]
1130    if !dir.is_absolute() {
1131      let idx = build_index(dir, stamp)?;
1132      let actual = idx.entries.get(&target_lower)?;
1133      let full = dir.join(actual).to_str()?.to_string();
1134      return is_readable_file(&full).then_some(full);
1135    }
1136
1137    let matched = CACHE.with(|cell| {
1138      let mut cache = cell.borrow_mut();
1139      let fresh = cache
1140        .get(dir)
1141        .is_some_and(|existing| existing.stamp == stamp);
1142      if !fresh {
1143        let idx = build_index(dir, stamp)?;
1144        if cache.len() >= MAX_CACHED_DIRS {
1145          cache.clear();
1146        }
1147        cache.insert(dir.to_path_buf(), idx);
1148      }
1149      cache
1150        .get(dir)
1151        .and_then(|idx| idx.entries.get(&target_lower).cloned())
1152    })?;
1153    let full = dir.join(matched).to_str()?.to_string();
1154    is_readable_file(&full).then_some(full)
1155  }
1156}
1157
1158/// Drop the thread-local case-insensitive directory listing cache.
1159/// Called at each conversion start ([`crate::reset_conversion_state`]) so a
1160/// long-lived worker never carries a cached listing across conversions even
1161/// within a coarse filesystem mtime tick.
1162pub fn clear_nocase_dir_cache() { nocase_dir_cache::clear(); }
1163
1164/// find the requested `pathname` using the `options` search configuration.
1165/// Mirrors Perl `pathname_find` (LaTeXML/Util/Pathname.pm L376-392): directory
1166/// search with strict-case match preferred, falling back to a
1167/// case-insensitive directory scan. The fallback is required for arxiv
1168/// papers shipping uppercase filenames (e.g. `PASJ95.STY` referenced as
1169/// `PASJ95.sty`) — Perl's regex pair pushes both strict and `/i` matches
1170/// and returns the strict ones if any exist, otherwise the case-insensitive
1171/// matches. kpsewhich is the caller's responsibility (see
1172/// `LaTeXML::Package::FindFile_aux`).
1173pub fn find(pathname: &str, options: PathnameFindOptions) -> Option<String> {
1174  if pathname.is_empty() {
1175    return None;
1176  }
1177  let no_paths = options.paths.as_ref().is_none_or(|paths| paths.is_empty());
1178  let opened_options = is_confined().then(|| options.clone());
1179  let mut paths = candidate_pathnames(pathname, options);
1180  // A confined conversion never looks for a file outside its roots: a name no candidate inside them finds is refused
1181  // when an outside one names a file as the system opens it ([`refused_exists`]), else it is missing. With no search
1182  // path to look in (a `literal:` input), a plain name is the installation's.
1183  let mut refused_outside = None;
1184  if let Some(opened_options) = opened_options {
1185    let (inside, outside): (Vec<String>, Vec<String>) =
1186      paths.into_iter().partition(|path| read_allowed(path));
1187    paths = inside;
1188    if !outside.is_empty()
1189      && !(no_paths && !is_absolute(pathname) && confinement::kpse_name_ok(pathname))
1190    {
1191      let all_outside = paths.is_empty();
1192      let names_a_file = move || {
1193        candidates(pathname, opened_options, true)
1194          .iter()
1195          .any(|path| (all_outside || !read_allowed(path)) && refused_exists(path))
1196      };
1197      if all_outside {
1198        if names_a_file() {
1199          refuse(pathname);
1200        }
1201        return None;
1202      }
1203      refused_outside = Some(names_a_file);
1204    } else if paths.is_empty() {
1205      return None;
1206    }
1207  }
1208  // Pass 1: strict-case existence check (the fast path; matches Perl's
1209  // `$local_file =~ m/$regex/` strict regex). A directory is no candidate: kpathsea's `READABLE` (`!S_ISDIR`) never
1210  // takes one, so `\input{intro}` beside a directory `intro/` looks further (2408.09583's
1211  // `chapters/introduction/introduction.tex`, where `chapters/introduction` was read as the file and its chapter
1212  // lost; Perl's `candidate_pathnames` takes any matching directory entry, KPE #1171).
1213  for path in &paths {
1214    if is_readable_file(path) {
1215      return Some(path.clone());
1216    }
1217  }
1218  // Pass 2: case-insensitive directory scan (Perl's `/i` regex fallback).
1219  // Only fired when no strict match existed; mirrors Perl's
1220  // `return @paths ? @paths : @nocase_paths` ordering. Confined, the file it finds is judged as the system opens it
1221  // (`lsec2.tex` for `LSEC2`, a link out of the folder), and a refused one is refused when nothing else is found.
1222  let mut refused_hit = false;
1223  for path in &paths {
1224    let p = Path::new(path);
1225    let dir = match p.parent() {
1226      Some(d) if !d.as_os_str().is_empty() => d,
1227      _ => Path::new("."),
1228    };
1229    let target = match p.file_name().and_then(|n| n.to_str()) {
1230      Some(n) => n,
1231      None => continue,
1232    };
1233    if let Some(found) = nocase_dir_cache::lookup(dir, target) {
1234      if read_allowed(&found) {
1235        return Some(found);
1236      }
1237      refused_hit = true;
1238    }
1239  }
1240  // (a `--path` directory's missing candidate, the source folder's a link out: the outside file is refused)
1241  if refused_hit || refused_outside.is_some_and(|names_a_file| names_a_file()) {
1242    refuse(pathname);
1243  }
1244  None
1245}
1246
1247/// A path TeX could open as a file: it exists and is not a directory (kpathsea's `READABLE`).
1248pub fn is_readable_file(path: &str) -> bool { std::fs::metadata(path).is_ok_and(|m| !m.is_dir()) }
1249
1250/// transform to a canonical file name, via `Path::file_name`
1251pub fn file_name(pathname: &str) -> String {
1252  let canonical_pathname = canonical(pathname);
1253  let canonical_path = Path::new(&canonical_pathname);
1254  match canonical_path.file_name() {
1255    Some(e) => e.to_string_lossy().to_string(),
1256    None => String::new(),
1257  }
1258}
1259
1260/// transform to a base name (via `Path::file_stem`)
1261/// Note: Perl's pathname_name returns the stem without extension and without case change.
1262pub fn file_stem(pathname: &str) -> String {
1263  let canonical_pathname = canonical(pathname);
1264  let canonical_path = Path::new(&canonical_pathname);
1265  match canonical_path.file_stem() {
1266    Some(e) => e.to_string_lossy().to_string(),
1267    None => String::new(),
1268  }
1269}
1270
1271/// obtain the directory portion of a pathname (via `Path::parent`)
1272/// Matches Perl's pathname_directory.
1273pub fn directory(pathname: &str) -> String {
1274  let canonical_pathname = canonical(pathname);
1275  let canonical_path = Path::new(&canonical_pathname);
1276  match canonical_path.parent() {
1277    Some(e) => e.to_string_lossy().to_string(),
1278    None => String::new(),
1279  }
1280}
1281
1282/// obtain the extension portion of a pathname (via `Path::extension`).
1283/// Perl's `pathname_type` preserves case; callers that need a lowercased
1284/// form should apply `.to_ascii_lowercase()` themselves.
1285pub fn extension(pathname: &str) -> String {
1286  let canonical_pathname = canonical(pathname);
1287  let canonical_path = Path::new(&canonical_pathname);
1288  match canonical_path.extension() {
1289    Some(e) => e.to_string_lossy().to_string(),
1290    None => String::new(),
1291  }
1292}
1293
1294/// Compose a pathname from dir, name, type components.
1295/// Port of Perl's pathname_make(%pieces).
1296pub fn make(dir: Option<&str>, name: Option<&str>, ext: Option<&str>) -> String {
1297  let mut result = String::new();
1298  if let Some(d) = dir {
1299    result.push_str(d);
1300  }
1301  if let Some(n) = name {
1302    if !result.is_empty() && !result.ends_with('/') {
1303      result.push('/');
1304    }
1305    result.push_str(n);
1306  }
1307  if let Some(t) = ext
1308    && !t.is_empty()
1309  {
1310    result.push('.');
1311    result.push_str(t);
1312  }
1313  canonical(&result)
1314}
1315
1316/// Lexical relative path from `base` to `target`, with `..` for the divergent
1317/// tail of `base` — the semantics of Perl's `File::Spec->abs2rel`, which
1318/// `pathname_relative` is built on. Component-based, no symlink resolution.
1319/// Both sides must be absolute (the only case `relative` calls it with); if
1320/// they share no root, falls back to the target string.
1321fn abs2rel(target: &Path, base: &Path) -> String {
1322  use std::path::Component;
1323  if !target.is_absolute() || !base.is_absolute() {
1324    return target.to_string_lossy().to_string();
1325  }
1326  let t: Vec<Component> = target.components().collect();
1327  let b: Vec<Component> = base.components().collect();
1328  let common = t.iter().zip(b.iter()).take_while(|(a, c)| a == c).count();
1329  if common == 0 {
1330    return target.to_string_lossy().to_string();
1331  }
1332  let mut result = PathBuf::new();
1333  for _ in 0..(b.len() - common) {
1334    result.push("..");
1335  }
1336  for comp in &t[common..] {
1337    result.push(comp.as_os_str());
1338  }
1339  // `PathBuf` re-joins with the OS separator, so on Windows the result is
1340  // `\`-separated — but this feeds forward-slash-only outputs (graphic
1341  // `candidates`, resource URLs) that must match Perl/pdflatex on every
1342  // platform. Normalize on Windows only; on Unix `\` is a legal filename byte
1343  // (and the parts are already `/`-joined), so the rewrite is compiled out
1344  // rather than risk corrupting a backslash-bearing name.
1345  #[cfg(windows)]
1346  {
1347    result.to_string_lossy().replace('\\', "/")
1348  }
1349  #[cfg(not(windows))]
1350  {
1351    result.to_string_lossy().into_owned()
1352  }
1353}
1354
1355/// Make a pathname relative to a base directory.
1356/// Port of Perl's pathname_relative($pathname, $base).
1357pub fn relative(pathname: &str, base: &str) -> String {
1358  let canonical_pathname = canonical(pathname);
1359  if base.is_empty() || !is_absolute(&canonical_pathname) {
1360    return canonical_pathname;
1361  }
1362  let canonical_base = canonical(base);
1363  // Perl's pathname_relative uses File::Spec->abs2rel, which emits a `../…`
1364  // path when `pathname` is NOT a descendant of `base` (a sibling tree, e.g.
1365  // a graphic reached through `\subimport*{../A/child/}` — issue #698).
1366  // `strip_prefix` can only strip a descendant prefix, so it used to fall back
1367  // to the raw ABSOLUTE path there, which then leaked into resource/graphic
1368  // URLs. abs2rel matches Perl and never leaks an absolute path.
1369  abs2rel(Path::new(&canonical_pathname), Path::new(&canonical_base))
1370}
1371
1372/// `pathname` relative to `base` when it lies underneath it (both made absolute against the cwd first), else `None`.
1373/// Port of Perl's `pathname_is_contained` (`Util/Pathname.pm` L179-186); a result that stays absolute (no common
1374/// root: another Windows drive) is not contained either.
1375pub fn is_contained(pathname: &str, base: &str) -> Option<String> {
1376  let rel = canonical(&relative(&absolute(pathname), &absolute(base)));
1377  let outside = rel == ".." || rel.starts_with("../") || Path::new(&rel).is_absolute();
1378  (!outside).then_some(rel)
1379}
1380
1381/// `pathname` made absolute with every directory that exists named as the file system names it: symbolic links
1382/// followed and, on Windows, 8.3 short names expanded (`RUNNER~1` → `runneradmin`) and letters cased as stored. The
1383/// longest existing prefix is resolved and the components that do not exist yet are kept as written, so a directory
1384/// about to be made resolves like one that is already there. Two paths in this form agree however each was obtained
1385/// — `current_dir`, [`canonicalize`], a command-line argument — which a lexical comparison does not: the rc3 Windows
1386/// release guards compared a destination not yet made, kept lexical (`C:/Users/RUNNER~1/…`), with the canonical
1387/// form of its existing parent (`C:/Users/runneradmin/…`), so an image inside the document's folder looked outside it.
1388pub fn resolved(pathname: &str) -> String {
1389  let abs = PathBuf::from(absolute(pathname));
1390  let mut tail: Vec<std::ffi::OsString> = Vec::new();
1391  let mut dir: &Path = &abs;
1392  loop {
1393    if let Ok(real) = canonicalize(dir) {
1394      let joined = tail.iter().rev().fold(real, |path, part| path.join(part));
1395      return canonical(&joined.to_string_lossy());
1396    }
1397    match (dir.parent(), dir.file_name()) {
1398      (Some(parent), Some(name)) => {
1399        tail.push(name.to_os_string());
1400        dir = parent;
1401      },
1402      _ => return canonical(&abs.to_string_lossy()),
1403    }
1404  }
1405}
1406
1407/// `pathname`'s directory [`resolved`], its last component kept as written: a file that is itself a symbolic link
1408/// keeps its own name, as a copy over it replaces the link and never writes through it.
1409pub fn resolved_directory_of(pathname: &str) -> String {
1410  let abs = PathBuf::from(absolute(pathname));
1411  match (abs.parent(), abs.file_name()) {
1412    (Some(parent), Some(name)) => {
1413      let dir = resolved(&parent.to_string_lossy());
1414      canonical(&Path::new(&dir).join(name).to_string_lossy())
1415    },
1416    _ => resolved(pathname),
1417  }
1418}
1419
1420/// [`is_contained`] whatever the spelling of either path: `pathname`'s directory and all of `base` [`resolved`] (both
1421/// made absolute against the working directory first). A symbolic link inside `base` that leads out of it is outside.
1422pub fn is_contained_resolved(pathname: &str, base: &str) -> Option<String> {
1423  is_contained(&resolved_directory_of(pathname), &resolved(base))
1424}
1425
1426/// Whether `a` and `b` name the same existing file (both [`canonicalize`]d, so links and spellings agree); false when
1427/// either does not exist.
1428pub fn same_file(a: impl AsRef<Path>, b: impl AsRef<Path>) -> bool {
1429  match (canonicalize(a), canonicalize(b)) {
1430    (Ok(ca), Ok(cb)) => ca == cb,
1431    _ => false,
1432  }
1433}
1434
1435/// Whether the existing `path`, as the system opens it (every link followed, a link before a `..` first), lies in the
1436/// existing directory `dir`; `None` when either is missing. Both are canonicalized by std, so on Windows both keep
1437/// the verbatim prefix [`canonicalize`] drops only under 260 characters, and a long path compares like a short one.
1438pub fn opens_inside(path: impl AsRef<Path>, dir: impl AsRef<Path>) -> Option<bool> {
1439  match (std::fs::canonicalize(path), std::fs::canonicalize(dir)) {
1440    (Ok(p), Ok(d)) => Some(p.starts_with(&d)),
1441    _ => None,
1442  }
1443}
1444
1445/// Find all matching files (like pathname_findall).
1446/// Port of Perl's pathname_findall($pathname, %options).
1447pub fn findall(pathname: &str, options: PathnameFindOptions) -> Vec<String> {
1448  candidate_pathnames(pathname, options)
1449}
1450
1451// Memo store for `kpsewhich` (see its doc below).
1452#[cfg(feature = "kpathsea")]
1453std::thread_local! {
1454  static KPSE_MEMO: std::cell::RefCell<rustc_hash::FxHashMap<String, Option<String>>> =
1455    std::cell::RefCell::new(rustc_hash::FxHashMap::default());
1456}
1457
1458/// Clear the per-thread kpsewhich memo. Called at the start of every
1459/// conversion (`reset_conversion_state`, at `initialize_report`): the persistent (non-harness) cortex_worker
1460/// runs many papers per thread, and a cached cwd-relative MISS from paper A
1461/// (kpathsea's path spec includes `.`) would wrongly persist into paper B
1462/// (PR_READINESS should-fix 12).
1463#[cfg(feature = "kpathsea")]
1464pub fn clear_kpsewhich_memo() { KPSE_MEMO.with(|m| m.borrow_mut().clear()); }
1465
1466#[cfg(not(feature = "kpathsea"))]
1467pub fn clear_kpsewhich_memo() {}
1468
1469/// search for a list of candidate names via the external `kpsewhich` utility
1470/// returning the first path that is found
1471///
1472/// Memoized (hits AND misses) per thread, keyed by the candidate list
1473/// (Principle 5, closed by the 2026-07-02 perf audit): repeated lookups of
1474/// the same missing asset (e.g. a figure referenced by many
1475/// `\includegraphics`) otherwise re-probe kpathsea each time — a full
1476/// fork-exec per probe on the subprocess-`kpsewhich` backend (portable
1477/// builds without linked libkpathsea), a cheaper but nonzero library walk
1478/// on the in-process backend. Results are stable for a fixed texmf tree
1479/// (the same assumption kpathsea's own ls-R cache makes); the memo clears
1480/// per conversion via `clear_kpsewhich_memo`.
1481///
1482/// With neither backend (no TeX installation) every lookup answers `None`, silently, as Perl's
1483/// `pathname_kpsewhich` does without a `kpsewhich` (Pathname.pm:395-403); a TeX installation is optional
1484/// here. Each conversion's log names the backend (`Info:kpathsea:backend`, `Converter::initialize_session`),
1485/// so a resolver that never came up is not mistaken for a missing file (issue #304).
1486#[cfg(feature = "kpathsea")]
1487pub fn kpsewhich(candidates: &[&str]) -> Option<String> { kpsewhich_in(candidates, false) }
1488
1489/// [`kpsewhich`] for names TeX opens with `\openin` (`\IfFileExists`, graphics.sty's `\Gin@getbase`): only TeX's
1490/// input path is searched (web2c's `\openin` asks kpathsea's `kpse_tex_format`), not first the format a name's suffix
1491/// suggests, which for a suffix kpathsea does not know (`.pdf`, `.png`) is that same search done twice.
1492#[cfg(feature = "kpathsea")]
1493pub fn kpsewhich_tex_input(candidates: &[&str]) -> Option<String> { kpsewhich_in(candidates, true) }
1494
1495#[cfg(feature = "kpathsea")]
1496fn kpsewhich_in(candidates: &[&str], tex_only: bool) -> Option<String> {
1497  // Confined: kpathsea is never asked for a `..` or out-of-root name, and a hit outside the roots (kpathsea's `.`, the
1498  // working directory, or an environment TEXINPUTS directory) is no hit. The memo keeps kpathsea's own answers.
1499  if is_confined() {
1500    return candidates
1501      .iter()
1502      .filter(|name| confinement::kpse_name_ok(name))
1503      .find_map(|name| {
1504        kpsewhich_memo(&[name], tex_only).filter(|found| confinement::kpse_hit_allowed(name, found))
1505      });
1506  }
1507  kpsewhich_memo(candidates, tex_only)
1508}
1509
1510#[cfg(feature = "kpathsea")]
1511fn kpsewhich_memo(candidates: &[&str], tex_only: bool) -> Option<String> {
1512  let key = format!(
1513    "{}{}",
1514    if tex_only { "\x1etex\x1f" } else { "" },
1515    candidates.join("\x1f")
1516  );
1517  if let Some(cached) = KPSE_MEMO.with(|m| m.borrow().get(&key).cloned()) {
1518    return cached;
1519  }
1520  let result = kpsewhich_uncached(candidates, tex_only);
1521  KPSE_MEMO.with(|m| {
1522    let mut m = m.borrow_mut();
1523    // Long-lived processes (--server, test harness): bound the memo rather
1524    // than grow without limit; 4096 distinct lookups per epoch is plenty.
1525    if m.len() >= 4096 {
1526      m.clear();
1527    }
1528    m.insert(key, result.clone());
1529  });
1530  result
1531}
1532
1533/// Probe each candidate through one backend, in order, returning the first
1534/// hit. Skips bogus bare-extension names and guards the in-process
1535/// `guess_format_from_filename` panic.
1536#[cfg(feature = "kpathsea")]
1537fn find_first_via(kpse: &Kpaths, candidates: &[&str], tex_only: bool) -> Option<String> {
1538  for candidate in candidates {
1539    // kpathsea-0.2.3 panics with "attempt to subtract with overflow" in
1540    // `guess_format_from_filename` (lib.rs:92) when `filename.len()` is
1541    // shorter than some alt_suffix the format-table holds (the L73 normal-
1542    // suffix loop has a `filename.len() > suffix.len()` guard but the L92
1543    // alt_suffix loop does NOT). User input like `\usepackage[opt]{}`
1544    // produces a `.sty` candidate (empty stem) which trips this. Pre-filter
1545    // those: a basename starting with `.` and containing only an extension
1546    // is bogus to look up. The catch_unwind below remains as defense-in-
1547    // depth. Witnesses: 0711.2664 (`.sty`), cs0503041 (`.sty`).
1548    let basename = candidate.rsplit(['/', '\\']).next().unwrap_or(candidate);
1549    if basename.starts_with('.') && !basename[1..].contains('.') {
1550      continue;
1551    }
1552    if !tex_only {
1553      let result =
1554        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kpse.find_file(candidate)));
1555      if let Ok(Some(path)) = result {
1556        return Some(path);
1557      }
1558    }
1559    // Extension-guessed lookup missed (or `tex_only`). The ENGINE's `\input`/`\openin`
1560    // always search the TEX format (TEXINPUTS includes `texmf-dist/tex//`),
1561    // regardless of extension — the guess-from-filename is a kpsewhich-CLI
1562    // convenience, not engine behavior. Retry with the explicit TEX format
1563    // so e.g. pgfornament's `\@@input vectorian46.pgf` resolves
1564    // (tex/generic/pgfornament/vectorian/; plain `kpsewhich` misses it,
1565    // `kpsewhich -format=tex` finds it). Perl reaches the same files via
1566    // its ls-R basename cache (Pathname.pm build_kpse_cache). Witness:
1567    // pgfornament/ornaments (291 missing_file errors) + pgfornament-han.
1568    let retry = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1569      kpse.find_file_with_format(candidate, kpathsea::formats::TEX)
1570    }));
1571    if let Ok(Some(path)) = retry {
1572      return Some(path);
1573    }
1574  }
1575  None
1576}
1577
1578#[cfg(feature = "kpathsea")]
1579fn kpsewhich_uncached(candidates: &[&str], tex_only: bool) -> Option<String> {
1580  KPSE
1581    .lock()
1582    .unwrap()
1583    .as_ref()
1584    .and_then(|kpse| find_first_via(kpse, candidates, tex_only))
1585}
1586
1587/// Without the `kpathsea` feature, file resolution is unavailable — every lookup
1588/// returns `None` (graceful degradation). The host-side proc-macro codegen build
1589/// takes this path; it never resolves TeX files at compile time.
1590#[cfg(not(feature = "kpathsea"))]
1591pub fn kpsewhich(_candidates: &[&str]) -> Option<String> { None }
1592
1593/// Without the `kpathsea` feature, as [`kpsewhich`]: `None`.
1594#[cfg(not(feature = "kpathsea"))]
1595pub fn kpsewhich_tex_input(_candidates: &[&str]) -> Option<String> { None }
1596
1597/// check if pathname contains dangerous pieces
1598pub fn is_nasty(file: &str) -> bool { PATHNAME_IS_NASTY_RE.is_match(file) }
1599
1600/// returns the current working directory
1601pub fn cwd() -> String { env::current_dir().unwrap().to_string_lossy().to_string() }
1602
1603#[cfg(test)]
1604mod tests {
1605  use super::*;
1606
1607  /// Every search-path variable of the installed kpathsea's format table is an override the confinement checks
1608  /// (`TEXMFCNF`, the configuration file's own path, aside); without `kpsewhich` the test says so and passes.
1609  #[test]
1610  fn every_kpathsea_format_variable_is_a_search_path() {
1611    let Ok(out) = tex_tool_command("kpsewhich").arg("--help-formats").output() else {
1612      eprintln!("SKIP every_kpathsea_format_variable_is_a_search_path: no kpsewhich");
1613      return;
1614    };
1615    let text = String::from_utf8_lossy(&out.stdout);
1616    let vars: Vec<&str> = text
1617      .lines()
1618      .filter_map(|line| line.split_once("[variables:").map(|(_, rest)| rest))
1619      .flat_map(|rest| rest.trim_end_matches(']').split_whitespace())
1620      .filter(|var| *var != "TEXMFCNF")
1621      .collect();
1622    assert!(
1623      vars.len() > 40,
1624      "kpsewhich --help-formats listed {} variables",
1625      vars.len()
1626    );
1627    let missed: Vec<&&str> = vars.iter().filter(|var| !is_kpse_path_var(var)).collect();
1628    assert!(
1629      missed.is_empty(),
1630      "search-path variables the confinement does not check: {missed:?}"
1631    );
1632    for var in [
1633      "TEXMFDOTDIR",
1634      "VARTEXFONTS",
1635      "TEXINPUTS_latex",
1636      "TEXBIB.bibtex",
1637    ] {
1638      assert!(is_kpse_path_var(var), "{var}");
1639    }
1640    for var in [
1641      "TEXMFCNF",
1642      "TEXMFHOME",
1643      "TEXMFROOT",
1644      "TEXMFDIST",
1645      "XDG_CONFIG_HOME",
1646      "PATH",
1647    ] {
1648      assert!(!is_kpse_path_var(var), "{var}");
1649    }
1650  }
1651
1652  /// The confinement is the guard's while it lives, restored when it drops (a persistent worker converts its next
1653  /// paper on the same thread under other roots): a file under the first roots is refused under the second, then
1654  /// readable again unconfined; a refusal is decided without a stat (the names do not exist).
1655  #[test]
1656  fn confinement_follows_its_guard() {
1657    let tmp = env::temp_dir().to_string_lossy().into_owned();
1658    let (a, b) = (
1659      format!("{tmp}/confine_a_{}", std::process::id()),
1660      format!("{tmp}/confine_b_{}", std::process::id()),
1661    );
1662    let in_a = format!("{a}/x.tex");
1663    let in_b = format!("{b}/missing/y.tex");
1664    assert!(!is_confined() && read_allowed(&in_a));
1665    {
1666      let _first = confine(InputConfinement {
1667        source: Some(a.clone()),
1668        ..InputConfinement::default()
1669      });
1670      assert!(is_confined() && read_allowed(&in_a) && !read_allowed(&in_b));
1671      assert!(!read_allowed(&format!("{a}/../escape.tex")));
1672    }
1673    assert!(!is_confined());
1674    let _second = confine(InputConfinement {
1675      source: Some(b.clone()),
1676      ..InputConfinement::default()
1677    });
1678    assert!(!read_allowed(&in_a) && read_allowed(&in_b));
1679    assert!(own_behalf(|| read_allowed(&in_a)));
1680  }
1681
1682  /// A confined name is judged by where it lies, whatever characters it spells (2204.02075's
1683  /// `pics/CAE_>2shapes_test/`): only an empty name and one with a NUL, CR or LF, which cut a path or a log line, are
1684  /// refused by spelling; and kpathsea is not asked for a `-`-, `~`- or `$`-led name.
1685  #[test]
1686  fn confinement_judges_a_name_by_where_it_lies() {
1687    let a = format!(
1688      "{}/confine_c_{}",
1689      env::temp_dir().to_string_lossy(),
1690      std::process::id()
1691    );
1692    let _confined = confine(InputConfinement {
1693      source: Some(a.clone()),
1694      ..InputConfinement::default()
1695    });
1696    for name in [
1697      "a>b/x.png",
1698      "q;\"$ x/y.png",
1699      "b`c|d<e/x.png",
1700      "|x.pdf",
1701      "-o.pdf",
1702    ] {
1703      assert!(read_allowed(&format!("{a}/{name}")), "{name}");
1704      assert!(!read_allowed(&format!("{a}/../{name}")), "../{name}");
1705    }
1706    for name in ["a\nb.png", "a\rb.png", "a\0b.png"] {
1707      assert!(!read_allowed(&format!("{a}/{name}")), "{name:?}");
1708    }
1709    assert!(!read_allowed(""));
1710    // kpathsea is never asked for a name a subprocess `kpsewhich` would read as an option, or one it would expand.
1711    for name in [
1712      "-var-value=HOME",
1713      "-expand-braces={/etc,x}",
1714      "$HOME/x.sty",
1715      "~/x.sty",
1716    ] {
1717      assert!(!confinement::kpse_name_ok(name), "{name}");
1718    }
1719    assert!(confinement::kpse_name_ok("x.sty"));
1720  }
1721
1722  /// Issue #950: the local copy of the kpathsea crate's rule, for a build without it.
1723  #[cfg(not(feature = "kpathsea"))]
1724  #[test]
1725  fn trim_texmf_root_without_the_kpathsea_feature() {
1726    assert_eq!(trim_texmf_root("/tl/2024//").as_deref(), Some("/tl/2024"));
1727    assert_eq!(
1728      trim_texmf_root("!!/tl/2024/").as_deref(),
1729      Some("!!/tl/2024")
1730    );
1731    assert_eq!(trim_texmf_root("/tl//2024"), None);
1732    assert_eq!(trim_texmf_root("/"), None);
1733    assert_eq!(trim_texmf_root("{/a/,/b/}"), None);
1734  }
1735
1736  /// The dual-TL agreement probe compares paths as the file system does: on Windows kpsewhich's SELFAUTOPARENT
1737  /// (`C:/texlive/2026`) and the linked library's `c:/texlive/2026/…` name one tree.
1738  #[cfg(feature = "kpathsea")]
1739  #[test]
1740  fn path_is_under_compares_as_the_file_system_does() {
1741    let file = "c:/texlive/2026/texmf-dist/tex/latex/base/latex.ltx";
1742    assert!(path_is_under(file, "c:/texlive/2026"));
1743    assert!(path_is_under(file, "c:/texlive/2026/"));
1744    assert!(
1745      !path_is_under(file, "c:/texlive/202"),
1746      "a name prefix is not a directory"
1747    );
1748    assert!(!path_is_under(file, "c:/texlive/2025"));
1749    assert_eq!(path_is_under(file, "C:/texlive/2026"), cfg!(windows));
1750    assert_eq!(path_is_under(file, r"C:\texlive\2026"), cfg!(windows));
1751  }
1752
1753  /// `relative` is Perl's `pathname_relative` (→ `File::Spec->abs2rel`): a
1754  /// path that is NOT a descendant of `base` must come back as a `../…` path,
1755  /// never the raw absolute path. The strip_prefix port used to leak the
1756  /// absolute path here, which surfaced as a `/mnt/g/…` graphic URL (issue
1757  /// #698) and would do the same for any resource relativized against the
1758  /// source directory (e.g. `xslt.rs`).
1759  /// `pathname_is_contained`: underneath, the base itself, a `..` escape, the base's parent (which Perl's regex lets
1760  /// through, KNOWN_PERL_ERRORS #1329).
1761  #[test]
1762  fn is_contained_is_underneath_only() {
1763    let abs = |p: &str| {
1764      if cfg!(windows) {
1765        format!("C:{p}")
1766      } else {
1767        p.to_string()
1768      }
1769    };
1770    assert_eq!(
1771      is_contained(&abs("/s/out/x/../img.svg"), &abs("/s")).as_deref(),
1772      Some("out/img.svg")
1773    );
1774    assert!(is_contained(&abs("/s"), &abs("/s")).is_some());
1775    assert_eq!(is_contained(&abs("/s/../c/A.svg"), &abs("/s")), None);
1776    assert_eq!(is_contained(&abs("/p"), &abs("/p/sub")), None);
1777  }
1778
1779  /// Two spellings of one directory contain alike: paths reached through a symbolic link (the Unix stand-in for a
1780  /// Windows 8.3 name) against canonical ones, including a destination not made yet — the case behind the rc3
1781  /// Windows release guards. A file that is a link keeps its name; a directory link that leads out is outside.
1782  #[cfg(unix)]
1783  #[test]
1784  fn resolved_relates_two_spellings_of_one_directory() {
1785    let root = env::temp_dir().join(format!("lx-resolved-{}", std::process::id()));
1786    let _ = std::fs::remove_dir_all(&root);
1787    std::fs::create_dir_all(&root).unwrap();
1788    let real = canonicalize(&root).unwrap().join("real");
1789    std::fs::create_dir_all(real.join("src/figs")).unwrap();
1790    std::fs::write(real.join("src/figs/a.png"), b"x").unwrap();
1791    let link = real.parent().unwrap().join("link");
1792    std::os::unix::fs::symlink(&real, &link).unwrap();
1793    let (real_src, link_src) = (real.join("src"), link.join("src"));
1794    let (real_img, link_img) = (real.join("src/figs/a.png"), link.join("src/figs/a.png"));
1795    let s = |p: &Path| p.to_string_lossy().into_owned();
1796    // The lexical relation leaves the folder; the resolved one stays in it.
1797    assert_eq!(is_contained(&s(&real_img), &s(&link_src)), None);
1798    assert_eq!(
1799      is_contained_resolved(&s(&real_img), &s(&link_src)).as_deref(),
1800      Some("figs/a.png")
1801    );
1802    assert_eq!(
1803      is_contained_resolved(&s(&link_img), &s(&real_src)).as_deref(),
1804      Some("figs/a.png")
1805    );
1806    // A destination not made yet, spelled through the link, against its own spelling: its existing parent resolves
1807    // and so does the base's, so the copy is inside (lexical base against canonical parent was the rc3 failure).
1808    let out = link_src.join("out");
1809    assert_eq!(
1810      is_contained_resolved(&s(&out.join("figs/b.png")), &s(&out)).as_deref(),
1811      Some("figs/b.png")
1812    );
1813    assert_eq!(resolved(&s(&out)), canonical(&s(&real_src.join("out"))));
1814    // A file that is itself a link keeps its name; a directory link that leads out of the base is outside.
1815    let img_link = real.join("src/img.png");
1816    std::os::unix::fs::symlink(real.join("src/figs/a.png"), &img_link).unwrap();
1817    assert_eq!(
1818      is_contained_resolved(&s(&img_link), &s(&link_src)).as_deref(),
1819      Some("img.png")
1820    );
1821    let away = real.join("away");
1822    std::fs::create_dir_all(&away).unwrap();
1823    std::os::unix::fs::symlink(&away, real.join("src/gone")).unwrap();
1824    assert_eq!(
1825      is_contained_resolved(&s(&link_src.join("gone/c.png")), &s(&link_src)),
1826      None
1827    );
1828    // No link: the resolved form is the lexical one.
1829    assert_eq!(resolved(&s(&real_img)), canonical(&s(&real_img)));
1830    assert!(same_file(&link_img, &real_img));
1831    assert!(!same_file(&link_img, real.join("src/figs/missing.png")));
1832    let _ = std::fs::remove_dir_all(&root);
1833  }
1834
1835  #[test]
1836  fn relative_emits_dotdot_for_non_descendant() {
1837    // A bare `/x` is not absolute on Windows (no drive), so prefix one there to
1838    // exercise the abs2rel branch on every platform. Results stay forward-slash.
1839    let abs = |p: &str| {
1840      if cfg!(windows) {
1841        format!("C:{p}")
1842      } else {
1843        p.to_string()
1844      }
1845    };
1846    // Sibling tree: base and target diverge one level up.
1847    assert_eq!(
1848      relative(
1849        &abs("/home/u/proj/A/child/images/pic.svg"),
1850        &abs("/home/u/proj/latexml")
1851      ),
1852      "../A/child/images/pic.svg"
1853    );
1854    // Descendant is unchanged (the case strip_prefix already handled).
1855    assert_eq!(
1856      relative(&abs("/home/u/proj/sub/pic.png"), &abs("/home/u/proj")),
1857      "sub/pic.png"
1858    );
1859    // Cousin that diverges two levels up.
1860    assert_eq!(
1861      relative(&abs("/a/b/c/f.tex"), &abs("/a/x/y")),
1862      "../../b/c/f.tex"
1863    );
1864    // A non-absolute pathname is returned canonicalized, as Perl does.
1865    assert_eq!(relative("sub/pic.png", &abs("/home/u/proj")), "sub/pic.png");
1866    // Empty base short-circuits to the canonical pathname.
1867    assert_eq!(relative(&abs("/a/b/pic.png"), ""), abs("/a/b/pic.png"));
1868  }
1869
1870  /// `choose_kpaths` branches that a real host cannot exercise: a MiKTeX
1871  /// banner, a failed in-process construction, and a TeX-less machine.
1872  #[cfg(feature = "kpathsea")]
1873  mod backend_selection {
1874    use super::*;
1875
1876    /// A real subprocess handle, or `None` where the host has no `kpsewhich`.
1877    fn subprocess() -> Option<Kpaths> { Kpaths::new_subprocess().ok() }
1878
1879    #[test]
1880    fn no_constructible_backend_reports_unavailable() {
1881      let (kpse, backend, why) = choose_kpaths(
1882        None,
1883        || Err("no lib"),
1884        || Err("no kpsewhich"),
1885        |_| true,
1886        |_| true,
1887      );
1888      assert!(kpse.is_none());
1889      assert_eq!(backend, KpathseaBackend::Unavailable);
1890      assert!(
1891        !why.is_empty(),
1892        "an unavailable backend must explain itself"
1893      );
1894    }
1895
1896    /// The regression this hardening exists for: a failed in-process
1897    /// construction used to `?` out and silently disable ALL file resolution
1898    /// instead of trying the subprocess backend.
1899    #[test]
1900    fn failed_in_process_construction_falls_back_to_subprocess() {
1901      if subprocess().is_none() {
1902        return; // no host kpsewhich — nothing to fall back to
1903      }
1904      let (kpse, backend, _) = choose_kpaths(
1905        None,
1906        || Err("libkpathsea did not initialize"),
1907        Kpaths::new_subprocess,
1908        |_| true,
1909        |_| true,
1910      );
1911      assert!(kpse.is_some(), "must not give up while a kpsewhich exists");
1912      assert_eq!(backend, KpathseaBackend::Subprocess);
1913    }
1914
1915    #[test]
1916    fn miktex_banner_selects_subprocess_without_constructing_in_process() {
1917      if subprocess().is_none() {
1918        return;
1919      }
1920      let (kpse, backend, _) = choose_kpaths(
1921        Some("MiKTeX 24.1"),
1922        || panic!("the in-process backend must not be constructed on a MiKTeX host"),
1923        Kpaths::new_subprocess,
1924        |_| true,
1925        |_| true,
1926      );
1927      assert!(kpse.is_some());
1928      assert_eq!(backend, KpathseaBackend::Subprocess);
1929    }
1930
1931    /// A linked backend that resolves nothing (sentinel miss) is abandoned for
1932    /// the subprocess one.
1933    #[test]
1934    fn sentinel_miss_falls_back_to_subprocess() {
1935      let Some(primary) = subprocess() else { return };
1936      if primary.is_in_process() {
1937        return; // this branch only fires for an in-process primary
1938      }
1939      let (kpse, backend, _) = choose_kpaths(
1940        None,
1941        Kpaths::new,
1942        Kpaths::new_subprocess,
1943        |_| false,
1944        |_| true,
1945      );
1946      assert!(kpse.is_some());
1947      assert_eq!(backend, KpathseaBackend::Subprocess);
1948    }
1949
1950    /// Dual-TL guard: an in-process backend that anchors a DIFFERENT TeX tree
1951    /// than the ambient kpsewhich is abandoned for the subprocess one, so
1952    /// file resolution always agrees with dump-year detection (both follow
1953    /// PATH). See the 2026-08-31 "2025-dump with TL2023 expl3" incident.
1954    #[test]
1955    fn ambient_tree_mismatch_falls_back_to_subprocess() {
1956      let Some(primary) = subprocess() else { return };
1957      if primary.is_in_process() {
1958        return; // this branch only fires for an in-process primary
1959      }
1960      let (kpse, backend, why) = choose_kpaths(
1961        None,
1962        Kpaths::new,
1963        Kpaths::new_subprocess,
1964        |_| true,
1965        |_| false,
1966      );
1967      assert!(kpse.is_some());
1968      assert_eq!(backend, KpathseaBackend::Subprocess);
1969      assert!(why.contains("different TeX tree"), "why = {why}");
1970    }
1971  }
1972
1973  /// No backend may conjure a hit for a name that cannot exist.
1974  #[cfg(feature = "kpathsea")]
1975  #[test]
1976  fn absent_names_resolve_to_none() {
1977    assert!(kpsewhich(&["lxo_definitely_absent_probe_304.tex"]).is_none());
1978  }
1979
1980  /// The backend chosen by `select_kpaths` must resolve a universal host
1981  /// file on whatever distribution is ambient — proving the shipped binary
1982  /// works out of the box on both TeX Live (in-process) and MiKTeX (subprocess
1983  /// fallback, since the linked libkpathsea can't read MiKTeX's fndb). Asks
1984  /// through the process-global `KPSE` handle (never constructs a second
1985  /// `Kpaths` — see the carve-out note). Skips cleanly when no TeX toolchain is
1986  /// present (e.g. a bare CI runner), so it can't spuriously fail there.
1987  #[cfg(feature = "kpathsea")]
1988  #[test]
1989  fn selected_backend_resolves_host_files() {
1990    let cmr = kpsewhich(&["cmr10.tfm"]);
1991    if cmr.is_none() && kpsewhich(&["article.cls"]).is_none() {
1992      return; // no TeX toolchain in this environment — nothing to assert
1993    }
1994    let in_process = KPSE
1995      .lock()
1996      .unwrap()
1997      .as_ref()
1998      .map(|k| k.is_in_process())
1999      .unwrap_or(false);
2000    assert!(
2001      cmr.is_some(),
2002      "selected kpathsea backend failed to resolve the universal cmr10.tfm \
2003       (in_process={in_process}); a MiKTeX host must fall back to subprocess"
2004    );
2005  }
2006
2007  fn pathsearch_tmproot(tag: &str) -> PathBuf {
2008    let mut d = env::temp_dir();
2009    d.push(format!("lxo_pathsearch_{}_{}", std::process::id(), tag));
2010    let _ = std::fs::remove_dir_all(&d);
2011    std::fs::create_dir_all(&d).unwrap();
2012    d
2013  }
2014
2015  /// A `--path` ending in `//` searches the directory tree RECURSIVELY
2016  /// (kpsewhich convention); a plain path searches only that directory.
2017  #[test]
2018  fn recursive_double_slash_descends_into_subdirs() {
2019    let root = pathsearch_tmproot("rec");
2020    let deep = root.join("a").join("b");
2021    std::fs::create_dir_all(&deep).unwrap();
2022    std::fs::write(deep.join("target.tex"), "x").unwrap();
2023    let root_s = root.to_str().unwrap().replace('\\', "/");
2024
2025    let found = find("target.tex", PathnameFindOptions {
2026      paths: Some(vec![format!("{root_s}//")]),
2027      ..Default::default()
2028    });
2029    assert!(
2030      found.as_deref().is_some_and(|p| p.ends_with("target.tex")),
2031      "recursive `//` should find the nested target.tex, got {found:?}"
2032    );
2033
2034    let flat = find("target.tex", PathnameFindOptions {
2035      paths: Some(vec![root_s]),
2036      ..Default::default()
2037    });
2038    assert!(
2039      flat.is_none(),
2040      "a plain (non-`//`) path must NOT descend into subdirectories, got {flat:?}"
2041    );
2042    let _ = std::fs::remove_dir_all(&root);
2043  }
2044
2045  /// The directory named directly by a `--path` (no `//`) is still searched —
2046  /// recursion is opt-in, not a regression of the flat case.
2047  #[test]
2048  fn plain_path_finds_file_in_that_dir() {
2049    let root = pathsearch_tmproot("flat");
2050    std::fs::write(root.join("here.tex"), "x").unwrap();
2051    let root_s = root.to_str().unwrap().replace('\\', "/");
2052    let found = find("here.tex", PathnameFindOptions {
2053      paths: Some(vec![root_s]),
2054      ..Default::default()
2055    });
2056    assert!(
2057      found.as_deref().is_some_and(|p| p.ends_with("here.tex")),
2058      "plain path should find a file directly in it, got {found:?}"
2059    );
2060    let _ = std::fs::remove_dir_all(&root);
2061  }
2062
2063  #[test]
2064  fn is_url_schemes() {
2065    // Perl `pathname_is_url`: `=~ /^($PROTOCOL_RE)/` — the protocol must be
2066    // ANCHORED at the start; a bare host (no /path) still matches.
2067    assert!(is_url("http://example.com/path"));
2068    assert!(is_url("http://example.com/path/file.tex"));
2069    assert!(is_url("ftp://host/file"));
2070    assert!(is_url("https://example.com")); // bare host — Perl matches the prefix
2071    assert!(!is_url("plain/path/file.tex"));
2072    assert!(!is_url("/absolute/path"));
2073    // A filename that merely CONTAINS a protocol mid-string is NOT a URL —
2074    // the old `^\w+://…` matched `myers_http://…` via its leading `\w+`,
2075    // wrongly resolving a JabRef `\bibAnnoteFile` key as an existing URL
2076    // (witness 1509.01434, "Script _").
2077    assert!(!is_url(
2078      "myers_http://www.mscs.dal.ca/myers/welcome.html_2014"
2079    ));
2080    assert!(!is_url("foo_ftp://bar/baz"));
2081  }
2082
2083  #[test]
2084  fn is_literaldata_prefix() {
2085    assert!(is_literaldata("literal:foo"));
2086    assert!(!is_literaldata("file:foo"));
2087    assert!(!is_literaldata("plain"));
2088  }
2089
2090  #[test]
2091  fn is_raw_tex_extensions() {
2092    assert!(is_raw("main.tex"));
2093    assert!(is_raw("hyphen.cfg"));
2094    assert!(is_raw("T1enc.def"));
2095    assert!(is_raw("article.cls"));
2096    assert!(is_raw("french.ldf"));
2097    assert!(!is_raw("foo.pdf"));
2098    assert!(!is_raw("bar.png"));
2099    assert!(!is_raw("baz"));
2100  }
2101
2102  #[test]
2103  fn is_reloadable_only_ldf() {
2104    assert!(is_reloadable("french.ldf"));
2105    assert!(!is_reloadable("main.tex"));
2106    assert!(!is_reloadable("foo.sty"));
2107    assert!(!is_reloadable("baz"));
2108  }
2109
2110  #[test]
2111  fn extension_basic() {
2112    assert_eq!(extension("foo.tex"), "tex");
2113    assert_eq!(extension("path/to/main.cls"), "cls");
2114    assert_eq!(extension("no_ext"), "");
2115    assert_eq!(extension("double.dot.ext"), "ext");
2116  }
2117
2118  #[test]
2119  fn file_name_strips_dirs() {
2120    assert_eq!(file_name("path/to/foo.tex"), "foo.tex");
2121    assert_eq!(file_name("foo.tex"), "foo.tex");
2122    assert_eq!(file_name("/abs/path/foo.tex"), "foo.tex");
2123  }
2124
2125  #[test]
2126  fn file_stem_strips_ext() {
2127    assert_eq!(file_stem("foo.tex"), "foo");
2128    assert_eq!(file_stem("path/to/foo.cls"), "foo");
2129    assert_eq!(file_stem("no_ext"), "no_ext");
2130  }
2131
2132  #[test]
2133  fn directory_returns_dir() {
2134    assert_eq!(directory("path/to/foo.tex"), "path/to");
2135    assert!(
2136      directory("foo.tex").is_empty() || directory("foo.tex") == ".",
2137      "relative-only filename: dir is empty or '.'"
2138    );
2139  }
2140
2141  #[test]
2142  fn make_reassembles_components() {
2143    let p = make(Some("path"), Some("foo"), Some("tex"));
2144    assert_eq!(p, "path/foo.tex");
2145  }
2146
2147  #[test]
2148  fn make_none_dir() {
2149    let p = make(None, Some("foo"), Some("tex"));
2150    // No directory → no leading slash.
2151    assert_eq!(p, "foo.tex");
2152  }
2153
2154  #[test]
2155  fn concat_joins_with_slash() {
2156    assert_eq!(concat("path", "foo.tex"), "path/foo.tex");
2157    assert_eq!(concat("a/b", "c.tex"), "a/b/c.tex");
2158  }
2159
2160  /// Perl `pathname_canonical` (Util/Pathname.pm:128) drops `dir/..` only for a real `dir`: a leading `./` is no
2161  /// directory (repro confinement/dot_parent_names).
2162  #[test]
2163  fn canonical_drops_only_a_real_directory_before_dotdot() {
2164    for (written, expected) in [
2165      ("./../../x", "../../x"),
2166      ("./sub/../../../x", "../../x"),
2167      ("./..", ".."),
2168      ("../a/b/../c", "../a/c"),
2169      ("/a/./b/../c", "/a/c"),
2170      ("/a/..", "/"),
2171      // (a relative name stays relative)
2172      (".//x", "x"),
2173      ("././/etc/x", "etc/x"),
2174      ("./././/x", "x"),
2175      ("x/..//etc/x", "etc/x"),
2176      ("./x/..//etc/x", "etc/x"),
2177      (".//../x", "../x"),
2178      (".//", "./"),
2179      // (an empty component is no directory: `doc//..` stays for the system to climb)
2180      ("/t/doc//../x", "/t/doc//../x"),
2181    ] {
2182      assert_eq!(canonical(written), expected, "{written}");
2183    }
2184    for (written, expected) in [
2185      (".//x", "x"),
2186      ("././/x", "x"),
2187      (".//./x", "x"),
2188      ("./x", "./x"),
2189      ("././x", "././x"),
2190      (".//", ".//"),
2191    ] {
2192      assert_eq!(dot_relative(written), expected, "{written}");
2193    }
2194  }
2195
2196  #[test]
2197  fn url_split_basic() {
2198    // URL_RE captures groups: 1=host+dir, 2=filename.
2199    let (base, file) = url_split("http://example.com/path/file.tex");
2200    assert_eq!(base, "example.com/path");
2201    assert_eq!(file, "file.tex");
2202  }
2203
2204  #[test]
2205  fn url_split_non_url_gets_index() {
2206    // Non-URL input falls back to (input, "index.tex").
2207    let (proto, rest) = url_split("plain_string");
2208    assert_eq!(proto, "plain_string");
2209    assert_eq!(rest, "index.tex");
2210  }
2211
2212  #[test]
2213  fn split_basic_path() {
2214    let (d, n, e) = split("path/to/foo.tex");
2215    assert_eq!(d, "path/to");
2216    assert_eq!(n, "foo");
2217    assert_eq!(e, "tex");
2218  }
2219
2220  #[test]
2221  fn split_no_ext() {
2222    let (_d, n, e) = split("foo");
2223    assert_eq!(n, "foo");
2224    assert_eq!(e, "");
2225  }
2226
2227  #[test]
2228  fn is_nasty_detects_bad_patterns() {
2229    // Consult the regex; typical "nasty" is path traversal `..` or
2230    // shell chars.
2231    let has_dotdot = is_nasty("path/../bad");
2232    let safe = is_nasty("foo.tex");
2233    // Whatever the regex is, path traversal should be flagged and a
2234    // plain filename should not.
2235    assert!(!safe, "plain filename should not be nasty");
2236    // Keep the dotdot assertion loose — the exact patterns are
2237    // implementation-defined.
2238    let _ = has_dotdot;
2239  }
2240
2241  #[test]
2242  fn nocase_dir_cache_finds_case_mismatch_and_skips_dirs() {
2243    let root = pathsearch_tmproot("nocase_cache");
2244    std::fs::write(root.join("PASJ95.STY"), "% sty").unwrap();
2245    std::fs::create_dir(root.join("INTRO")).unwrap();
2246    let root_s = root.to_str().unwrap().replace('\\', "/");
2247
2248    // Exercise `nocase_dir_cache::lookup` directly so the cache path is tested
2249    // even on case-insensitive filesystems (macOS APFS, Windows) where `find()`
2250    // hits Pass 1 before reaching the fallback cache.
2251    let found1 = nocase_dir_cache::lookup(&root, "pasj95.sty");
2252    let found2 = nocase_dir_cache::lookup(&root, "pasj95.sty");
2253    assert!(
2254      found1.as_deref().is_some_and(|p| p.ends_with("PASJ95.STY")),
2255      "expected PASJ95.STY, got {found1:?}"
2256    );
2257    assert_eq!(found2, found1);
2258
2259    // Subdirectories are never returned as readable files.
2260    assert_eq!(nocase_dir_cache::lookup(&root, "intro"), None);
2261
2262    // Misses stay `None`; per-conversion cache reset immediately exposes newly
2263    // created files with zero dependence on filesystem mtime granularity.
2264    assert_eq!(nocase_dir_cache::lookup(&root, "later.sty"), None);
2265    std::fs::write(root.join("LATER.STY"), "% later").unwrap();
2266    clear_nocase_dir_cache();
2267    let later = nocase_dir_cache::lookup(&root, "later.sty");
2268    assert!(
2269      later.as_deref().is_some_and(|p| p.ends_with("LATER.STY")),
2270      "expected LATER.STY after cache clear, got {later:?}"
2271    );
2272
2273    // On Unix, creating a sibling subdirectory increments the parent's `st_nlink`
2274    // immediately (even on 1s-resolution filesystems), invalidating `DirStamp`
2275    // without calling `clear_nocase_dir_cache()`.
2276    #[cfg(unix)]
2277    {
2278      assert_eq!(nocase_dir_cache::lookup(&root, "after_nlink.sty"), None);
2279      std::fs::write(root.join("AFTER_NLINK.STY"), "% nlink").unwrap();
2280      std::fs::create_dir(root.join("BUMP_NLINK")).unwrap();
2281      let after = nocase_dir_cache::lookup(&root, "after_nlink.sty");
2282      assert!(
2283        after
2284          .as_deref()
2285          .is_some_and(|p| p.ends_with("AFTER_NLINK.STY")),
2286        "expected AFTER_NLINK.STY after dir stamp change, got {after:?}"
2287      );
2288    }
2289
2290    // End-to-end `find()`: on case-sensitive filesystems Pass 1 misses and
2291    // Pass 2 returns the on-disk casing (`PASJ95.STY`); on case-insensitive
2292    // filesystems Pass 1 succeeds directly with the requested spelling.
2293    let opts = || PathnameFindOptions {
2294      paths: Some(vec![root_s.clone()]),
2295      ..Default::default()
2296    };
2297    clear_nocase_dir_cache();
2298    let case_sensitive = !is_readable_file(&format!("{root_s}/pasj95.sty"));
2299    let via_find = find("pasj95.sty", opts());
2300    let expected_suffix = if case_sensitive {
2301      "PASJ95.STY"
2302    } else {
2303      "pasj95.sty"
2304    };
2305    assert!(
2306      via_find
2307        .as_deref()
2308        .is_some_and(|p| p.ends_with(expected_suffix)),
2309      "expected {expected_suffix}, got {via_find:?}"
2310    );
2311    assert_eq!(find("pasj95.sty", opts()), via_find);
2312    assert_eq!(find("intro", opts()), None);
2313
2314    let _ = std::fs::remove_dir_all(&root);
2315  }
2316}