Skip to main content

ultrafast_geom/
markup.rs

1//! Inline styling inside a `text` param:
2//!
3//! - `*word*`: the emphasis style, set by the node's `em_*` params.
4//! - `[words]{color=#ffd23f weight=800 font="Instrument Serif"}`: a span
5//!   with its own attributes (color, font, weight, style, size, highlight,
6//!   underline, rise).
7//! - `\*`, `\[` and `\\` set the characters themselves. A `*` without a
8//!   partner, or brackets without `{...}` after them, stay literal.
9
10use std::collections::BTreeMap;
11
12#[derive(Debug, Clone, PartialEq)]
13pub enum Style {
14    Em,
15    Attrs(BTreeMap<String, String>),
16}
17
18/// A styled byte range of the plain text.
19#[derive(Debug, Clone, PartialEq)]
20pub struct Span {
21    pub start: usize,
22    pub end: usize,
23    pub style: Style,
24}
25
26/// Whether `s` has anything markup would change.
27pub fn has_markup(s: &str) -> bool {
28    s.contains('*') || s.contains('[') || s.contains('\\')
29}
30
31fn attrs(s: &str) -> BTreeMap<String, String> {
32    let mut out = BTreeMap::new();
33    let c: Vec<char> = s.chars().collect();
34    let mut i = 0;
35    while i < c.len() {
36        while i < c.len() && (c[i].is_whitespace() || c[i] == ',' || c[i] == ';') {
37            i += 1;
38        }
39        let k0 = i;
40        while i < c.len() && c[i] != '=' && !c[i].is_whitespace() {
41            i += 1;
42        }
43        let key: String = c[k0..i].iter().collect();
44        if key.is_empty() {
45            break;
46        }
47        if i >= c.len() || c[i] != '=' {
48            out.insert(key, "true".into());
49            continue;
50        }
51        i += 1;
52        let val: String = if i < c.len() && (c[i] == '"' || c[i] == '\'') {
53            let q = c[i];
54            i += 1;
55            let v0 = i;
56            while i < c.len() && c[i] != q {
57                i += 1;
58            }
59            let v = c[v0..i].iter().collect();
60            i += 1;
61            v
62        } else {
63            let v0 = i;
64            while i < c.len() && !c[i].is_whitespace() && c[i] != ',' && c[i] != ';' {
65                i += 1;
66            }
67            c[v0..i].iter().collect()
68        };
69        out.insert(key.trim().to_string(), val);
70    }
71    out
72}
73
74/// Index of the first `ch` at or after `from` that is not escaped.
75fn unescaped(b: &[u8], from: usize, ch: u8) -> Option<usize> {
76    let mut j = from;
77    while j < b.len() {
78        match b[j] {
79            b'\\' => j += 2,
80            c if c == ch => return Some(j),
81            _ => j += 1,
82        }
83    }
84    None
85}
86
87/// Escapes `s` so markup sets it literally.
88pub fn escape(s: &str) -> String {
89    let mut out = String::with_capacity(s.len());
90    for c in s.chars() {
91        if matches!(c, '*' | '[' | ']' | '\\' | '{') {
92            out.push('\\');
93        }
94        out.push(c);
95    }
96    out
97}
98
99/// The plain text and its styled spans.
100pub fn parse(s: &str) -> (String, Vec<Span>) {
101    let mut plain = String::with_capacity(s.len());
102    let mut spans = Vec::new();
103    let b = s.as_bytes();
104    let mut em_open: Option<usize> = None;
105    let mut i = 0;
106    // Whether a later unescaped `*` closes one opened here.
107    let closes = |from: usize| -> bool {
108        let mut j = from;
109        while j < b.len() {
110            match b[j] {
111                b'\\' => j += 2,
112                b'*' => return true,
113                b'\n' => return false,
114                _ => j += 1,
115            }
116        }
117        false
118    };
119    while i < b.len() {
120        match b[i] {
121            b'\\' if i + 1 < b.len() && matches!(b[i + 1], b'*' | b'[' | b']' | b'\\' | b'{') => {
122                plain.push(b[i + 1] as char);
123                i += 2;
124            }
125            b'*' => {
126                match em_open.take() {
127                    Some(start) => {
128                        if plain.len() > start {
129                            spans.push(Span {
130                                start,
131                                end: plain.len(),
132                                style: Style::Em,
133                            })
134                        }
135                    }
136                    None if closes(i + 1) => em_open = Some(plain.len()),
137                    None => plain.push('*'),
138                }
139                i += 1;
140            }
141            b'[' => {
142                // `[text]{attrs}`: find the closing bracket (escapes
143                // skipped), then braces.
144                let close = unescaped(b, i + 1, b']');
145                let brace = close.filter(|&c| b.get(c + 1) == Some(&b'{'));
146                let end = brace.and_then(|c| s[c + 2..].find('}').map(|k| c + 2 + k));
147                match (close, end) {
148                    (Some(c), Some(e)) if !s[i + 1..c].contains('\n') => {
149                        let (inner, inner_spans) = parse(&s[i + 1..c]);
150                        let start = plain.len();
151                        for sp in inner_spans {
152                            spans.push(Span {
153                                start: sp.start + start,
154                                end: sp.end + start,
155                                style: sp.style,
156                            });
157                        }
158                        plain.push_str(&inner);
159                        spans.push(Span {
160                            start,
161                            end: plain.len(),
162                            style: Style::Attrs(attrs(&s[c + 2..e])),
163                        });
164                        i = e + 1;
165                    }
166                    _ => {
167                        plain.push('[');
168                        i += 1;
169                    }
170                }
171            }
172            _ => {
173                let ch = s[i..].chars().next().unwrap();
174                plain.push(ch);
175                i += ch.len_utf8();
176            }
177        }
178    }
179    (plain, spans)
180}
181
182/// The text a reader sees: markup removed.
183pub fn plain(s: &str) -> String {
184    if has_markup(s) { parse(s).0 } else { s.to_string() }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn emphasis_and_attribute_spans() {
193        let (p, s) = parse("Make it *live* now");
194        assert_eq!(p, "Make it live now");
195        assert_eq!(
196            s,
197            vec![Span {
198                start: 8,
199                end: 12,
200                style: Style::Em
201            }]
202        );
203        let (p, s) = parse(r#"A [big idea]{color=#ff0 font="Instrument Serif" weight=800}."#);
204        assert_eq!(p, "A big idea.");
205        assert_eq!((s[0].start, s[0].end), (2, 10));
206        let Style::Attrs(a) = &s[0].style else { panic!() };
207        assert_eq!(a["color"], "#ff0");
208        assert_eq!(a["font"], "Instrument Serif");
209        assert_eq!(a["weight"], "800");
210    }
211
212    #[test]
213    fn literals_stay() {
214        assert_eq!(parse("5 * 3").0, "5 * 3");
215        assert_eq!(parse("a [b] c").0, "a [b] c");
216        assert_eq!(parse(r"\*not em\*").0, "*not em*");
217        assert_eq!(parse("**").0, "");
218        assert!(parse("*a*\n*b").1.len() == 1);
219        assert_eq!(parse("*a*\n*b").0, "a\n*b");
220    }
221
222    #[test]
223    fn escaped_brackets_inside_spans() {
224        let src = format!("[{}]{{color=#f00}}x", escape("a[0]*b\\"));
225        let (p, s) = parse(&src);
226        assert_eq!(p, "a[0]*b\\x");
227        assert_eq!((s[0].start, s[0].end), (0, 7));
228    }
229
230    #[test]
231    fn nested_emphasis_inside_a_span() {
232        let (p, s) = parse("[x *y* z]{underline=3}");
233        assert_eq!(p, "x y z");
234        assert_eq!(s.len(), 2);
235        assert_eq!((s[0].start, s[0].end, &s[0].style), (2, 3, &Style::Em));
236    }
237}