mrk-cli 0.10.0

Render Markdown beautifully in the terminal: syntax highlighting, tables, themes, and Mermaid diagrams as images.
Documentation
use comrak::nodes::{AstNode, NodeTable, NodeValue, TableAlignment};

use super::context::Context;
use super::inline;
use crate::document::{Line, Span, Style};
use crate::text;

/// A squeezed column keeps room for a short word; below that the table renders as records.
const MIN_COLUMN_WIDTH: usize = 3;
/// `│ ` before each cell and ` │` after the last: three cells of frame per column, plus one.
const FRAME_PER_COLUMN: usize = 3;
const RECORD_INDENT: &str = "  ";
const RECORD_SEPARATOR: &str = ": ";

type Cell = Vec<Span>;

struct Row {
    cells: Vec<Cell>,
    is_header: bool,
}

struct WrappedRow {
    cells: Vec<Vec<Line>>,
    is_header: bool,
}

struct Border {
    left: &'static str,
    junction: &'static str,
    right: &'static str,
}

const TOP: Border = Border { left: "╭", junction: "┬", right: "╮" };
const MIDDLE: Border = Border { left: "├", junction: "┼", right: "┤" };
const BOTTOM: Border = Border { left: "╰", junction: "┴", right: "╯" };

/// A rounded box with the header in bold `accent`; cells wrap when the table is wider than the context,
/// and a table with too many columns to fit renders as one `header: value` record per row.
pub(super) fn render<'a>(node: &'a AstNode<'a>, table: &NodeTable, context: &Context) -> Vec<Line> {
    let rows = rows(node, table.alignments.len(), context);
    match column_widths(&rows, table.alignments.len(), context.width()) {
        Some(widths) => boxed(&rows, &widths, &table.alignments, context),
        None => records(&rows, context),
    }
}

fn header_style(context: &Context) -> Style {
    Style::fg(context.palette().accent).bold()
}

fn rows<'a>(node: &'a AstNode<'a>, columns: usize, context: &Context) -> Vec<Row> {
    let header = header_style(context);
    node.children()
        .map(|row| {
            let is_header = matches!(row.data().value, NodeValue::TableRow(true));
            let style = if is_header { header } else { context.style };
            let cells = row.children().map(|cell| inline::spans(cell, style, context)).chain(std::iter::repeat_with(Vec::new));
            Row { cells: cells.take(columns).collect(), is_header }
        })
        .collect()
}

fn cell_width(cell: &Cell) -> usize {
    text::spans_width(cell).max(1)
}

/// Each column as wide as its widest cell when that fits; otherwise the room is shared, narrow columns keeping
/// their natural width and wide ones splitting the rest evenly. `None` when even that cannot fit.
fn column_widths(rows: &[Row], columns: usize, width: usize) -> Option<Vec<usize>> {
    let natural: Vec<usize> = (0..columns).map(|column| rows.iter().map(|row| cell_width(&row.cells[column])).max().unwrap_or(1)).collect();
    let room = width.checked_sub(FRAME_PER_COLUMN * columns + 1)?;
    if natural.iter().sum::<usize>() <= room {
        return Some(natural);
    }
    if room < MIN_COLUMN_WIDTH * columns {
        return None;
    }
    let mut by_width: Vec<usize> = (0..columns).collect();
    by_width.sort_by_key(|column| natural[*column]);
    let mut widths = vec![0; columns];
    let mut remaining = room;
    for (placed, column) in by_width.into_iter().enumerate() {
        let share = remaining / (columns - placed);
        widths[column] = natural[column].min(share);
        remaining -= widths[column];
    }
    Some(widths)
}

fn boxed(rows: &[Row], widths: &[usize], alignments: &[TableAlignment], context: &Context) -> Vec<Line> {
    let border = Style::fg(context.palette().subtle);
    let wrapped: Vec<WrappedRow> = rows.iter().map(|row| wrap_row(row, widths)).collect();
    let widths = fitted_widths(&wrapped, widths.len());
    let (header, body): (Vec<&WrappedRow>, Vec<&WrappedRow>) = wrapped.iter().partition(|row| row.is_header);
    let separator = (!body.is_empty()).then(|| rule(&MIDDLE, &widths, border));
    let header_lines = header.into_iter().flat_map(|row| row_lines(row, &widths, alignments, border));
    let body_lines = body.into_iter().flat_map(|row| row_lines(row, &widths, alignments, border));
    let top = std::iter::once(rule(&TOP, &widths, border));
    let bottom = std::iter::once(rule(&BOTTOM, &widths, border));
    top.chain(header_lines).chain(separator).chain(body_lines).chain(bottom).collect()
}

fn wrap_row(row: &Row, widths: &[usize]) -> WrappedRow {
    WrappedRow {
        cells: row.cells.iter().zip(widths).map(|(cell, width)| text::wrap(cell, *width, &[])).collect(),
        is_header: row.is_header,
    }
}

/// Each column only as wide as its widest wrapped line, so a squeezed column gives back what wrapping left over.
fn fitted_widths(rows: &[WrappedRow], columns: usize) -> Vec<usize> {
    (0..columns).map(|column| rows.iter().flat_map(|row| row.cells[column].iter().map(Line::width)).max().unwrap_or(0).max(1)).collect()
}

fn rule(edges: &Border, widths: &[usize], border: Style) -> Line {
    let segments: Vec<String> = widths.iter().map(|width| "─".repeat(width + 2)).collect();
    Line::new(vec![Span::new(format!("{}{}{}", edges.left, segments.join(edges.junction), edges.right), border).framed()])
}

fn row_lines(row: &WrappedRow, widths: &[usize], alignments: &[TableAlignment], border: Style) -> Vec<Line> {
    let height = row.cells.iter().map(Vec::len).max().unwrap_or(1);
    (0..height).map(|index| row_line(row, index, widths, alignments, border)).collect()
}

