Skip to main content

dot/tui/
markdown.rs

1use std::sync::LazyLock;
2
3use ratatui::style::{Color, Modifier, Style};
4use ratatui::text::{Line, Span};
5use syntect::highlighting::ThemeSet;
6use syntect::parsing::{ParseState, Scope, ScopeStack, SyntaxSet};
7
8use crate::tui::theme::{SyntaxStyles, Theme};
9
10static SYNTAX_SET: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);
11static THEME_SET: LazyLock<ThemeSet> = LazyLock::new(ThemeSet::load_defaults);
12
13#[derive(Clone, Copy)]
14enum ScopeKind {
15    Keyword,
16    Str,
17    Comment,
18    Function,
19    Type,
20    Number,
21    Constant,
22    Attribute,
23}
24
25static SCOPE_MATCHERS: LazyLock<Vec<(Scope, ScopeKind)>> = LazyLock::new(|| {
26    use ScopeKind::*;
27    [
28        ("entity.other.attribute-name", Attribute),
29        ("entity.name.function", Function),
30        ("entity.name.type", Type),
31        ("entity.name.class", Type),
32        ("entity.name.tag", Keyword),
33        ("constant.character", Str),
34        ("constant.language", Constant),
35        ("constant.numeric", Number),
36        ("support.function", Function),
37        ("support.type", Type),
38        ("variable.language", Keyword),
39        ("meta.attribute", Attribute),
40        ("keyword", Keyword),
41        ("storage", Keyword),
42        ("comment", Comment),
43        ("string", Str),
44    ]
45    .into_iter()
46    .filter_map(|(s, kind)| Some((Scope::new(s).ok()?, kind)))
47    .collect()
48});
49
50fn resolve_scope(stack: &ScopeStack, styles: &SyntaxStyles) -> Style {
51    for scope in stack.as_slice().iter().rev() {
52        for (prefix, kind) in SCOPE_MATCHERS.iter() {
53            if prefix.is_prefix_of(*scope) {
54                return match kind {
55                    ScopeKind::Keyword => styles.keyword,
56                    ScopeKind::Str => styles.string,
57                    ScopeKind::Comment => styles.comment,
58                    ScopeKind::Function => styles.function,
59                    ScopeKind::Type => styles.type_name,
60                    ScopeKind::Number => styles.number,
61                    ScopeKind::Constant => styles.constant,
62                    ScopeKind::Attribute => styles.attribute,
63                };
64            }
65        }
66    }
67    Style::default()
68}
69
70fn word_wrap(text: &str, max_width: usize) -> Vec<String> {
71    if max_width == 0 {
72        return vec![text.to_string()];
73    }
74    let mut result: Vec<String> = Vec::new();
75    for raw in text.lines() {
76        if raw.is_empty() {
77            result.push(String::new());
78            continue;
79        }
80        let mut current = String::new();
81        let mut current_len: usize = 0;
82        for word in raw.split_whitespace() {
83            let word_len = word.chars().count();
84            if current.is_empty() {
85                current.push_str(word);
86                current_len = word_len;
87            } else if current_len + 1 + word_len <= max_width {
88                current.push(' ');
89                current.push_str(word);
90                current_len += 1 + word_len;
91            } else {
92                result.push(std::mem::take(&mut current));
93                current.push_str(word);
94                current_len = word_len;
95            }
96        }
97        if !current.is_empty() {
98            result.push(current);
99        }
100    }
101    if result.is_empty() {
102        result.push(String::new());
103    }
104    result
105}
106
107fn truncate_code_line(line: &str, max_chars: usize) -> String {
108    if line.chars().count() <= max_chars {
109        return line.to_string();
110    }
111    let truncated: String = line.chars().take(max_chars.saturating_sub(1)).collect();
112    format!("{}…", truncated)
113}
114
115pub fn render_markdown(text: &str, theme: &Theme, width: u16) -> Vec<Line<'static>> {
116    let mut lines: Vec<Line<'static>> = Vec::new();
117    let mut in_code_block = false;
118    let mut code_lang = String::new();
119    let mut code_lines: Vec<String> = Vec::new();
120    let mut just_closed_code = false;
121
122    for raw_line in text.lines() {
123        if raw_line.starts_with("```") {
124            if in_code_block {
125                render_code_block(&code_lang, &code_lines, theme, width, &mut lines);
126                code_lines.clear();
127                code_lang.clear();
128                in_code_block = false;
129                just_closed_code = true;
130            } else {
131                in_code_block = true;
132                code_lang = raw_line.trim_start_matches('`').trim().to_string();
133                if let Some(last) = lines.last()
134                    && last.spans.iter().all(|s| s.content.trim().is_empty())
135                {
136                    lines.pop();
137                }
138            }
139            continue;
140        }
141
142        if in_code_block {
143            code_lines.push(raw_line.to_string());
144            continue;
145        }
146
147        if raw_line.is_empty() {
148            if just_closed_code {
149                continue;
150            }
151            lines.push(Line::from(""));
152            continue;
153        }
154        just_closed_code = false;
155
156        if let Some(heading) = raw_line.strip_prefix("### ") {
157            lines.push(Line::from(Span::styled(
158                heading.to_string(),
159                theme
160                    .heading
161                    .patch(Style::default().add_modifier(Modifier::BOLD)),
162            )));
163        } else if let Some(heading) = raw_line.strip_prefix("## ") {
164            lines.push(Line::from(Span::styled(heading.to_string(), theme.heading)));
165        } else if let Some(heading) = raw_line.strip_prefix("# ") {
166            lines.push(Line::from(Span::styled(
167                heading.to_string(),
168                theme
169                    .heading
170                    .patch(Style::default().add_modifier(Modifier::BOLD)),
171            )));
172        } else if let Some(quote) = raw_line.strip_prefix("> ") {
173            lines.push(Line::from(vec![
174                Span::styled("  │ ", theme.border),
175                Span::styled(quote.to_string(), theme.blockquote),
176            ]));
177        } else if raw_line.starts_with("- ") || raw_line.starts_with("* ") {
178            let content = &raw_line[2..];
179            let prefix_len = 4usize;
180            let wrap_w = (width as usize).saturating_sub(prefix_len);
181            let sub_lines = word_wrap(content, wrap_w);
182            for (i, sub) in sub_lines.into_iter().enumerate() {
183                if i == 0 {
184                    let spans = parse_inline(&sub, theme);
185                    let mut full = vec![Span::styled("  \u{00b7} ", theme.list_bullet)];
186                    full.extend(spans);
187                    lines.push(Line::from(full));
188                } else {
189                    let spans = parse_inline(&sub, theme);
190                    let mut full = vec![Span::raw("    ")];
191                    full.extend(spans);
192                    lines.push(Line::from(full));
193                }
194            }
195        } else if raw_line
196            .chars()
197            .next()
198            .map(|c| c.is_ascii_digit())
199            .unwrap_or(false)
200            && raw_line.contains(". ")
201        {
202            if let Some(pos) = raw_line.find(". ") {
203                let num = &raw_line[..pos + 2];
204                let content = &raw_line[pos + 2..];
205                let prefix_len = num.chars().count() + 3;
206                let wrap_w = (width as usize).saturating_sub(prefix_len);
207                let sub_lines = word_wrap(content, wrap_w);
208                let indent = " ".repeat(prefix_len);
209                for (i, sub) in sub_lines.into_iter().enumerate() {
210                    if i == 0 {
211                        let spans = parse_inline(&sub, theme);
212                        let mut full = vec![Span::styled(format!("  {} ", num), theme.list_bullet)];
213                        full.extend(spans);
214                        lines.push(Line::from(full));
215                    } else {
216                        let spans = parse_inline(&sub, theme);
217                        let mut full = vec![Span::raw(indent.clone())];
218                        full.extend(spans);
219                        lines.push(Line::from(full));
220                    }
221                }
222            }
223        } else if raw_line.trim() == "---" || raw_line.trim() == "***" {
224            lines.push(Line::from(Span::styled(
225                "\u{2500}".repeat(width.saturating_sub(4) as usize),
226                theme.border,
227            )));
228        } else {
229            let sub_lines = word_wrap(raw_line, width as usize);
230            for sub in sub_lines {
231                let spans = parse_inline(&sub, theme);
232                lines.push(Line::from(spans));
233            }
234        }
235    }
236
237    if in_code_block {
238        render_code_block(&code_lang, &code_lines, theme, width, &mut lines);
239    }
240
241    let mut deduped: Vec<Line<'static>> = Vec::with_capacity(lines.len());
242    let mut prev_empty = false;
243    for line in lines {
244        let is_empty = line.spans.iter().all(|s| s.content.is_empty());
245        if is_empty && prev_empty {
246            continue;
247        }
248        prev_empty = is_empty;
249        deduped.push(line);
250    }
251    deduped
252}
253
254pub fn render_code_block(
255    lang: &str,
256    code_lines: &[String],
257    theme: &Theme,
258    width: u16,
259    output: &mut Vec<Line<'static>>,
260) {
261    let w = width as usize;
262
263    output.push(Line::from(""));
264
265    if !lang.is_empty() {
266        output.push(Line::from(vec![
267            Span::styled(" │ ", theme.border),
268            Span::styled(lang.to_string(), Style::default().fg(theme.muted_fg)),
269        ]));
270    }
271
272    let is_diff = lang == "diff" || lang == "patch";
273    if is_diff {
274        for raw_line in code_lines {
275            let line = &truncate_code_line(raw_line, w.saturating_sub(3));
276            let diff_style = if line.starts_with('+') {
277                theme.diff_add
278            } else if line.starts_with('-') {
279                theme.diff_remove
280            } else if line.starts_with('@') {
281                theme.diff_hunk
282            } else {
283                Style::default().fg(theme.fg)
284            };
285            output.push(Line::from(vec![
286                Span::styled(" │ ", theme.border),
287                Span::styled(line.to_string(), diff_style),
288            ]));
289        }
290        if code_lines.is_empty() {
291            output.push(Line::from(Span::styled(" │", theme.border)));
292        }
293    } else if let Some(syntect_theme_name) = theme.syntect_theme
294        && !lang.is_empty()
295        && let Some(syntax) = SYNTAX_SET.find_syntax_by_token(lang)
296        && let Some(st_theme) = THEME_SET.themes.get(syntect_theme_name)
297    {
298        let mut highlighter = syntect::easy::HighlightLines::new(syntax, st_theme);
299        for raw_line in code_lines {
300            let line: &str = &truncate_code_line(raw_line, w.saturating_sub(3));
301            let highlighted = highlighter.highlight_line(line, &SYNTAX_SET);
302            match highlighted {
303                Ok(ranges) => {
304                    let mut spans = vec![Span::styled(" │ ", theme.border)];
305                    for (style, text) in ranges {
306                        let fg = style.foreground;
307                        let clean = text.trim_end_matches('\n');
308                        if clean.is_empty() {
309                            continue;
310                        }
311                        spans.push(Span::styled(
312                            clean.to_string(),
313                            Style::default().fg(Color::Rgb(fg.r, fg.g, fg.b)),
314                        ));
315                    }
316                    output.push(Line::from(spans));
317                }
318                Err(_) => {
319                    output.push(Line::from(vec![
320                        Span::styled(" │ ", theme.border),
321                        Span::styled(line.to_string(), Style::default().fg(theme.fg)),
322                    ]));
323                }
324            }
325        }
326        if code_lines.is_empty() {
327            output.push(Line::from(Span::styled(" │", theme.border)));
328        }
329    } else if let Some(styles) = &theme.syntax
330        && !lang.is_empty()
331        && let Some(syntax) = SYNTAX_SET.find_syntax_by_token(lang)
332    {
333        let mut state = ParseState::new(syntax);
334        let mut stack = ScopeStack::new();
335        for raw_line in code_lines {
336            let line = &truncate_code_line(raw_line, w.saturating_sub(3));
337            match state.parse_line(line, &SYNTAX_SET) {
338                Ok(ops) => {
339                    let mut spans = vec![Span::styled(" │ ", theme.border)];
340                    let mut prev = 0;
341                    for (pos, op) in &ops {
342                        let pos = (*pos).min(line.len());
343                        if pos > prev {
344                            let text = &line[prev..pos];
345                            spans.push(Span::styled(
346                                text.to_string(),
347                                resolve_scope(&stack, styles),
348                            ));
349                        }
350                        let _ = stack.apply(op);
351                        prev = pos;
352                    }
353                    if prev < line.len() {
354                        let text = &line[prev..];
355                        spans.push(Span::styled(
356                            text.to_string(),
357                            resolve_scope(&stack, styles),
358                        ));
359                    }
360                    output.push(Line::from(spans));
361                }
362                Err(_) => {
363                    output.push(Line::from(vec![
364                        Span::styled(" │ ", theme.border),
365                        Span::styled(line.to_string(), Style::default().fg(theme.fg)),
366                    ]));
367                }
368            }
369        }
370        if code_lines.is_empty() {
371            output.push(Line::from(Span::styled(" │", theme.border)));
372        }
373    } else {
374        for raw_line in code_lines {
375            let line = &truncate_code_line(raw_line, w.saturating_sub(3));
376            output.push(Line::from(vec![
377                Span::styled(" │ ", theme.border),
378                Span::styled(line.to_string(), Style::default().fg(theme.fg)),
379            ]));
380        }
381        if code_lines.is_empty() {
382            output.push(Line::from(Span::styled(" │", theme.border)));
383        }
384    }
385
386    output.push(Line::from(""));
387}
388
389#[allow(clippy::while_let_on_iterator)]
390fn parse_inline(text: &str, theme: &Theme) -> Vec<Span<'static>> {
391    let mut spans: Vec<Span<'static>> = Vec::new();
392    let mut chars = text.char_indices().peekable();
393    let mut current = String::new();
394
395    while let Some((_i, c)) = chars.next() {
396        match c {
397            '`' => {
398                if !current.is_empty() {
399                    spans.push(Span::raw(std::mem::take(&mut current)));
400                }
401                let mut code = String::new();
402                let mut closed = false;
403                while let Some((_, ch)) = chars.next() {
404                    if ch == '`' {
405                        closed = true;
406                        break;
407                    }
408                    code.push(ch);
409                }
410                if closed {
411                    spans.push(Span::styled(code, theme.inline_code));
412                } else {
413                    spans.push(Span::raw(format!("`{}", code)));
414                }
415            }
416            '*' => {
417                let next_is_star = chars.peek().map(|(_, ch)| *ch == '*').unwrap_or(false);
418                if next_is_star {
419                    chars.next();
420                    if !current.is_empty() {
421                        spans.push(Span::raw(std::mem::take(&mut current)));
422                    }
423                    let mut bold_text = String::new();
424                    let mut closed = false;
425                    while let Some((_, ch)) = chars.next() {
426                        if ch == '*' && chars.peek().map(|(_, c)| *c == '*').unwrap_or(false) {
427                            chars.next();
428                            closed = true;
429                            break;
430                        }
431                        bold_text.push(ch);
432                    }
433                    if closed {
434                        spans.push(Span::styled(bold_text, theme.bold));
435                    } else {
436                        spans.push(Span::raw(format!("**{}", bold_text)));
437                    }
438                } else {
439                    if !current.is_empty() {
440                        spans.push(Span::raw(std::mem::take(&mut current)));
441                    }
442                    let mut italic_text = String::new();
443                    let mut closed = false;
444                    while let Some((_, ch)) = chars.next() {
445                        if ch == '*' {
446                            closed = true;
447                            break;
448                        }
449                        italic_text.push(ch);
450                    }
451                    if closed {
452                        spans.push(Span::styled(italic_text, theme.italic));
453                    } else {
454                        spans.push(Span::raw(format!("*{}", italic_text)));
455                    }
456                }
457            }
458            '[' => {
459                if !current.is_empty() {
460                    spans.push(Span::raw(std::mem::take(&mut current)));
461                }
462                let mut link_text = String::new();
463                let mut found_bracket = false;
464                while let Some((_, ch)) = chars.next() {
465                    if ch == ']' {
466                        found_bracket = true;
467                        break;
468                    }
469                    link_text.push(ch);
470                }
471                if found_bracket && chars.peek().map(|(_, c)| *c == '(').unwrap_or(false) {
472                    chars.next();
473                    let mut _url = String::new();
474                    while let Some((_, ch)) = chars.next() {
475                        if ch == ')' {
476                            break;
477                        }
478                        _url.push(ch);
479                    }
480                    spans.push(Span::styled(link_text, theme.link));
481                } else {
482                    spans.push(Span::raw(format!("[{}", link_text)));
483                    if found_bracket {
484                        spans.push(Span::raw("]"));
485                    }
486                }
487            }
488            _ => {
489                current.push(c);
490            }
491        }
492    }
493
494    if !current.is_empty() {
495        spans.push(Span::raw(current));
496    }
497
498    if spans.is_empty() {
499        spans.push(Span::raw(""));
500    }
501
502    spans
503}