Skip to main content

gitpoulpi_hosting/markup/
mod.rs

1//! Markup conversion for issue and pull-request text (plan `conversations`).
2//!
3//! Hosts speak different markup: Jira wiki, Textile (Redmine), HTML (Azure
4//! DevOps Server, some trackers) and flavours of Markdown. Everything the
5//! app displays is normalised to Markdown first, and text the user writes is
6//! converted back for hosts that do not take Markdown. All of it is pure and
7//! lives here so the TUI, the CLI and MCP agree.
8//!
9//! Every importer starts with [`sanitize`]: no escape sequence or control
10//! character reaches a renderer.
11//!
12//! The converters are deliberately forgiving rather than complete: what they
13//! do not understand stays as readable text.
14
15mod html_lite;
16mod jira_wiki;
17mod sanitize;
18mod textile;
19
20pub use html_lite::{html_to_markdown, markdown_to_html};
21pub use jira_wiki::{jira_to_markdown, markdown_to_jira};
22pub use sanitize::sanitize;
23pub use textile::textile_to_markdown;
24
25fn is_word(c: char) -> bool {
26    c.is_alphanumeric() || c == '_'
27}
28
29/// Rewrites `marker text marker` pairs (`*bold*`) to `open text close`.
30///
31/// An opener sits at the start or after a non-word character and is followed
32/// by a non-blank; a closer follows a non-blank and is followed by a non-word
33/// character. Pairs never span a newline, so `2 * 3 * 4` and `a-b-c` stay.
34pub(crate) fn wrap_pairs(text: &str, marker: char, open: &str, close: &str) -> String {
35    let chars: Vec<char> = text.chars().collect();
36    let mut out = String::with_capacity(text.len() + 8);
37    let mut i = 0;
38    while i < chars.len() {
39        if chars[i] == marker && opens_at(&chars, i, marker) {
40            if let Some(j) = closer_for(&chars, i, marker) {
41                out.push_str(open);
42                out.extend(&chars[i + 1..j]);
43                out.push_str(close);
44                i = j + 1;
45                continue;
46            }
47        }
48        out.push(chars[i]);
49        i += 1;
50    }
51    out
52}
53
54fn opens_at(chars: &[char], i: usize, marker: char) -> bool {
55    let prev_ok = i == 0 || !is_word(chars[i - 1]) && chars[i - 1] != marker;
56    let next_ok = chars
57        .get(i + 1)
58        .is_some_and(|n| !n.is_whitespace() && *n != marker);
59    prev_ok && next_ok
60}
61
62fn closer_for(chars: &[char], i: usize, marker: char) -> Option<usize> {
63    let mut j = i + 1;
64    while j < chars.len() {
65        let c = chars[j];
66        if c == '\n' {
67            return None;
68        }
69        if c == marker
70            && j > i + 1
71            && !chars[j - 1].is_whitespace()
72            && chars[j - 1] != marker
73            && chars
74                .get(j + 1)
75                .is_none_or(|n| !is_word(*n) && *n != marker)
76        {
77            return Some(j);
78        }
79        j += 1;
80    }
81    None
82}
83
84/// Splits `text` at spans delimited by `start` and `end` (code spans), as
85/// `(is_code, piece)`; the delimiters are not part of the pieces. An
86/// unterminated opener is plain text.
87pub(crate) fn split_spans<'a>(text: &'a str, start: &str, end: &str) -> Vec<(bool, &'a str)> {
88    let mut out = Vec::new();
89    let mut rest = text;
90    while let Some(a) = rest.find(start) {
91        let after = &rest[a + start.len()..];
92        match after.find(end) {
93            Some(b) if b > 0 && !after[..b].contains('\n') => {
94                if a > 0 {
95                    out.push((false, &rest[..a]));
96                }
97                out.push((true, &after[..b]));
98                rest = &after[b + end.len()..];
99            }
100            _ => {
101                out.push((false, &rest[..a + start.len()]));
102                rest = after;
103            }
104        }
105    }
106    if !rest.is_empty() {
107        out.push((false, rest));
108    }
109    out
110}
111
112/// What a produced Markdown line is, to decide where blank lines go.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub(crate) enum Block {
115    Para,
116    List,
117    Heading,
118    Quote,
119    Table,
120    Code,
121    Rule,
122}
123
124/// Collects lines and puts one blank line between blocks of different kinds.
125#[derive(Default)]
126pub(crate) struct Lines {
127    lines: Vec<String>,
128    last: Option<Block>,
129}
130
131impl Lines {
132    pub(crate) fn push(&mut self, kind: Block, line: String) {
133        if let Some(last) = self.last {
134            let same_run = last == kind
135                && matches!(
136                    kind,
137                    Block::List | Block::Table | Block::Quote | Block::Para | Block::Code
138                );
139            if !same_run && !self.lines.last().is_some_and(String::is_empty) {
140                self.lines.push(String::new());
141            }
142        }
143        self.lines.push(line);
144        self.last = Some(kind);
145    }
146
147    pub(crate) fn blank(&mut self) {
148        if !self.lines.last().is_some_and(String::is_empty) && !self.lines.is_empty() {
149            self.lines.push(String::new());
150        }
151        self.last = None;
152    }
153
154    pub(crate) fn finish(self) -> String {
155        let mut s = self.lines.join("\n");
156        while s.ends_with('\n') {
157            s.pop();
158        }
159        s
160    }
161}
162
163/// Decodes the handful of HTML entities that show up in issue text.
164pub(crate) fn decode_entities(s: &str) -> String {
165    let mut out = String::with_capacity(s.len());
166    let mut rest = s;
167    while let Some(a) = rest.find('&') {
168        out.push_str(&rest[..a]);
169        let tail = &rest[a..];
170        let Some(semi) = tail.find(';').filter(|s| *s <= 10) else {
171            out.push('&');
172            rest = &tail[1..];
173            continue;
174        };
175        let name = &tail[1..semi];
176        let decoded = match name {
177            "amp" => Some('&'),
178            "lt" => Some('<'),
179            "gt" => Some('>'),
180            "quot" => Some('"'),
181            "apos" | "#39" => Some('\''),
182            "nbsp" => Some(' '),
183            _ => name
184                .strip_prefix('#')
185                .and_then(|n| {
186                    n.strip_prefix(['x', 'X'])
187                        .map(|h| u32::from_str_radix(h, 16))
188                        .unwrap_or_else(|| n.parse())
189                        .ok()
190                })
191                .and_then(char::from_u32),
192        };
193        match decoded {
194            Some(c) => {
195                out.push(c);
196                rest = &tail[semi + 1..];
197            }
198            None => {
199                out.push('&');
200                rest = &tail[1..];
201            }
202        }
203    }
204    out.push_str(rest);
205    out
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[test]
213    fn wrap_pairs_table() {
214        let cases: &[(&str, char, &str, &str)] = &[
215            ("a *b* c", '*', "a **b** c", ""),
216            ("*b*", '*', "**b**", ""),
217            ("2 * 3 * 4", '*', "2 * 3 * 4", ""),
218            ("a-b-c", '-', "a-b-c", ""),
219            ("x -gone- y", '-', "x ~~gone~~ y", ""),
220            ("*open\nclose*", '*', "*open\nclose*", ""),
221            ("snake*case*x", '*', "snake*case*x", ""),
222        ];
223        for (input, marker, want, _) in cases {
224            let (open, close) = if *marker == '*' {
225                ("**", "**")
226            } else {
227                ("~~", "~~")
228            };
229            assert_eq!(wrap_pairs(input, *marker, open, close), *want, "{input:?}");
230        }
231    }
232
233    #[test]
234    fn entities() {
235        assert_eq!(
236            decode_entities("a &amp; b &lt;c&gt; &#65;&#x42; &bogus; &"),
237            "a & b <c> AB &bogus; &"
238        );
239    }
240}