Skip to main content

egui_pop_model/links/
inline.rs

1//! The inline subset for short texts (ADR 0017): tips, toasts and
2//! settings descriptions may carry emphasis, code and links without a
3//! markdown renderer. A text is cut into [`Run`]s, each drawn as it says;
4//! nothing else of markdown is read (no headings, lists, images or
5//! HTML: they stay as they are written).
6//!
7//! | Written | Drawn |
8//! |---|---|
9//! | `*text*`, `_text_` | emphasis |
10//! | `**text**`, `__text__` | strong |
11//! | `` `code` `` | code |
12//! | `[label](target)` | a link showing `label` |
13//! | `<https://…>`, a bare `https://…` | a link showing its address |
14//! | `\*` | a literal `*` (any ASCII punctuation) |
15//!
16//! A delimiter opens only when a closing one follows (`2 * 3` stays as
17//! it is), `_` never inside a word (`snake_case_name` stays as it is),
18//! and a code span's text is taken verbatim.
19//!
20//! ```
21//! use egui_pop_model::links::inline::{runs, Run};
22//!
23//! let r = runs("Press `Ctrl+K`, see [the guide](docs:guide).");
24//! assert_eq!(r[1], Run { text: "Ctrl+K".into(), code: true, ..Run::default() });
25//! assert_eq!(r[3].link.as_deref(), Some("docs:guide"));
26//! assert_eq!(runs("snake_case_name").len(), 1);
27//! ```
28
29/// A piece of a short text, drawn one way.
30#[derive(Clone, Debug, Default, PartialEq, Eq)]
31pub struct Run {
32    pub text: String,
33    pub strong: bool,
34    pub emphasis: bool,
35    pub code: bool,
36    /// A link's target: the run is its label.
37    pub link: Option<String>,
38}
39
40/// Whether a text uses the subset at all: one without it is drawn as a
41/// plain label.
42pub fn has_markup(text: &str) -> bool {
43    text.contains(['*', '_', '`', '[', '<', '\\'])
44        || text.contains("https://")
45        || text.contains("http://")
46}
47
48/// The runs of a short text, in order; neighbours drawn the same way are
49/// merged.
50pub fn runs(text: &str) -> Vec<Run> {
51    let mut out = Vec::new();
52    parse(text, false, false, &mut out);
53    merge(out)
54}
55
56/// The text without its markup (a link's label, a code span's text), for
57/// a screen reader or a search.
58pub fn plain(text: &str) -> String {
59    runs(text).into_iter().map(|r| r.text).collect()
60}
61
62fn merge(runs: Vec<Run>) -> Vec<Run> {
63    let mut out: Vec<Run> = Vec::with_capacity(runs.len());
64    for r in runs {
65        if r.text.is_empty() {
66            continue;
67        }
68        match out.last_mut() {
69            Some(last)
70                if last.link.is_none()
71                    && r.link.is_none()
72                    && (last.strong, last.emphasis, last.code)
73                        == (r.strong, r.emphasis, r.code) =>
74            {
75                last.text.push_str(&r.text);
76            }
77            _ => out.push(r),
78        }
79    }
80    out
81}
82
83struct Builder<'a> {
84    out: &'a mut Vec<Run>,
85    buf: String,
86    strong: bool,
87    emphasis: bool,
88}
89
90impl Builder<'_> {
91    fn flush(&mut self) {
92        if !self.buf.is_empty() {
93            self.out.push(Run {
94                text: std::mem::take(&mut self.buf),
95                strong: self.strong,
96                emphasis: self.emphasis,
97                ..Run::default()
98            });
99        }
100    }
101
102    fn push(&mut self, run: Run) {
103        self.flush();
104        self.out.push(run);
105    }
106}
107
108fn parse(text: &str, strong: bool, emphasis: bool, out: &mut Vec<Run>) {
109    let mut b = Builder {
110        out,
111        buf: String::new(),
112        strong,
113        emphasis,
114    };
115    let bytes = text.as_bytes();
116    let mut i = 0;
117    while i < text.len() {
118        let rest = &text[i..];
119        let c = rest.chars().next().unwrap_or_default();
120        match c {
121            '\\' => {
122                let next = rest[1..].chars().next();
123                match next {
124                    Some(n) if n.is_ascii_punctuation() => {
125                        b.buf.push(n);
126                        i += 2;
127                    }
128                    _ => {
129                        b.buf.push('\\');
130                        i += 1;
131                    }
132                }
133                continue;
134            }
135            '`' => {
136                if let Some(end) = rest[1..].find('`') {
137                    let code = &rest[1..1 + end];
138                    if !code.is_empty() {
139                        b.push(Run {
140                            text: code.to_string(),
141                            code: true,
142                            ..Run::default()
143                        });
144                        i += end + 2;
145                        continue;
146                    }
147                }
148            }
149            '[' => {
150                if let Some((label, target, used)) = markdown_link(rest) {
151                    b.push(Run {
152                        text: label.to_string(),
153                        strong,
154                        emphasis,
155                        link: Some(target.to_string()),
156                        ..Run::default()
157                    });
158                    i += used;
159                    continue;
160                }
161            }
162            '<' => {
163                if let Some(end) = rest.find('>') {
164                    let inner = &rest[1..end];
165                    if is_autolink(inner) {
166                        b.push(Run {
167                            text: inner.to_string(),
168                            strong,
169                            emphasis,
170                            link: Some(inner.to_string()),
171                            ..Run::default()
172                        });
173                        i += end + 1;
174                        continue;
175                    }
176                }
177            }
178            'h' | 'H' => {
179                let before = text[..i].chars().next_back();
180                if before.is_none_or(|p| !p.is_alphanumeric())
181                    && let Some(len) = bare_url(rest)
182                {
183                    let url = &rest[..len];
184                    b.push(Run {
185                        text: url.to_string(),
186                        strong,
187                        emphasis,
188                        link: Some(url.to_string()),
189                        ..Run::default()
190                    });
191                    i += len;
192                    continue;
193                }
194            }
195            '*' | '_' => {
196                let double = bytes.get(i + 1) == Some(&(c as u8));
197                let width = if double { 2 } else { 1 };
198                let before = text[..i].chars().next_back();
199                if opens(c, before, &rest[width..])
200                    && let Some(close) = closing(&rest[width..], c, double)
201                {
202                    let inner = &rest[width..width + close];
203                    b.flush();
204                    if double {
205                        parse(inner, true, b.emphasis, b.out);
206                    } else {
207                        parse(inner, b.strong, true, b.out);
208                    }
209                    i += width + close + width;
210                    continue;
211                }
212                // Not emphasis: the delimiters as written.
213                b.buf.push_str(&rest[..width]);
214                i += width;
215                continue;
216            }
217            _ => {}
218        }
219        b.buf.push(c);
220        i += c.len_utf8();
221    }
222    b.flush();
223}
224
225/// A delimiter opens when text follows it at once, and `_` only at the
226/// start of a word.
227fn opens(c: char, before: Option<char>, after: &str) -> bool {
228    let next = after.chars().next();
229    if next.is_none_or(char::is_whitespace) {
230        return false;
231    }
232    !(c == '_' && before.is_some_and(char::is_alphanumeric))
233}
234
235/// Where the closing delimiter starts in `rest`: preceded by text, and
236/// for `_` not followed by a letter or digit; a single one is not part
237/// of a double.
238fn closing(rest: &str, c: char, double: bool) -> Option<usize> {
239    let bytes = rest.as_bytes();
240    let d = c as u8;
241    let mut i = 0;
242    while i < bytes.len() {
243        if bytes[i] == b'\\' {
244            i += 2;
245            continue;
246        }
247        if bytes[i] == b'`'
248            && let Some(end) = rest[i + 1..].find('`')
249        {
250            i += end + 2;
251            continue;
252        }
253        if bytes[i] == d && i > 0 {
254            let run = bytes[i..].iter().take_while(|b| **b == d).count();
255            let fits = if double { run >= 2 } else { run == 1 };
256            let before = rest[..i].chars().next_back();
257            let after = rest[i + if double { 2 } else { 1 }..].chars().next();
258            if fits
259                && before.is_some_and(|p| !p.is_whitespace())
260                && !(c == '_' && after.is_some_and(char::is_alphanumeric))
261            {
262                return Some(i);
263            }
264            i += run;
265            continue;
266        }
267        i += 1;
268    }
269    None
270}
271
272/// `[label](target)` at the start of `text`: the label, the target and
273/// the bytes used.
274fn markdown_link(text: &str) -> Option<(&str, &str, usize)> {
275    let close = text.find("](")?;
276    let label = &text[1..close];
277    if label.is_empty() || label.contains(['[', ']', '\n']) {
278        return None;
279    }
280    let after = &text[close + 2..];
281    let end = after.find(')')?;
282    let target = after[..end].trim().trim_matches(['<', '>']);
283    if target.is_empty() || target.contains(char::is_whitespace) {
284        return None;
285    }
286    Some((label, target, close + 2 + end + 1))
287}
288
289fn is_autolink(inner: &str) -> bool {
290    let Some((scheme, rest)) = inner.split_once(':') else {
291        return false;
292    };
293    !rest.is_empty()
294        && !inner.contains(char::is_whitespace)
295        && scheme.len() >= 2
296        && scheme
297            .chars()
298            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
299}
300
301/// The length of a bare `http(s)://` address at the start of `text`,
302/// without the punctuation that ends a sentence.
303fn bare_url(text: &str) -> Option<usize> {
304    let lower = text.get(..8).unwrap_or(text).to_ascii_lowercase();
305    if !(lower.starts_with("https://") || lower.starts_with("http://")) {
306        return None;
307    }
308    let end = text.find(char::is_whitespace).unwrap_or(text.len());
309    let url = text[..end].trim_end_matches(['.', ',', ';', ':', '!', '?', ')', '"', '\'', '>']);
310    (url.len() > "http://".len()).then_some(url.len())
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    fn r(text: &str) -> Run {
318        Run {
319            text: text.into(),
320            ..Run::default()
321        }
322    }
323
324    #[test]
325    fn emphasis_strong_and_code() {
326        assert_eq!(
327            runs("a *b* **c** `d*e`"),
328            vec![
329                r("a "),
330                Run {
331                    emphasis: true,
332                    ..r("b")
333                },
334                r(" "),
335                Run {
336                    strong: true,
337                    ..r("c")
338                },
339                r(" "),
340                Run {
341                    code: true,
342                    ..r("d*e")
343                },
344            ]
345        );
346        assert_eq!(
347            runs("**bold _and_ more**")[1],
348            Run {
349                strong: true,
350                emphasis: true,
351                ..r("and")
352            }
353        );
354    }
355
356    #[test]
357    fn delimiters_without_a_pair_or_inside_words_stay() {
358        assert_eq!(runs("2 * 3 = 6"), vec![r("2 * 3 = 6")]);
359        assert_eq!(runs("snake_case_name"), vec![r("snake_case_name")]);
360        assert_eq!(runs("a ** b"), vec![r("a ** b")]);
361        assert_eq!(runs(r"\*not\*"), vec![r("*not*")]);
362        assert_eq!(runs("an `unclosed code"), vec![r("an `unclosed code")]);
363    }
364
365    #[test]
366    fn links_of_every_form() {
367        let found =
368            runs("See [the guide](docs:guide), <mailto:a@b.example> or https://example.org/x.");
369        let links: Vec<(&str, &str)> = found
370            .iter()
371            .filter_map(|r| Some((r.text.as_str(), r.link.as_deref()?)))
372            .collect();
373        assert_eq!(
374            links,
375            [
376                ("the guide", "docs:guide"),
377                ("mailto:a@b.example", "mailto:a@b.example"),
378                ("https://example.org/x", "https://example.org/x"),
379            ]
380        );
381        assert_eq!(found.last().unwrap(), &r("."));
382        assert_eq!(plain("See [the guide](docs:guide)."), "See the guide.");
383        assert!(!has_markup("Plain words."));
384    }
385}