Skip to main content

docling_core/
fallback.rs

1//! docling-core's `FormattingFallbackMode` (docling-core#661, #1205): how the
2//! Markdown export renders the formatting Markdown has no syntax for —
3//! underline, subscript and superscript. `none` (the default) drops it, as
4//! every docling Markdown has; `html` writes `<u>…</u>`, `<sub>…</sub>` and
5//! `<sup>…</sup>` (`MarkdownParams.formatting_fallback_mode=HTML`), in
6//! docling-core's decoration order — bold, italic, underline, strikethrough,
7//! sub/superscript, then the link.
8//!
9//! The flat nodes carry Markdown the backends rendered at conversion time,
10//! by when a run's underline or script is gone. So the fallback is decided
11//! there too: while a conversion runs [`with_fallback`] (the converter's
12//! `markdown_formatting_fallback(Html)`), a backend's run renderer wraps
13//! such a run in invisible marks — Unicode noncharacters, which no
14//! interchanged text holds — through [`underline`] and [`script`]. The
15//! Markdown export turns the marks into the tags ([`render`]); every other
16//! export strips them ([`strip`]): DocLang, LaTeX, the chunks and the plain
17//! text read the same node text, and keep their own rendering of the runs
18//! (or none). Without the fallback no mark is ever written, so the default
19//! output is untouched.
20
21use std::borrow::Cow;
22use std::cell::Cell;
23
24use crate::Script;
25
26/// docling-core's `FormattingFallbackMode`.
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
28pub enum FormattingFallback {
29    /// Underline and sub/superscript print as plain text (docling's default).
30    #[default]
31    None,
32    /// `<u>`, `<sub>`, `<sup>` tags.
33    Html,
34}
35
36impl FormattingFallback {
37    /// The wire value: `none` | `html`.
38    pub fn as_str(self) -> &'static str {
39        match self {
40            FormattingFallback::None => "none",
41            FormattingFallback::Html => "html",
42        }
43    }
44}
45
46impl std::fmt::Display for FormattingFallback {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.write_str(self.as_str())
49    }
50}
51
52impl std::str::FromStr for FormattingFallback {
53    type Err = String;
54
55    fn from_str(s: &str) -> Result<Self, Self::Err> {
56        match s.trim().to_ascii_lowercase().as_str() {
57            "none" => Ok(FormattingFallback::None),
58            "html" => Ok(FormattingFallback::Html),
59            other => Err(format!(
60                "unknown formatting fallback {other:?} (expected none | html)"
61            )),
62        }
63    }
64}
65
66/// The marks, open and close per tag: noncharacters U+FDD0–U+FDD5.
67const MARKS: [(char, &str); 6] = [
68    ('\u{FDD0}', "<u>"),
69    ('\u{FDD1}', "</u>"),
70    ('\u{FDD2}', "<sub>"),
71    ('\u{FDD3}', "</sub>"),
72    ('\u{FDD4}', "<sup>"),
73    ('\u{FDD5}', "</sup>"),
74];
75
76fn is_mark(c: char) -> bool {
77    ('\u{FDD0}'..='\u{FDD5}').contains(&c)
78}
79
80thread_local! {
81    static ACTIVE: Cell<bool> = const { Cell::new(false) };
82}
83
84/// A mark was ever written in this process ([`any_marks`]).
85static EVER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
86
87/// Run `f` — a backend's conversion — with the HTML fallback on (`on`) or
88/// off; the previous state is restored afterwards, also on a panic.
89pub fn with_fallback<R>(on: bool, f: impl FnOnce() -> R) -> R {
90    struct Restore(bool);
91    impl Drop for Restore {
92        fn drop(&mut self) {
93            ACTIVE.with(|a| a.set(self.0));
94        }
95    }
96    let _restore = Restore(ACTIVE.with(|a| a.replace(on)));
97    f()
98}
99
100/// Whether the current conversion writes the marks.
101pub fn active() -> bool {
102    ACTIVE.with(Cell::get)
103}
104
105fn wrap(text: String, open: char, close: char) -> String {
106    if text.is_empty() {
107        return text;
108    }
109    EVER.store(true, std::sync::atomic::Ordering::Relaxed);
110    let mut s = String::with_capacity(text.len() + 6);
111    s.push(open);
112    s.push_str(&text);
113    s.push(close);
114    s
115}
116
117/// An underlined run's Markdown `text` — wrapped for `<u>` under the
118/// fallback, unchanged otherwise. Call it where docling-core's
119/// `serialize_underline` sits: after italic, before strikethrough.
120pub fn underline(text: String, on: bool) -> String {
121    if on && active() {
122        wrap(text, '\u{FDD0}', '\u{FDD1}')
123    } else {
124        text
125    }
126}
127
128/// A run's Markdown `text` with its script — wrapped for `<sub>` / `<sup>`
129/// under the fallback, unchanged otherwise. Call it after strikethrough,
130/// before the link (docling-core's `serialize_subscript` / `_superscript`).
131pub fn script(text: String, script: Script) -> String {
132    if !active() {
133        return text;
134    }
135    match script {
136        Script::Sub => wrap(text, '\u{FDD2}', '\u{FDD3}'),
137        Script::Super => wrap(text, '\u{FDD4}', '\u{FDD5}'),
138        Script::Baseline => text,
139    }
140}
141
142/// The Markdown export's view of node text: the marks as tags under
143/// [`FormattingFallback::Html`], dropped otherwise.
144pub fn render(text: &str, mode: FormattingFallback) -> Cow<'_, str> {
145    if !text.contains(is_mark) {
146        return Cow::Borrowed(text);
147    }
148    match mode {
149        FormattingFallback::None => strip(text),
150        FormattingFallback::Html => {
151            let mut s = String::with_capacity(text.len() + 16);
152            for c in text.chars() {
153                match MARKS.iter().find(|(m, _)| *m == c) {
154                    Some((_, tag)) => s.push_str(tag),
155                    None => s.push(c),
156                }
157            }
158            Cow::Owned(s)
159        }
160    }
161}
162
163/// `text` without the marks — every export but Markdown.
164pub fn strip(text: &str) -> Cow<'_, str> {
165    if text.contains(is_mark) {
166        Cow::Owned(text.chars().filter(|&c| !is_mark(c)).collect())
167    } else {
168        Cow::Borrowed(text)
169    }
170}
171
172/// [`strip`] on an owned string, without a copy when there is nothing to do.
173pub fn strip_owned(text: String) -> String {
174    match strip(&text) {
175        Cow::Borrowed(_) => text,
176        Cow::Owned(s) => s,
177    }
178}
179
180/// Whether any mark was ever written in this process: until then no node
181/// holds one, and the exports skip the strip entirely.
182pub(crate) fn any_marks() -> bool {
183    EVER.load(std::sync::atomic::Ordering::Relaxed)
184}
185
186/// A writer passing everything on but the marks — the JSON writers' strip,
187/// streaming: a mark is the UTF-8 sequence `EF B7 90`–`95`, held back
188/// across a write boundary until it is complete.
189pub(crate) struct MarkFilter<W> {
190    inner: W,
191    pending: Vec<u8>,
192}
193
194impl<W: std::io::Write> MarkFilter<W> {
195    pub(crate) fn new(inner: W) -> Self {
196        MarkFilter {
197            inner,
198            pending: Vec::new(),
199        }
200    }
201}
202
203impl<W: std::io::Write> std::io::Write for MarkFilter<W> {
204    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
205        let mut data = std::mem::take(&mut self.pending);
206        data.extend_from_slice(buf);
207        let mut out = Vec::with_capacity(data.len());
208        let mut i = 0;
209        while i < data.len() {
210            if data[i] == 0xEF {
211                // An incomplete sequence at the end waits for the next write.
212                if data.len() - i < 3 {
213                    self.pending = data[i..].to_vec();
214                    break;
215                }
216                if data[i + 1] == 0xB7 && (0x90..=0x95).contains(&data[i + 2]) {
217                    i += 3;
218                    continue;
219                }
220            }
221            out.push(data[i]);
222            i += 1;
223        }
224        self.inner.write_all(&out)?;
225        Ok(buf.len())
226    }
227
228    fn flush(&mut self) -> std::io::Result<()> {
229        if !self.pending.is_empty() {
230            let rest = std::mem::take(&mut self.pending);
231            self.inner.write_all(&rest)?;
232        }
233        self.inner.flush()
234    }
235}
236
237/// [`strip`] over every string of a JSON value.
238pub fn strip_value(v: &mut serde_json::Value) {
239    match v {
240        serde_json::Value::String(s) => {
241            if s.contains(is_mark) {
242                *s = strip(s).into_owned();
243            }
244        }
245        serde_json::Value::Array(a) => a.iter_mut().for_each(strip_value),
246        serde_json::Value::Object(o) => o.values_mut().for_each(strip_value),
247        _ => {}
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn marks_only_under_the_fallback() {
257        assert_eq!(underline("x".into(), true), "x");
258        assert_eq!(script("2".into(), Script::Sub), "2");
259        with_fallback(true, || {
260            let u = underline("&lt;tag&gt;".into(), true);
261            let sub = script("2".into(), Script::Sub);
262            let sup = script("2".into(), Script::Super);
263            let text = format!("H{sub}O, mc{sup}, {u}");
264            assert_eq!(
265                render(&text, FormattingFallback::Html),
266                "H<sub>2</sub>O, mc<sup>2</sup>, <u>&lt;tag&gt;</u>"
267            );
268            assert_eq!(
269                render(&text, FormattingFallback::None),
270                "H2O, mc2, &lt;tag&gt;"
271            );
272            assert_eq!(strip(&text), "H2O, mc2, &lt;tag&gt;");
273            // Not underlined: unchanged even under the fallback.
274            assert_eq!(underline("x".into(), false), "x");
275        });
276        assert!(!active());
277    }
278
279    #[test]
280    fn parses_the_wire_values() {
281        assert_eq!("HTML".parse(), Ok(FormattingFallback::Html));
282        assert_eq!("none".parse(), Ok(FormattingFallback::None));
283        assert!("tags".parse::<FormattingFallback>().is_err());
284    }
285}