curd-editor 0.27.1

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
//! Showing an answer written in Markdown: wrapped, with headings, lists and
//! coloured blocks of code.

use super::*;

/// Breaks `text` into lines of at most `width` characters, at spaces where
/// it can.
pub fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    for line in text.split('\n') {
        let chars: Vec<(char, Style)> = line.chars().map(|c| (c, Style::Plain)).collect();
        let pieces = wrap_chars(&chars, width);
        lines.extend(pieces.iter().map(|piece| piece.iter().map(|(c, _)| *c).collect()));
    }
    lines
}

/// Breaks one line of styled characters into pieces of at most `width`,
/// at spaces where it can.
pub(super) fn wrap_chars(chars: &[(char, Style)], width: usize) -> Vec<&[(char, Style)]> {
    let width = width.max(1);
    let mut pieces = Vec::new();
    let mut start = 0;
    while chars.len() - start > width {
        let limit = start + width;
        let cut = (start + 1..=limit).rev().find(|at| chars[*at].0 == ' ').unwrap_or(limit);
        pieces.push(&chars[start..cut]);
        start = cut + (chars[cut].0 == ' ') as usize;
    }
    pieces.push(&chars[start..]);
    pieces
}

/// Styled characters as one row of `width` characters, after `prefix`.
pub(super) fn row_of(prefix: Option<Span>, chars: &[(char, Style)], width: usize) -> Row {
    let mut row: Row = prefix.into_iter().collect();
    let mut used: usize = row.iter().map(|span| span.text.chars().count()).sum();
    for (c, style) in chars {
        match row.last_mut() {
            Some(last) if last.style == *style => last.text.push(*c),
            _ => row.push(Span::new(*style, c.to_string())),
        }
    }
    used += chars.len();
    row.push(Span::new(Style::Plain, " ".repeat(width.saturating_sub(used))));
    row
}

/// The language a block of code is in, from the word after its opening
/// fence: ```rust.
pub(super) fn fence_language(tag: &str) -> Option<Language> {
    let extension = match tag.trim().to_ascii_lowercase().as_str() {
        "rust" => "rs".into(),
        "python" => "py".into(),
        "javascript" | "typescript" => "js".into(),
        "c++" => "cpp".into(),
        "golang" => "go".into(),
        other => other.to_string(),
    };
    Language::from_path(&format!("code.{extension}"))
}

/// One line of ordinary text as styled characters: `code` in colour,
/// **bold** in bold, and the marks themselves left out.
pub(super) fn inline(text: &str, base: Style) -> Vec<(char, Style)> {
    let code = Style::Colored(Color::Cyan);
    let chars: Vec<char> = text.chars().collect();
    let (mut in_code, mut bold) = (false, false);
    let mut styled = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        match chars[i] {
            '`' => in_code = !in_code,
            '*' if !in_code && chars.get(i + 1) == Some(&'*') => {
                bold = !bold;
                i += 1;
            }
            c if in_code => styled.push((c, code)),
            c if bold => styled.push((c, Style::Bold)),
            c => styled.push((c, base)),
        }
        i += 1;
    }
    styled
}

/// An answer as rows: Markdown the way a terminal can show it. Headings
/// are bold, list items get a bullet, and blocks of code are set apart by
/// a bar and coloured like code in the editor.
pub fn markdown(text: &str, width: usize) -> Vec<Row> {
    let mut rows = Vec::new();
    // Inside a block of code: its language, if known, and what the next
    // line starts inside of (a comment or string left open).
    let mut code: Option<(Option<Language>, LineState)> = None;
    for line in text.split('\n') {
        // One character per cell of the screen, so wide characters and
        // tabs keep the rows the right width.
        let line = &widen(line);
        if let Some(tag) = line.trim_start().strip_prefix("```") {
            code = match code {
                Some(_) => None,
                None => Some((fence_language(tag), LineState::Code)),
            };
            continue;
        }
        let Some((language, state)) = &mut code else {
            let trimmed = line.trim_start();
            let indent = &line[..line.len() - trimmed.len()];
            let heading = trimmed.trim_start_matches('#');
            let chars = if heading.len() < trimmed.len() && heading.starts_with(' ') {
                inline(heading.trim_start(), Style::Bold)
            } else if let Some(item) = trimmed.strip_prefix("- ").or(trimmed.strip_prefix("* ")) {
                inline(&format!("{indent}• {item}"), Style::Plain)
            } else {
                inline(line, Style::Plain)
            };
            for piece in wrap_chars(&chars, width) {
                rows.push(row_of(None, piece, width));
            }
            continue;
        };
        let mut chars: Vec<(char, Style)> = line.chars().map(|c| (c, Style::Plain)).collect();
        if let Some(language) = language {
            let mut tokens = Vec::new();
            *state = highlight::lex_line(line, *language, *state, &mut tokens);
            for token in tokens {
                let decoration = Decoration { kind: token.kind, ..Decoration::default() };
                let end = token.end.min(chars.len());
                for (_, style) in &mut chars[token.start.min(end)..end] {
                    *style = Style::Code(decoration);
                }
            }
        }
        for piece in wrap_chars(&chars, width.saturating_sub(2)) {
            rows.push(row_of(Some(Span::new(Style::Dim, "│ ")), piece, width));
        }
    }
    rows
}