Skip to main content

latexml_core/common/
cleaners.rs

1use std::{borrow::Cow, sync::LazyLock};
2
3use regex::Regex;
4use unicode_normalization::UnicodeNormalization;
5use unidecode::unidecode;
6
7use crate::binding::def::dialect::{
8  DIRTY_ID_IDIOM_RE, LEADING_PROTOCOL_RE, NON_ID_CHARSET_RE, SPACES_RE, TILDE_NOISE_RE,
9  TRAILING_SLASH_RE,
10};
11
12static TRAILING_PUNCT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\.,;]+$").unwrap());
13static NON_ALNUM_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[^a-zA-Z0-9]").unwrap());
14
15//======================================================================
16// Cleaners
17//======================================================================
18
19/// Perl's `substr($text, $offset, $len)` for a non-negative offset and length: it counts CHARACTERS, so a byte slice of
20/// document text (`year[2..4]` on `1–250, 2023`, witnesses 2308.14725, 2607.14650) panics where Perl reads on. Past
21/// the end it is empty, as Perl's in-range `substr` is.
22pub fn substr(text: &str, offset: usize, len: usize) -> &str {
23  let byte_at = |n: usize, from: &str| from.char_indices().nth(n).map_or(from.len(), |(at, _)| at);
24  let start = byte_at(offset, text);
25  let rest = &text[start..];
26  &rest[..byte_at(len, rest)]
27}
28
29static RMLETTERS: [char; 7] = ['i', 'v', 'x', 'l', 'c', 'd', 'm'];
30/// auxiliary helper for `roman`
31pub fn roman_aux<T: Into<i64>>(stuff: T) -> String {
32  let mut n: i64 = stuff.into();
33  if n <= 0 {
34    return String::new();
35  }
36  let mut div = 1000;
37  let mut s: String = if n >= div {
38    String::from_utf8(vec![b'm'; (n / div) as usize]).unwrap()
39  } else {
40    String::new()
41  };
42  let mut p = 4;
43  while n % div != 0 {
44    n %= div;
45    div /= 10;
46    let mut d = n / div;
47    if d % 5 == 4 {
48      s.push(RMLETTERS[p]);
49      d += 1;
50    }
51    if d > 4 {
52      s.push(RMLETTERS[p + (d / 5) as usize]);
53      d %= 5;
54    }
55    if d != 0 {
56      s.push_str(&String::from_utf8(vec![RMLETTERS[p] as u8; d as usize]).unwrap());
57    }
58    // silly, but i'm postponing rewriting the entire method for now, just porting over from Perl
59    if p > 2 {
60      p -= 2;
61    } else {
62      p = 0;
63    }
64  }
65  s
66}
67
68/// cleans a string down to characters acceptable for an id attribute
69pub fn clean_id(key: &str) -> String {
70  let cleaned = Cow::Borrowed(key.trim()); // Trim leading/trailing whitespace
71  let cleaned_1 = SPACES_RE.replace_all(&cleaned, ""); // remove all spaces
72  // Remove common idiom:
73  // Perl parity: CleanID strips `${}^{foo}$` down to just `foo`.
74  // The regex captures that inner content as named group `label`; the
75  // replacement must reference it by the correct name (`$inner` was a
76  // stale typo that silently erased the captured text).
77  let cleaned_2 = DIRTY_ID_IDIOM_RE.replace_all(&cleaned_1, "$label");
78  // transform some forbidden chars
79  let cleaned_3 = cleaned_2
80    .replace(':', "..") // No colons!
81    .replace('@', "-at-")
82    .replace('*', "-star-")
83    .replace('$', "-dollar-")
84    .replace(',', "-comma-")
85    .replace('%', "-pct-")
86    .replace('&', "-amp-");
87  let cleaned_4 = unidecode(&cleaned_3);
88  let cleaned_5 = NON_ID_CHARSET_RE.replace_all(&cleaned_4, ""); // remove everything else.
89  let out = cleaned_5.as_ref();
90  // Perl parity (Package.pm CleanID): XML ids must start with a letter or `_`
91  // (since we already replaced `:` with `..`). Prepend "X" when the cleaned
92  // key starts with anything else — protects against leading `.`, `-`, or
93  // digits, which would otherwise produce invalid id attributes.
94  match out.chars().next() {
95    Some(c) if c.is_ascii_alphabetic() || c == '_' => out.to_string(),
96    Some(_) => format!("X{out}"),
97    None => String::new(),
98  }
99}
100/// cleans a string down to characters acceptable for a label attribute
101pub fn clean_label<'a>(label: &'a str, prefix_opt: Option<&str>) -> Cow<'a, str> {
102  let key = label.trim(); // Trim leading/trailing, in any case
103  let cleaned_1 = SPACES_RE.replace_all(key, "_"); // spaces to underscores
104  let prefix = prefix_opt.unwrap_or("LABEL");
105  if prefix.is_empty() {
106    cleaned_1
107  } else {
108    Cow::Owned(s!("{}:{}", prefix, cleaned_1))
109  }
110}
111
112/// Clean string for use in index keys (Perl: CleanIndexKey)
113/// Applies NFC normalization and removes trailing punctuation.
114pub fn clean_index_key(key: &str) -> String {
115  let trimmed = key.trim();
116  let normalized: String = trimmed.nfc().collect();
117  TRAILING_PUNCT_RE.replace(&normalized, "").to_string()
118}
119
120/// Clean string for use as a CSS class name (Perl: CleanClassName)
121/// Decomposes to NFD, removes non-alphanumeric chars, recomposes to NFC.
122pub fn clean_class_name(key: &str) -> String {
123  let trimmed = key.trim();
124  let decomposed: String = trimmed.nfd().collect();
125  let cleaned = NON_ALNUM_RE.replace_all(&decomposed, "");
126  cleaned.nfc().collect()
127}
128
129/// cleans a string down to characters acceptable for a bibliography key
130pub fn clean_bib_key(key: &str) -> String {
131  // Originally lc() here, but let's preserve case till Postproc.
132  let trimmed = key.trim();
133  SPACES_RE.replace_all(trimmed, "").to_string()
134}
135
136/// Return the bibkey in a form to ACTUALLY lookup (Perl: NormalizeBibKey)
137/// Usually use clean_bib_key to preserve key in the original form (case)
138pub fn normalize_bib_key(key: &str) -> String { clean_bib_key(key).to_lowercase() }
139
140/// Split comma-separated text into trimmed tokens (Perl: TrimmedCommaList)
141pub fn trimmed_comma_list(text: &str) -> Vec<String> {
142  let trimmed = text.trim();
143  if trimmed.is_empty() {
144    return Vec::new();
145  }
146  trimmed.split(',').map(|s| s.trim().to_string()).collect()
147}
148
149/// cleans a string down to characters acceptable for a URL
150pub fn clean_url(url: &str) -> String {
151  let cleaned = url.trim(); // Trim leading/trailing whitespace
152  TILDE_NOISE_RE.replace_all(cleaned, "~").to_string()
153}
154
155/// builds a complete url from fragments
156pub fn compose_url(base: &str, url: &str, fragid_opt: Option<&str>) -> String {
157  let base = TRAILING_SLASH_RE.replace(base, ""); //  remove trailing /
158  let fragid = fragid_opt.unwrap_or("");
159  let base: String = if !base.is_empty() && !LEADING_PROTOCOL_RE.is_match(url) {
160    // already has protocol, so is absolute url
161    base.to_string() + if url.starts_with('/') { "" } else { "/" } // else start w/base, possibly /
162  } else {
163    String::new()
164  };
165  let fragid: String = if !fragid.is_empty() {
166    s!("#{}", clean_id(fragid))
167  } else {
168    String::new()
169  };
170  clean_url(&(base + url + &fragid))
171}
172
173#[cfg(test)]
174mod tests {
175  use super::*;
176
177  #[test]
178  fn clean_id_preserves_alpha_start() {
179    assert_eq!(clean_id("foo"), "foo");
180    assert_eq!(clean_id("Foo_bar"), "Foo_bar");
181    assert_eq!(clean_id("_underscore"), "_underscore");
182  }
183
184  #[test]
185  fn clean_id_prepends_x_for_non_alpha_start() {
186    // Leading digit, dot, or hyphen is invalid in XML ids — prepend X.
187    assert_eq!(clean_id("1foo"), "X1foo");
188    assert_eq!(clean_id(".foo"), "X.foo");
189    assert_eq!(clean_id("-foo"), "X-foo");
190  }
191
192  #[test]
193  fn clean_id_after_colon_replacement() {
194    // `:` becomes `..`, so ":foo" → "..foo" → needs X prefix.
195    assert_eq!(clean_id(":foo"), "X..foo");
196  }
197
198  #[test]
199  fn clean_id_empty_stays_empty() {
200    assert_eq!(clean_id(""), "");
201    assert_eq!(clean_id("   "), "");
202  }
203
204  #[test]
205  fn clean_id_dirty_idiom_preserves_label() {
206    // Perl: $key =~ s/\$\{\}\^\{(.*?)\}\$/$1/g; retains the captured
207    // content. Common TeX idiom from latex generates ${}^{foo}$.
208    assert_eq!(clean_id("${}^{foo}$"), "foo");
209    assert_eq!(clean_id("bar${}^{tag}$"), "bartag");
210  }
211
212  #[test]
213  fn roman_aux_non_positive() {
214    assert_eq!(roman_aux(0i64), "");
215    assert_eq!(roman_aux(-1i64), "");
216  }
217
218  #[test]
219  fn roman_aux_basic() {
220    assert_eq!(roman_aux(1i64), "i");
221    assert_eq!(roman_aux(1000i64), "m");
222    assert_eq!(roman_aux(1999i64), "mcmxcix");
223  }
224
225  #[test]
226  fn clean_label_default_prefix() {
227    // Spaces become underscores; default prefix is "LABEL:".
228    assert_eq!(clean_label("foo bar", None), "LABEL:foo_bar");
229    assert_eq!(clean_label("simple", None), "LABEL:simple");
230  }
231
232  #[test]
233  fn clean_label_custom_prefix() {
234    assert_eq!(clean_label("thm:main", Some("REF")), "REF:thm:main");
235  }
236
237  #[test]
238  fn clean_label_empty_prefix_skips_colon() {
239    // Empty prefix means no prefix at all (not an empty-prefix colon).
240    let out = clean_label("foo bar", Some(""));
241    assert_eq!(out, "foo_bar");
242  }
243
244  #[test]
245  fn clean_label_trims_whitespace() {
246    // Leading/trailing whitespace trimmed before space-to-underscore.
247    assert_eq!(clean_label("  foo  ", None), "LABEL:foo");
248  }
249
250  #[test]
251  fn clean_class_name_basic() {
252    // clean_class_name strips spaces, converts to lowercase, removes
253    // non-class-safe chars.
254    let out = clean_class_name("foo");
255    assert!(out.contains("foo"), "got {out:?}");
256  }
257
258  #[test]
259  fn clean_bib_key_basic() {
260    // Bib keys are case-preserved but trimmed/cleaned.
261    let out = clean_bib_key("Author:2020");
262    assert!(!out.is_empty());
263  }
264
265  #[test]
266  fn normalize_bib_key_case_insensitive() {
267    // normalize_bib_key should produce the same output for case variants.
268    let a = normalize_bib_key("Author2020");
269    let b = normalize_bib_key("AUTHOR2020");
270    assert_eq!(a, b, "normalize_bib_key folds case (got {a:?} vs {b:?})");
271  }
272
273  #[test]
274  fn trimmed_comma_list_basic() {
275    let out = trimmed_comma_list("a, b ,c,  d");
276    assert_eq!(out, vec!["a", "b", "c", "d"]);
277  }
278
279  #[test]
280  fn trimmed_comma_list_handles_empty_segments() {
281    // Leading/trailing/internal empty comma positions — behavior may
282    // retain empty tokens or drop them depending on the implementation;
283    // just assert consistency with non-empty entries.
284    let out = trimmed_comma_list(",a,,b,");
285    assert!(
286      out.iter().any(|s| s == "a") && out.iter().any(|s| s == "b"),
287      "got {out:?}"
288    );
289  }
290
291  #[test]
292  fn clean_url_removes_quotes_and_whitespace() {
293    // clean_url is lenient — it trims and normalizes. At minimum it
294    // must not break a well-formed URL.
295    let canonical = "http://example.com/path";
296    assert_eq!(clean_url(canonical), canonical);
297  }
298
299  #[test]
300  fn clean_index_key_trims_trailing_punct() {
301    // Per docstring: Applies NFC + strips trailing punctuation.
302    let out = clean_index_key("topic.");
303    assert_eq!(out, "topic", "got {out:?}");
304  }
305}