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(2));
276            let (prefix_char, diff_style, bg_color) = if line.starts_with('+') {
277                ("+", theme.diff_add, Some(theme.diff_add_bg))
278            } else if line.starts_with('-') {
279                ("-", theme.diff_remove, Some(theme.diff_remove_bg))
280            } else if line.starts_with('@') {
281                ("@", theme.diff_hunk, None)
282            } else {
283                (" ", Style::default().fg(theme.fg), None)
284            };
285            let gutter_style = if let Some(bg) = bg_color {
286                diff_style.bg(bg)
287            } else {
288                diff_style
289            };
290            let content_style = if let Some(bg) = bg_color {
291                diff_style.bg(bg)
292            } else {
293                diff_style
294            };
295            let content_text = if line.len() > 1 { &line[1..] } else { "" };
296            let pad_needed = w.saturating_sub(2 + 2 + content_text.chars().count());
297            let mut spans = vec![
298                Span::styled("│ ", theme.border),
299                Span::styled(format!("{} ", prefix_char), gutter_style),
300                Span::styled(content_text.to_string(), content_style),
301            ];
302            if bg_color.is_some() && pad_needed > 0 {
303                spans.push(Span::styled(" ".repeat(pad_needed), content_style));
304            }
305            output.push(Line::from(spans));
306        }
307        if code_lines.is_empty() {
308            output.push(Line::from(Span::styled("│", theme.border)));
309        }
310    } else if let Some(syntect_theme_name) = theme.syntect_theme
311        && !lang.is_empty()
312        && let Some(syntax) = SYNTAX_SET.find_syntax_by_token(lang)
313        && let Some(st_theme) = THEME_SET.themes.get(syntect_theme_name)
314    {
315        let mut highlighter = syntect::easy::HighlightLines::new(syntax, st_theme);
316        for raw_line in code_lines {
317            let line: &str = &truncate_code_line(raw_line, w.saturating_sub(2));
318            let highlighted = highlighter.highlight_line(line, &SYNTAX_SET);
319            match highlighted {
320                Ok(ranges) => {
321                    let mut spans = vec![Span::styled("│ ", theme.border)];
322                    for (style, text) in ranges {
323                        let fg = style.foreground;
324                        let clean = text.trim_end_matches('\n');
325                        if clean.is_empty() {
326                            continue;
327                        }
328                        spans.push(Span::styled(
329                            clean.to_string(),
330                            Style::default().fg(Color::Rgb(fg.r, fg.g, fg.b)),
331                        ));
332                    }
333                    output.push(Line::from(spans));
334                }
335                Err(_) => {
336                    output.push(Line::from(vec![
337                        Span::styled("│ ", theme.border),
338                        Span::styled(line.to_string(), Style::default().fg(theme.fg)),
339                    ]));
340                }
341            }
342        }
343        if code_lines.is_empty() {
344            output.push(Line::from(Span::styled("│", theme.border)));
345        }
346    } else if let Some(styles) = &theme.syntax
347        && !lang.is_empty()
348        && let Some(syntax) = SYNTAX_SET.find_syntax_by_token(lang)
349    {
350        let mut state = ParseState::new(syntax);
351        let mut stack = ScopeStack::new();
352        for raw_line in code_lines {
353            let line = &truncate_code_line(raw_line, w.saturating_sub(2));
354            match state.parse_line(line, &SYNTAX_SET) {
355                Ok(ops) => {
356                    let mut spans = vec![Span::styled("│ ", theme.border)];
357                    let mut prev = 0;
358                    for (pos, op) in &ops {
359                        let pos = (*pos).min(line.len());
360                        if pos > prev {
361                            let text = &line[prev..pos];
362                            spans.push(Span::styled(
363                                text.to_string(),
364                                resolve_scope(&stack, styles),
365                            ));
366                        }
367                        let _ = stack.apply(op);
368                        prev = pos;
369                    }
370                    if prev < line.len() {
371                        let text = &line[prev..];
372                        spans.push(Span::styled(
373                            text.to_string(),
374                            resolve_scope(&stack, styles),
375                        ));
376                    }
377                    output.push(Line::from(spans));
378                }
379                Err(_) => {
380                    output.push(Line::from(vec![
381                        Span::styled("│ ", theme.border),
382                        Span::styled(line.to_string(), Style::default().fg(theme.fg)),
383                    ]));
384                }
385            }
386        }
387        if code_lines.is_empty() {
388            output.push(Line::from(Span::styled("│", theme.border)));
389        }
390    } else {
391        for raw_line in code_lines {
392            let line = &truncate_code_line(raw_line, w.saturating_sub(2));
393            output.push(Line::from(vec![
394                Span::styled("│ ", theme.border),
395                Span::styled(line.to_string(), Style::default().fg(theme.fg)),
396            ]));
397        }
398        if code_lines.is_empty() {
399            output.push(Line::from(Span::styled("│", theme.border)));
400        }
401    }
402
403    output.push(Line::from(""));
404}
405
406#[allow(clippy::while_let_on_iterator)]
407fn parse_inline(text: &str, theme: &Theme) -> Vec<Span<'static>> {
408    let mut spans: Vec<Span<'static>> = Vec::new();
409    let mut chars = text.char_indices().peekable();
410    let mut current = String::new();
411
412    while let Some((_i, c)) = chars.next() {
413        match c {
414            '`' => {
415                if !current.is_empty() {
416                    spans.push(Span::raw(std::mem::take(&mut current)));
417                }
418                let mut code = String::new();
419                let mut closed = false;
420                while let Some((_, ch)) = chars.next() {
421                    if ch == '`' {
422                        closed = true;
423                        break;
424                    }
425                    code.push(ch);
426                }
427                if closed {
428                    spans.push(Span::styled(code, theme.inline_code));
429                } else {
430                    spans.push(Span::raw(format!("`{}", code)));
431                }
432            }
433            '*' => {
434                let next_is_star = chars.peek().map(|(_, ch)| *ch == '*').unwrap_or(false);
435                if next_is_star {
436                    chars.next();
437                    if !current.is_empty() {
438                        spans.push(Span::raw(std::mem::take(&mut current)));
439                    }
440                    let mut bold_text = String::new();
441                    let mut closed = false;
442                    while let Some((_, ch)) = chars.next() {
443                        if ch == '*' && chars.peek().map(|(_, c)| *c == '*').unwrap_or(false) {
444                            chars.next();
445                            closed = true;
446                            break;
447                        }
448                        bold_text.push(ch);
449                    }
450                    if closed {
451                        spans.push(Span::styled(bold_text, theme.bold));
452                    } else {
453                        spans.push(Span::raw(format!("**{}", bold_text)));
454                    }
455                } else {
456                    if !current.is_empty() {
457                        spans.push(Span::raw(std::mem::take(&mut current)));
458                    }
459                    let mut italic_text = String::new();
460                    let mut closed = false;
461                    while let Some((_, ch)) = chars.next() {
462                        if ch == '*' {
463                            closed = true;
464                            break;
465                        }
466                        italic_text.push(ch);
467                    }
468                    if closed {
469                        spans.push(Span::styled(italic_text, theme.italic));
470                    } else {
471                        spans.push(Span::raw(format!("*{}", italic_text)));
472                    }
473                }
474            }
475            '[' => {
476                if !current.is_empty() {
477                    spans.push(Span::raw(std::mem::take(&mut current)));
478                }
479                let mut link_text = String::new();
480                let mut found_bracket = false;
481                while let Some((_, ch)) = chars.next() {
482                    if ch == ']' {
483                        found_bracket = true;
484                        break;
485                    }
486                    link_text.push(ch);
487                }
488                if found_bracket && chars.peek().map(|(_, c)| *c == '(').unwrap_or(false) {
489                    chars.next();
490                    let mut _url = String::new();
491                    while let Some((_, ch)) = chars.next() {
492                        if ch == ')' {
493                            break;
494                        }
495                        _url.push(ch);
496                    }
497                    spans.push(Span::styled(link_text, theme.link));
498                } else {
499                    spans.push(Span::raw(format!("[{}", link_text)));
500                    if found_bracket {
501                        spans.push(Span::raw("]"));
502                    }
503                }
504            }
505            _ => {
506                current.push(c);
507            }
508        }
509    }
510
511    if !current.is_empty() {
512        spans.push(Span::raw(current));
513    }
514
515    if spans.is_empty() {
516        spans.push(Span::raw(""));
517    }
518
519    spans
520}