/// Line `index` of every cell of the row, between the borders; a cell with fewer lines is blank there.
fn row_line(row: &WrappedRow, index: usize, widths: &[usize], alignments: &[TableAlignment], border: Style) -> Line {
    let cells = row
        .cells
        .iter()
        .zip(widths)
        .zip(alignments)
        .map(|((lines, width), alignment)| aligned(lines.get(index).cloned().unwrap_or_default(), *width, *alignment));
    let separators = std::iter::once("│ ").chain(std::iter::repeat(" │ ")).map(|separator| Span::new(separator, border).framed());
    let framed = separators.zip(cells).flat_map(|(separator, cell)| std::iter::once(separator).chain(cell));
    Line::new(framed.chain(std::iter::once(Span::new(" │", border).framed())).collect())
}

fn aligned(line: Line, width: usize, alignment: TableAlignment) -> Vec<Span> {
    let free = width.saturating_sub(line.width());
    let before = match alignment {
        TableAlignment::Right => free,
        TableAlignment::Center => free / 2,
        TableAlignment::Left | TableAlignment::None => 0,
    };
    let padding = |cells: usize| Span::plain(" ".repeat(cells)).framed();
    std::iter::once(padding(before))
        .chain(line.spans)
        .chain(std::iter::once(padding(free - before)))
        .filter(|span| !span.text.is_empty())
        .collect()
}

/// One `header: value` line per cell, rows a blank line apart, each header name cut to one line since every record
/// repeats it; a table with no body row lists its header names.
fn records(rows: &[Row], context: &Context) -> Vec<Line> {
    let Some((header, body)) = rows.split_first() else { return Vec::new() };
    let wrap = |spans: &[Span]| text::wrap(spans, context.width(), &[Span::plain(RECORD_INDENT).framed()]);
    if body.is_empty() {
        return header.cells.iter().flat_map(|name| wrap(name)).collect();
    }
    let separator = [Span::new(RECORD_SEPARATOR, header_style(context)).framed()];
    let name_width = context.width().saturating_sub(text::display_width(RECORD_SEPARATOR));
    let names: Vec<Line> = header.cells.iter().map(|name| text::fit(name, name_width)).collect();
    let record = |row: &Row| -> Vec<Line> {
        names.iter().zip(&row.cells).flat_map(|(name, cell)| wrap(&[&name.spans, &separator[..], cell].concat())).collect()
    };
    body.iter().map(record).collect::<Vec<_>>().join(&Line::blank())
}

#[cfg(test)]
mod tests {
    use crate::document::{Span, Style};
    use crate::markdown::{plain_at, styled};
    use crate::theme::MRK_DARK;

    const TABLE: &str =
        "| Name | Left | Center | Right |\n|------|:-----|:------:|------:|\n| mrk | a | b | 1 |\n| glow | longer cell text | c | 22 |";

    #[test]
    fn natural_width_with_alignment() {
        insta::assert_snapshot!(plain_at(TABLE, 80));
    }

    #[test]
    fn cells_wrap_when_the_table_is_too_wide() {
        insta::assert_snapshot!(plain_at(TABLE, 34));
    }

    #[test]
    fn too_many_columns_render_as_records() {
        let header = (1..=12).map(|column| format!("c{column}")).collect::<Vec<_>>().join(" | ");
        let row = (1..=12).map(|column| format!("v{column}")).collect::<Vec<_>>().join(" | ");
        let source = format!("| {header} |\n|{}\n| {row} |\n| {row} |", "---|".repeat(12));

        insta::assert_snapshot!(plain_at(&source, 30));
    }

    #[test]
    fn a_cell_is_as_wide_as_the_emoji_its_removed_characters_merge_into() {
        insta::assert_snapshot!(plain_at(
            "| a | b |\n|---|---|\n| ❤\u{200b}\u{fe0f}❤\u{200b}\u{fe0f}❤\u{200b}\u{fe0f} | x |\n| abc | y |",
            40
        ));
    }

    #[test]
    fn a_record_cuts_a_header_name_wider_than_the_line_to_one_line() {
        let header = format!("{} | {}", "word ".repeat(10), "c | ".repeat(9));
        let source = format!("| {header}\n|{}\n| v1 | v2 |", "---|".repeat(10));
        let plain = plain_at(&source, 20);

        assert_eq!(plain.lines().take(3).collect::<Vec<_>>(), ["word word word wo…:", "  v1", "c: v2"]);
    }

    #[test]
    fn a_header_only_table_too_wide_to_box_lists_its_names() {
        let header = (1..=10).map(|column| format!("c{column}")).collect::<Vec<_>>().join(" | ");
        let source = format!("| {header} |\n|{}", "---|".repeat(10));

        assert_eq!(plain_at(&source, 20), "c1\nc2\nc3\nc4\nc5\nc6\nc7\nc8\nc9\nc10\n");
    }

    #[test]
    fn header_is_bold_accent_and_borders_subtle() {
        let palette = MRK_DARK.palette;
        let border = |text: &str| Span::new(text, Style::fg(palette.subtle)).framed();

        assert_eq!(
            styled("| a |\n|---|\n| b |"),
            [
                vec![border("╭───╮")],
                vec![border("│ "), Span::new("a", Style::fg(palette.accent).bold()), border(" │")],
                vec![border("├───┤")],
                vec![border("│ "), Span::new("b", Style::fg(palette.text)), border(" │")],
                vec![border("╰───╯")],
            ]
        );
    }

    #[test]
    fn missing_cells_are_empty() {
        insta::assert_snapshot!(plain_at("| a | b |\n|---|---|\n| only |", 40));
    }
}