ctb_formats_html/
entities.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! HTML parsing, plain text rendering, and HTML table extraction utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::get_html_data;
30use ctb_utilities::csv_tools::{self, CsvTable};
31use std::collections::HashMap;
32use std::sync::{Arc, Mutex, OnceLock};
33
34/// Supported HTML / XML / MathML entity sets.
35#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
36pub enum EntitySet {
37    /// HTML 3.2 Latin 1 entities.
38    Html32,
39    /// Netscape 1999 RSS board HTML entity set.
40    Netscape1999,
41    /// XML standard entity set (including &apos;).
42    Xml,
43    /// HTML 4.0 character entity set.
44    Html4,
45    /// HTML 5 named character references (including multi-codepoint and legacy semicolon-less references).
46    Html5,
47    /// MathML entity set.
48    MathMl,
49}
50
51impl EntitySet {
52    /// Returns the CSV filename corresponding to this entity set.
53    #[must_use]
54    pub const fn filename(self) -> &'static str {
55        match self {
56            Self::Html32 => "entities-html32.csv",
57            Self::Netscape1999 => "entities-netscape-1999.csv",
58            Self::Xml => "entities-xml.csv",
59            Self::Html4 => "entities-html4.0.csv",
60            Self::Html5 => "entities-html5.csv",
61            Self::MathMl => "entities-mathml.csv",
62        }
63    }
64
65    /// Returns the cache key for this entity set.
66    #[must_use]
67    pub const fn cache_key(self) -> &'static str {
68        match self {
69            Self::Html32 => "ctb_formats_html::data/entities-html32.csv",
70            Self::Netscape1999 => {
71                "ctb_formats_html::data/entities-netscape-1999.csv"
72            }
73            Self::Xml => "ctb_formats_html::data/entities-xml.csv",
74            Self::Html4 => "ctb_formats_html::data/entities-html4.0.csv",
75            Self::Html5 => "ctb_formats_html::data/entities-html5.csv",
76            Self::MathMl => "ctb_formats_html::data/entities-mathml.csv",
77        }
78    }
79}
80
81/// In-memory table storing bidirectional entity lookups.
82#[derive(Clone, Debug, Default)]
83pub struct EntityTable {
84    char_to_entity: HashMap<String, String>,
85    entity_to_text: HashMap<String, String>,
86    max_entity_len: usize,
87}
88
89fn parse_entity_table(
90    set: EntitySet,
91    records: &CsvTable,
92) -> Result<EntityTable> {
93    let mut char_to_entity = HashMap::new();
94    let mut entity_to_text = HashMap::new();
95
96    for row_idx in 0..records.row_count() {
97        let Some(row) = records.row(row_idx) else {
98            continue;
99        };
100        if row.is_empty() {
101            continue;
102        }
103
104        match set {
105            EntitySet::Html32 | EntitySet::Netscape1999 => {
106                // Format: Col 0 = Char, Col 1 = Numeric (&#...;), Col 2 = Named (&...;)
107                if let (Some(col0), Some(col2)) = (row.first(), row.get(2)) {
108                    let char_str = col0.clone();
109                    let named_entity = col2.clone();
110                    if !char_str.is_empty() && !named_entity.is_empty() {
111                        char_to_entity
112                            .entry(char_str.clone())
113                            .or_insert_with(|| named_entity.clone());
114                        entity_to_text.insert(named_entity, char_str);
115                    }
116                }
117            }
118            EntitySet::Xml | EntitySet::Html4 => {
119                // Format: Col 0 = Decimal codepoint, Col 1 = name (without & or ;)
120                if let (Some(col0), Some(col1)) = (row.first(), row.get(1)) {
121                    if let Ok(ch) =
122                        crate::utilities::string::parse_dec_char(col0)
123                    {
124                        let char_str = ch.to_string();
125                        let named_entity = format!("&{col1};");
126                        char_to_entity
127                            .entry(char_str.clone())
128                            .or_insert_with(|| named_entity.clone());
129                        entity_to_text.insert(named_entity, char_str);
130                    }
131                }
132            }
133            EntitySet::Html5 => {
134                // Format: Col 0 = Hex codepoints space-separated, Col 1 = name (with or without ;)
135                if let (Some(col0), Some(col1)) = (row.first(), row.get(1)) {
136                    let mut text = String::new();
137                    for part in col0.split_whitespace() {
138                        if let Ok(ch) =
139                            crate::utilities::string::parse_hex_char(part)
140                        {
141                            text.push(ch);
142                        }
143                    }
144                    if !text.is_empty() {
145                        let named_entity = format!("&{col1}");
146                        entity_to_text
147                            .insert(named_entity.clone(), text.clone());
148                        if named_entity.ends_with(';') {
149                            char_to_entity.entry(text).or_insert(named_entity);
150                        }
151                    }
152                }
153            }
154            EntitySet::MathMl => {
155                // Format: Col 0 = Codepoints space-separated (decimal or hex), Col 1 = name (without & or ;)
156                if let (Some(col0), Some(col1)) = (row.first(), row.get(1)) {
157                    let mut text = String::new();
158                    for part in col0.split_whitespace() {
159                        let ch_opt = if col0.starts_with('x') {
160                            crate::utilities::string::parse_hex_char(part).ok()
161                        } else {
162                            crate::utilities::string::parse_dec_char(part).ok()
163                        };
164                        if let Some(ch) = ch_opt {
165                            text.push(ch);
166                        }
167                    }
168                    if !text.is_empty() {
169                        let named_entity = format!("&{col1};");
170                        entity_to_text
171                            .insert(named_entity.clone(), text.clone());
172                        char_to_entity.entry(text).or_insert(named_entity);
173                    }
174                }
175            }
176        }
177    }
178
179    let max_entity_len = match entity_to_text.keys().map(String::len).max() {
180        Some(len) => len,
181        None => 0,
182    };
183
184    Ok(EntityTable {
185        char_to_entity,
186        entity_to_text,
187        max_entity_len,
188    })
189}
190
191static ENTITY_TABLES: OnceLock<Mutex<HashMap<EntitySet, Arc<EntityTable>>>> =
192    OnceLock::new();
193
194fn get_entity_table(set: EntitySet) -> Result<Arc<EntityTable>> {
195    let map_mutex = ENTITY_TABLES.get_or_init(|| Mutex::new(HashMap::new()));
196    let mut map = map_mutex
197        .lock()
198        .map_err(|e| anyhow::anyhow!("Entity cache lock poisoned: {e}"))?;
199    if let Some(table) = map.get(&set) {
200        return Ok(Arc::clone(table));
201    }
202    let csv = csv_tools::get_or_load_cached(set.cache_key(), || {
203        let bytes = bail_if_none!(get_html_data(set.filename()));
204        csv_tools::parse_csv_reader(
205            &bytes,
206            csv_tools::CsvParseOptions {
207                has_header: false,
208                ..Default::default()
209            },
210        )
211    })?;
212    let table = Arc::new(parse_entity_table(set, &csv)?);
213    map.insert(set, Arc::clone(&table));
214    Ok(table)
215}
216
217/// Escape HTML special characters to be used in text content.
218pub fn escape_text(text: &str) -> String {
219    html_escape::encode_text(text).to_string()
220}
221
222/// Escape special characters for use in HTML attribute values.
223pub fn escape_quoted_attr(text: &str) -> String {
224    html_escape::encode_quoted_attribute(text).to_string()
225}
226
227fn core_entity_for_char(ch: char, set: EntitySet) -> Option<&'static str> {
228    match ch {
229        '<' => Some("&lt;"),
230        '>' => Some("&gt;"),
231        '&' => Some("&amp;"),
232        '"' => Some("&quot;"),
233        '\'' if matches!(set, EntitySet::Xml) => Some("&apos;"),
234        _ => None,
235    }
236}
237
238fn core_char_for_entity(entity: &str) -> Option<char> {
239    match entity {
240        "&lt;" => Some('<'),
241        "&gt;" => Some('>'),
242        "&amp;" => Some('&'),
243        "&quot;" => Some('"'),
244        "&apos;" => Some('\''),
245        _ => None,
246    }
247}
248
249fn decode_numeric_entity(entity: &str) -> Option<char> {
250    let numeric = entity.strip_prefix("&#")?.strip_suffix(';')?;
251
252    let (radix, digits) = if let Some(hex) = numeric
253        .strip_prefix('x')
254        .or_else(|| numeric.strip_prefix('X'))
255    {
256        (16, hex)
257    } else {
258        (10, numeric)
259    };
260
261    let value = u32::from_str_radix(digits, radix).ok()?;
262    char::from_u32(value)
263}
264
265/// Replace applicable characters with named HTML entities from the specified entity set.
266///
267/// Unknown characters are left as-is.
268pub fn to_entities(input: String, set: EntitySet) -> Result<String> {
269    let table = get_entity_table(set)?;
270    let mut out = String::with_capacity(input.len());
271    for ch in input.chars() {
272        if let Some(entity) = core_entity_for_char(ch, set) {
273            out.push_str(entity);
274        } else if let Some(entity) = table.char_to_entity.get(&ch.to_string()) {
275            out.push_str(entity);
276        } else {
277            out.push(ch);
278        }
279    }
280    Ok(out)
281}
282
283/// Replace HTML entities (named or numeric) with characters using the specified entity set.
284///
285/// Unknown entities are left as-is.
286pub fn from_entities(input: String, set: EntitySet) -> Result<String> {
287    let table = get_entity_table(set)?;
288    let mut i = 0usize;
289    let mut out = String::with_capacity(input.len());
290
291    while i < input.len() {
292        let Some(rest) = input.get(i..) else {
293            break;
294        };
295
296        if !rest.starts_with('&') {
297            let Some(ch) = rest.chars().next() else {
298                break;
299            };
300            out.push(ch);
301            i = i.saturating_add(ch.len_utf8());
302            continue;
303        }
304
305        // Numeric entity: &#123; or &#x12a;
306        if rest.starts_with("&#") {
307            if let Some(semi_pos) = rest.find(';') {
308                if let Some(candidate) = rest.get(..=semi_pos) {
309                    if let Some(ch) = decode_numeric_entity(candidate) {
310                        out.push(ch);
311                        i = i.saturating_add(semi_pos).saturating_add(1);
312                        continue;
313                    }
314                }
315            }
316        }
317
318        // Named entity lookup
319        // 1. Try finding a ';' up to max_entity_len
320        let max_search = table.max_entity_len.min(rest.len());
321        let mut matched = false;
322
323        if let Some(semi_pos) = rest.get(..max_search).and_then(|s| s.find(';'))
324        {
325            if let Some(candidate) = rest.get(..=semi_pos) {
326                if let Some(ch) = core_char_for_entity(candidate) {
327                    out.push(ch);
328                    i = i.saturating_add(semi_pos).saturating_add(1);
329                    matched = true;
330                } else if let Some(replacement) =
331                    table.entity_to_text.get(candidate)
332                {
333                    out.push_str(replacement);
334                    i = i.saturating_add(semi_pos).saturating_add(1);
335                    matched = true;
336                }
337            }
338        }
339
340        if matched {
341            continue;
342        }
343
344        // 2. If no semicolon match, check for semicolon-less entity (only registered for HTML5)
345        let mut longest_len = 0usize;
346        let mut longest_replacement: Option<&str> = None;
347
348        for prefix_len in (2..=max_search).rev() {
349            if let Some(candidate) = rest.get(..prefix_len) {
350                if let Some(replacement) = table.entity_to_text.get(candidate) {
351                    longest_len = prefix_len;
352                    longest_replacement = Some(replacement.as_str());
353                    break;
354                }
355            }
356        }
357
358        if let Some(replacement) = longest_replacement {
359            out.push_str(replacement);
360            i = i.saturating_add(longest_len);
361            continue;
362        }
363
364        // Unrecognized entity: output '&' and advance 1 byte
365        out.push('&');
366        i = i.saturating_add('&'.len_utf8());
367    }
368
369    Ok(out)
370}
371
372/// Replace applicable characters with their Netscape 1999 named HTML entities.
373///
374/// Unknown characters are left as-is. Those with HTML syntax significance are
375/// encoded, except '.
376pub fn to_entities_netscape_1999(input: String) -> Result<String> {
377    to_entities(input, EntitySet::Netscape1999)
378}
379
380/// Replace Netscape 1999 HTML entities (named or numeric) with characters.
381///
382/// Unknown entities are left as-is.
383pub fn from_entities_netscape_1999(input: String) -> Result<String> {
384    from_entities(input, EntitySet::Netscape1999)
385}
386
387/// Replace applicable characters with their HTML 3.2 named HTML entities.
388///
389/// Unknown characters are left as-is. Those with HTML syntax significance are
390/// encoded, except '.
391pub fn to_entities_html32(input: String) -> Result<String> {
392    to_entities(input, EntitySet::Html32)
393}
394
395/// Replace HTML 3.2 named HTML entities (named or numeric) with characters.
396///
397/// Unknown entities are left as-is.
398pub fn from_entities_html32(input: String) -> Result<String> {
399    from_entities(input, EntitySet::Html32)
400}
401
402/// Replace applicable characters with their XML named entities.
403///
404/// Unknown characters are left as-is. Those with XML syntax significance (<, >, &, ", ')
405/// are encoded.
406pub fn to_entities_xml(input: String) -> Result<String> {
407    to_entities(input, EntitySet::Xml)
408}
409
410/// Replace XML named entities (named or numeric) with characters.
411///
412/// Unknown entities are left as-is.
413pub fn from_entities_xml(input: String) -> Result<String> {
414    from_entities(input, EntitySet::Xml)
415}
416
417/// Replace applicable characters with their HTML 4.0 named HTML entities.
418///
419/// Unknown characters are left as-is. Those with HTML syntax significance are
420/// encoded, except '.
421pub fn to_entities_html4(input: String) -> Result<String> {
422    to_entities(input, EntitySet::Html4)
423}
424
425/// Replace HTML 4.0 named HTML entities (named or numeric) with characters.
426///
427/// Unknown entities are left as-is.
428pub fn from_entities_html4(input: String) -> Result<String> {
429    from_entities(input, EntitySet::Html4)
430}
431
432/// Replace applicable characters with their HTML 5 named HTML entities.
433///
434/// Unknown characters are left as-is. Those with HTML syntax significance are
435/// encoded, except '.
436pub fn to_entities_html5(input: String) -> Result<String> {
437    to_entities(input, EntitySet::Html5)
438}
439
440/// Replace HTML 5 named HTML entities (named or numeric) with characters.
441///
442/// Unknown entities are left as-is.
443pub fn from_entities_html5(input: String) -> Result<String> {
444    from_entities(input, EntitySet::Html5)
445}
446
447/// Replace applicable characters with their MathML named entities.
448///
449/// Unknown characters are left as-is. Those with HTML/XML syntax significance are
450/// encoded, except '.
451pub fn to_entities_mathml(input: String) -> Result<String> {
452    to_entities(input, EntitySet::MathMl)
453}
454
455/// Replace MathML named entities (named or numeric) with characters.
456///
457/// Unknown entities are left as-is.
458pub fn from_entities_mathml(input: String) -> Result<String> {
459    from_entities(input, EntitySet::MathMl)
460}
461
462#[cfg(test)]
463#[allow(
464    clippy::panic,
465    clippy::expect_used,
466    clippy::unwrap_used,
467    clippy::unwrap_in_result,
468    clippy::panic_in_result_fn,
469    clippy::indexing_slicing,
470    clippy::arithmetic_side_effects,
471    reason = "Standard repository test boilerplate"
472)]
473mod tests {
474    use super::*;
475
476    #[crate::ctb_test]
477    fn test_escape_html() {
478        assert_eq!(escape_text("Hello"), "Hello");
479        assert_eq!(escape_text("<script>"), "&lt;script&gt;");
480        assert_eq!(escape_text("A & B"), "A &amp; B");
481        assert_eq!(escape_text("1 < 2 > 0"), "1 &lt; 2 &gt; 0");
482    }
483
484    #[crate::ctb_test]
485    fn test_escape_attr() {
486        assert_eq!(escape_quoted_attr("Hello"), "Hello");
487        assert_eq!(escape_quoted_attr("a\"b"), "a&quot;b");
488        assert_eq!(escape_quoted_attr("it's"), "it&#x27;s");
489        assert_eq!(escape_quoted_attr("a&b"), "a&amp;b");
490    }
491
492    #[crate::ctb_test]
493    fn test_netscape_entities_1999_roundtrip_basic() -> Result<()> {
494        assert_eq!(
495            &*to_entities_netscape_1999("Å & B".to_string())?,
496            "&ring; &amp; B"
497        );
498
499        let input = "<&\"".to_string();
500        let encoded = to_entities_netscape_1999(input.clone())?;
501        assert_eq!(encoded, "&lt;&amp;&quot;".to_string());
502        let decoded = from_entities_netscape_1999(encoded)?;
503        assert_eq!(decoded, input);
504        Ok(())
505    }
506
507    #[crate::ctb_test]
508    fn test_netscape_entities_1999_decodes_numeric() -> Result<()> {
509        let decoded =
510            from_entities_netscape_1999("&#60;&#38;&#34;".to_string())?;
511        assert_eq!(decoded, "<&\"".to_string());
512        Ok(())
513    }
514
515    #[crate::ctb_test]
516    fn test_html32_roundtrip_basic() -> Result<()> {
517        assert_eq!(
518            &*to_entities_html32("Å & B".to_string())?,
519            "&Aring; &amp; B"
520        );
521
522        let input = "<&\"".to_string();
523        let encoded = to_entities_html32(input.clone())?;
524        assert_eq!(encoded, "&lt;&amp;&quot;".to_string());
525        let decoded = from_entities_html32(encoded)?;
526        assert_eq!(decoded, input);
527        Ok(())
528    }
529
530    #[crate::ctb_test]
531    fn test_html32_decodes_numeric() -> Result<()> {
532        let decoded = from_entities_html32("&#60;&#38;&#34;".to_string())?;
533        assert_eq!(decoded, "<&\"".to_string());
534        Ok(())
535    }
536
537    #[crate::ctb_test]
538    fn test_xml_entities() -> Result<()> {
539        let input = "<&\"'>".to_string();
540        let encoded = to_entities_xml(input.clone())?;
541        assert_eq!(encoded, "&lt;&amp;&quot;&apos;&gt;");
542        let decoded = from_entities_xml(encoded)?;
543        assert_eq!(decoded, input);
544        Ok(())
545    }
546
547    #[crate::ctb_test]
548    fn test_html4_entities() -> Result<()> {
549        let input = "© 2026 & Co. ™".to_string();
550        let encoded = to_entities_html4(input.clone())?;
551        assert_eq!(encoded, "&copy; 2026 &amp; Co. &trade;");
552        let decoded = from_entities_html4(encoded)?;
553        assert_eq!(decoded, input);
554        Ok(())
555    }
556
557    #[crate::ctb_test]
558    fn test_html5_entities_multi_codepoint_and_semicolonless() -> Result<()> {
559        // Multi-codepoint entity decoding
560        let decoded = from_entities_html5("&ncongdot;".to_string())?;
561        assert_eq!(decoded, "\u{2A6D}\u{338}");
562
563        // Semicolon-less legacy entity in HTML5
564        let decoded_legacy = from_entities_html5("&copy 2026".to_string())?;
565        assert_eq!(decoded_legacy, "© 2026");
566
567        // Non-legacy entity with semicolon only should NOT decode without semicolon
568        let not_decoded = from_entities_html5("&NewLine text".to_string())?;
569        assert_eq!(not_decoded, "&NewLine text");
570
571        // With semicolon it does decode
572        let decoded_nl = from_entities_html5("&NewLine;text".to_string())?;
573        assert_eq!(decoded_nl, "\ntext");
574
575        Ok(())
576    }
577
578    #[crate::ctb_test]
579    fn test_mathml_entities() -> Result<()> {
580        let decoded = from_entities_mathml("&ncongdot;".to_string())?;
581        assert_eq!(decoded, "\u{2A6D}\u{338}");
582
583        let decoded_amp = from_entities_mathml("&amp;&AMP;".to_string())?;
584        assert_eq!(decoded_amp, "&&");
585        Ok(())
586    }
587}