use std::collections::BTreeMap;
use std::ops::{Deref, Range};
use std::sync::OnceLock;
use mbdown::{
mermaid_text, Alignment, BorderMode, ColumnWidth, Container, ContainerEnd, Document, Event,
HeadingLevel, InlineTag, Node, WidthMode,
};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use syntect::easy::HighlightLines;
use syntect::highlighting::{FontStyle, Theme as SyntaxTheme, ThemeSet};
use syntect::parsing::SyntaxSet;
use syntect::util::LinesWithEndings;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
const TXM_WIDE_FILLER: char = '\u{200b}';
mod catppuccin {
use ratatui::style::Color;
pub const PINK: Color = Color::Rgb(245, 194, 231);
pub const MAUVE: Color = Color::Rgb(203, 166, 247);
pub const RED: Color = Color::Rgb(243, 139, 168);
pub const PEACH: Color = Color::Rgb(250, 179, 135);
pub const YELLOW: Color = Color::Rgb(249, 226, 175);
pub const GREEN: Color = Color::Rgb(166, 227, 161);
pub const TEAL: Color = Color::Rgb(148, 226, 213);
pub const SKY: Color = Color::Rgb(137, 220, 235);
pub const SAPPHIRE: Color = Color::Rgb(116, 199, 236);
pub const BLUE: Color = Color::Rgb(137, 180, 250);
pub const LAVENDER: Color = Color::Rgb(180, 190, 254);
pub const TEXT: Color = Color::Rgb(205, 214, 244);
pub const SUBTEXT_0: Color = Color::Rgb(166, 173, 200);
pub const OVERLAY_1: Color = Color::Rgb(127, 132, 156);
pub const OVERLAY_0: Color = Color::Rgb(108, 112, 134);
pub const SURFACE_0: Color = Color::Rgb(49, 50, 68);
pub const SYNTAX: [Color; 13] = [
PINK, MAUVE, RED, PEACH, YELLOW, GREEN, TEAL, SKY, SAPPHIRE, BLUE, LAVENDER, TEXT,
SUBTEXT_0,
];
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CornerStyle {
#[default]
Square,
Rounded,
}
impl CornerStyle {
const fn top_left(self) -> char {
match self {
Self::Square => '┌',
Self::Rounded => '╭',
}
}
const fn top_right(self) -> char {
match self {
Self::Square => '┐',
Self::Rounded => '╮',
}
}
const fn bottom_left(self) -> char {
match self {
Self::Square => '└',
Self::Rounded => '╰',
}
}
const fn bottom_right(self) -> char {
match self {
Self::Square => '┘',
Self::Rounded => '╯',
}
}
}
#[derive(Clone, Debug)]
pub struct Theme {
pub corner_style: CornerStyle,
pub heading_1: Style,
pub heading_2: Style,
pub heading_3: Style,
pub heading_minor: Style,
pub quote: Style,
pub list: Style,
pub rule: Style,
pub code: Style,
pub code_block: Style,
pub code_label: Style,
pub link: Style,
pub hashtag: Style,
pub wikilink: Style,
styles: BTreeMap<String, Style>,
}
impl Default for Theme {
fn default() -> Self {
Self {
corner_style: CornerStyle::Square,
heading_1: Style::default()
.fg(catppuccin::LAVENDER)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
heading_2: Style::default()
.fg(catppuccin::BLUE)
.add_modifier(Modifier::BOLD),
heading_3: Style::default()
.fg(catppuccin::MAUVE)
.add_modifier(Modifier::BOLD),
heading_minor: Style::default()
.fg(catppuccin::SAPPHIRE)
.add_modifier(Modifier::BOLD),
quote: Style::default().fg(catppuccin::MAUVE),
list: Style::default()
.fg(catppuccin::TEAL)
.add_modifier(Modifier::BOLD),
rule: Style::default().fg(catppuccin::OVERLAY_0),
code: Style::default().fg(catppuccin::PEACH),
code_block: Style::default()
.fg(catppuccin::TEXT)
.bg(catppuccin::SURFACE_0),
code_label: Style::default().fg(catppuccin::OVERLAY_1),
link: Style::default()
.fg(catppuccin::BLUE)
.underline_color(catppuccin::BLUE)
.add_modifier(Modifier::UNDERLINED),
hashtag: Style::default()
.fg(catppuccin::PINK)
.add_modifier(Modifier::BOLD),
wikilink: Style::default()
.fg(catppuccin::SKY)
.add_modifier(Modifier::UNDERLINED),
styles: BTreeMap::new(),
}
}
}
impl Theme {
pub fn with_corner_style(mut self, corner_style: CornerStyle) -> Self {
self.corner_style = corner_style;
self
}
pub fn insert(&mut self, name: impl Into<String>, style: Style) -> Option<Style> {
self.styles.insert(name.into().to_ascii_lowercase(), style)
}
fn get(&self, name: &str) -> Option<Style> {
self.styles.get(name).copied()
}
fn heading(&self, level: HeadingLevel) -> (&'static str, Style) {
match level {
HeadingLevel::H1 => ("◆ ", self.heading_1),
HeadingLevel::H2 => ("◇ ", self.heading_2),
HeadingLevel::H3 => ("› ", self.heading_3),
HeadingLevel::H4 | HeadingLevel::H5 | HeadingLevel::H6 => ("· ", self.heading_minor),
}
}
}
pub struct Renderer {
width: usize,
theme: Theme,
image_height: usize,
render_front_matter: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImagePlacement {
pub source: String,
pub title: String,
pub alt: String,
pub row: usize,
pub column: usize,
pub width: usize,
pub height: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CellRegion {
pub row: usize,
pub column: usize,
pub width: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SemanticKind {
Hashtag { name: String },
WikiLink { target: String },
Embed { target: String },
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SemanticPlacement {
pub kind: SemanticKind,
pub source_span: Range<usize>,
pub regions: Vec<CellRegion>,
}
impl SemanticPlacement {
fn offset(&mut self, row: usize, column: usize) {
for region in &mut self.regions {
region.row += row;
region.column += column;
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FrontMatter {
pub kind: mbdown::FrontMatterKind,
pub source: String,
pub raw: String,
pub span: Range<usize>,
}
impl From<&mbdown::FrontMatter<'_>> for FrontMatter {
fn from(front_matter: &mbdown::FrontMatter<'_>) -> Self {
Self {
kind: front_matter.kind(),
source: front_matter.source().to_owned(),
raw: front_matter.raw().to_owned(),
span: front_matter.span(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RenderedDocument {
pub text: Text<'static>,
pub images: Vec<ImagePlacement>,
pub semantics: Vec<SemanticPlacement>,
pub front_matter: Option<FrontMatter>,
}
impl Deref for RenderedDocument {
type Target = Text<'static>;
fn deref(&self) -> &Self::Target {
&self.text
}
}
impl Renderer {
pub fn new(width: usize) -> Self {
Self::with_theme(width, Theme::default())
}
pub fn with_theme(width: usize, theme: Theme) -> Self {
Self {
width: width.max(1),
theme,
image_height: 12,
render_front_matter: false,
}
}
pub fn with_image_height(mut self, image_height: usize) -> Self {
self.image_height = image_height.max(1);
self
}
pub fn with_front_matter(mut self, enabled: bool) -> Self {
self.render_front_matter = enabled;
self
}
pub fn render<'a>(&self, document: &Document<'a>) -> RenderedDocument {
let mut output = Output::new(self.width, &self.theme, self.image_height);
if self.render_front_matter {
if let Some(front_matter) = document.front_matter() {
output.front_matter(front_matter);
}
}
let front_matter = document.front_matter().map(FrontMatter::from);
output.nodes(document.nodes());
let rendered = output.finish();
RenderedDocument {
text: Text::from(rendered.lines),
images: rendered.images,
semantics: rendered.semantics,
front_matter,
}
}
}
struct RenderedLines {
lines: Vec<Line<'static>>,
images: Vec<ImagePlacement>,
semantics: Vec<SemanticPlacement>,
}
struct PendingSemantic {
kind: SemanticKind,
source_span: Range<usize>,
style: Style,
}
const SEMANTIC_START: &str = "\u{2063}\u{200b}\u{2063}";
const SEMANTIC_END: &str = "\u{200b}\u{2063}\u{200b}";
struct Output<'a> {
width: usize,
theme: &'a Theme,
lines: Vec<Line<'static>>,
images: Vec<ImagePlacement>,
semantics: Vec<SemanticPlacement>,
pending_semantics: Vec<PendingSemantic>,
spans: Vec<Span<'static>>,
styles: Vec<(String, Style)>,
quote_depth: usize,
lists: Vec<Option<u64>>,
items: Vec<ItemState>,
image_height: usize,
}
#[derive(Default)]
struct ItemState {
completed: bool,
continuation_width: usize,
continues: bool,
}
impl<'a> Output<'a> {
fn new(width: usize, theme: &'a Theme, image_height: usize) -> Self {
Self {
width,
theme,
lines: Vec::new(),
images: Vec::new(),
semantics: Vec::new(),
pending_semantics: Vec::new(),
spans: Vec::new(),
styles: vec![(String::new(), Style::default())],
quote_depth: 0,
lists: Vec::new(),
items: Vec::new(),
image_height,
}
}
fn nodes(&mut self, nodes: &[Node<'_>]) {
for node in nodes {
match node {
Node::Markdown(markdown) => {
self.markdown(markdown.events(), markdown.source_span().start)
}
Node::Box { spec, children } => self.render_box(spec, children),
Node::Center { children } => {
self.flush();
let mut child =
child_output(self.width, self.theme, children, self.image_height);
let row_offset = self.lines.len();
let row_padding = child
.lines
.iter()
.map(|line| self.width.saturating_sub(spans_width(&line.spans)) / 2)
.collect::<Vec<_>>();
for image in &mut child.images {
image.row += row_offset;
image.column += self.width.saturating_sub(image.width) / 2;
}
for semantic in &mut child.semantics {
for region in &mut semantic.regions {
region.column += row_padding.get(region.row).copied().unwrap_or(0);
region.row += row_offset;
}
}
self.images.extend(child.images);
self.semantics.extend(child.semantics);
for mut line in child.lines {
let padding = self.width.saturating_sub(spans_width(&line.spans)) / 2;
if padding > 0 {
line.spans.insert(0, Span::raw(" ".repeat(padding)));
}
self.lines.push(line);
}
}
Node::Right { children } => {
self.flush();
let mut child =
child_output(self.width, self.theme, children, self.image_height);
let row_offset = self.lines.len();
let row_padding = child
.lines
.iter()
.map(|line| self.width.saturating_sub(spans_width(&line.spans)))
.collect::<Vec<_>>();
for image in &mut child.images {
image.row += row_offset;
image.column += self.width.saturating_sub(image.width);
}
for semantic in &mut child.semantics {
for region in &mut semantic.regions {
region.column += row_padding.get(region.row).copied().unwrap_or(0);
region.row += row_offset;
}
}
self.images.extend(child.images);
self.semantics.extend(child.semantics);
for mut line in child.lines {
let padding = self.width.saturating_sub(spans_width(&line.spans));
if padding > 0 && !line.spans.is_empty() {
line.spans.insert(0, Span::raw(" ".repeat(padding)));
}
self.lines.push(line);
}
}
Node::Indent { spec, children } => {
self.flush();
let mut child = child_output(
self.width.saturating_sub(spec.first).max(1),
self.theme,
children,
self.image_height,
);
let row_offset = self.lines.len();
for image in &mut child.images {
image.row += row_offset;
image.column += spec.first;
}
for semantic in &mut child.semantics {
semantic.offset(row_offset, spec.first);
}
self.images.extend(child.images);
self.semantics.extend(child.semantics);
for mut line in child.lines {
if !line.spans.is_empty() {
line.spans.insert(0, Span::raw(" ".repeat(spec.first)));
}
self.lines.push(line);
}
}
Node::Columns { spec, children } => self.render_columns(spec, children),
Node::Column { children, .. } => self.nodes(children),
}
}
}
fn render_box(&mut self, spec: &mbdown::BoxSpec, children: &[Node<'_>]) {
self.flush();
let width = match spec.width {
WidthMode::Full => self.width,
WidthMode::Exact(width) => width.min(self.width),
WidthMode::Fit => self.width,
}
.max(
usize::from(spec.border == BorderMode::Single) * 2
+ spec.padding.x.saturating_mul(2)
+ 1,
);
let background = spec
.bg
.as_deref()
.and_then(|value| parse_color(value).or_else(|| self.theme.get(value)?.bg));
let border_style = spec
.border_color
.as_deref()
.and_then(|value| {
parse_color(value)
.map(|color| Style::default().fg(color))
.or_else(|| self.theme.get(value))
})
.or_else(|| self.theme.get("markdown-box"))
.unwrap_or_default();
let style = background.map_or(border_style, |bg| border_style.bg(bg));
let border_width = usize::from(spec.border == BorderMode::Single) * 2;
let inside_width = width.saturating_sub(border_width).max(1);
let padding = constrained_padding(inside_width, spec.padding);
let content_width = inside_width
.saturating_sub(padding.x.saturating_mul(2))
.max(1);
let fill_style = background.map_or_else(Style::default, |bg| Style::default().bg(bg));
let mut content = pad_rendered(
child_output(content_width, self.theme, children, self.image_height),
inside_width,
padding,
fill_style,
);
if spec.border == BorderMode::None {
let row_offset = self.lines.len();
for image in &mut content.images {
image.row += row_offset;
}
for semantic in &mut content.semantics {
semantic.offset(row_offset, 0);
}
self.images.extend(content.images);
self.semantics.extend(content.semantics);
self.lines.extend(content.lines);
return;
}
let title = spec.title.trim();
let top = if title.is_empty() {
format!(
"{}{}{}",
self.theme.corner_style.top_left(),
"─".repeat(width.saturating_sub(2)),
self.theme.corner_style.top_right()
)
} else {
let title_width = UnicodeWidthStr::width(title);
format!(
"{}─ {title} {}{}",
self.theme.corner_style.top_left(),
"─".repeat(width.saturating_sub(title_width + 5)),
self.theme.corner_style.top_right()
)
};
self.lines.push(Line::from(Span::styled(top, style)));
let row_offset = self.lines.len();
for image in &mut content.images {
image.row += row_offset;
image.column += 1;
}
for semantic in &mut content.semantics {
semantic.offset(row_offset, 1);
}
self.images.extend(content.images);
self.semantics.extend(content.semantics);
for mut line in content.lines {
line.spans.insert(0, Span::styled("│", style));
line.spans.push(Span::styled("│", style));
self.lines.push(line);
}
self.lines.push(Line::from(Span::styled(
format!(
"{}{}{}",
self.theme.corner_style.bottom_left(),
"─".repeat(width.saturating_sub(2)),
self.theme.corner_style.bottom_right()
),
style,
)));
}
fn render_columns(&mut self, spec: &mbdown::ColumnsSpec, children: &[Node<'_>]) {
self.flush();
let columns: Vec<_> = children
.iter()
.filter_map(|node| match node {
Node::Column { spec, children } => Some((spec, children.as_slice())),
_ => None,
})
.collect();
let parent_bg = spec
.bg
.as_deref()
.and_then(|value| parse_color(value).or_else(|| self.theme.get(value)?.bg));
let parent_style = parent_bg.map_or_else(Style::default, |bg| Style::default().bg(bg));
let padding = constrained_padding(self.width, spec.padding);
let inner_width = self
.width
.saturating_sub(padding.x.saturating_mul(2))
.max(1);
if columns.len() < 2 {
let mut content = RenderedLines {
lines: Vec::new(),
images: Vec::new(),
semantics: Vec::new(),
};
for (column, children) in columns {
let mut rendered = render_column_output(
column,
children,
inner_width,
parent_bg,
self.theme,
self.image_height,
);
let row_offset = content.lines.len();
for image in &mut rendered.images {
image.row += row_offset;
}
for semantic in &mut rendered.semantics {
semantic.offset(row_offset, 0);
}
content.lines.extend(rendered.lines);
content.images.extend(rendered.images);
content.semantics.extend(rendered.semantics);
}
self.extend_rendered(pad_rendered(content, self.width, padding, parent_style));
return;
}
let gap_total = spec.gap.saturating_mul(columns.len() - 1);
let fixed: usize = columns
.iter()
.map(|(column, _)| match column.width {
ColumnWidth::Fixed(width) => width,
ColumnWidth::Flex(_) => 0,
})
.sum();
let flex_weight: usize = columns
.iter()
.map(|(column, _)| match column.width {
ColumnWidth::Flex(weight) => weight,
ColumnWidth::Fixed(_) => 0,
})
.sum();
let flexible = inner_width.saturating_sub(gap_total + fixed);
let widths: Vec<_> = columns
.iter()
.map(|(column, _)| match column.width {
ColumnWidth::Fixed(width) => width.min(inner_width),
ColumnWidth::Flex(weight) => flexible.saturating_mul(weight) / flex_weight.max(1),
})
.collect();
if gap_total + widths.iter().sum::<usize>() > inner_width
|| columns.iter().zip(&widths).any(|((column, _), width)| {
*width < 8 || *width <= column.padding.x.saturating_mul(2)
})
{
let mut stacked = RenderedLines {
lines: Vec::new(),
images: Vec::new(),
semantics: Vec::new(),
};
for (index, (column, children)) in columns.iter().enumerate() {
if index > 0 {
stacked.lines.push(Line::default());
}
let mut rendered = render_column_output(
column,
children,
inner_width,
parent_bg,
self.theme,
self.image_height,
);
let row_offset = stacked.lines.len();
for image in &mut rendered.images {
image.row += row_offset;
}
for semantic in &mut rendered.semantics {
semantic.offset(row_offset, 0);
}
stacked.lines.extend(rendered.lines);
stacked.images.extend(rendered.images);
stacked.semantics.extend(rendered.semantics);
}
self.extend_rendered(pad_rendered(stacked, self.width, padding, parent_style));
return;
}
let rendered: Vec<_> = columns
.iter()
.zip(&widths)
.map(|((column, children), width)| {
render_column_output(
column,
children,
*width,
parent_bg,
self.theme,
self.image_height,
)
})
.collect();
let height = rendered
.iter()
.map(|rendered| rendered.lines.len())
.max()
.unwrap_or(0);
let mut output = Vec::new();
for row in 0..height {
let mut line = Vec::new();
for (index, ((column, _), width)) in columns.iter().zip(&widths).enumerate() {
let mut cell = rendered[index].lines.get(row).cloned().unwrap_or_default();
let background = column
.bg
.as_deref()
.and_then(|value| parse_color(value).or_else(|| self.theme.get(value)?.bg))
.or(parent_bg);
if let Some(background) = background {
apply_background(&mut cell, background, *width);
}
let remaining = width.saturating_sub(spans_width(&cell.spans));
line.extend(cell.spans);
if remaining > 0 {
line.push(Span::styled(
" ".repeat(remaining),
background.map_or_else(Style::default, |bg| Style::default().bg(bg)),
));
}
if index + 1 < columns.len() {
line.push(Span::styled(
" ".repeat(spec.gap),
parent_bg.map_or_else(Style::default, |bg| Style::default().bg(bg)),
));
}
}
output.push(Line::from(line));
}
let mut images = Vec::new();
let mut semantics = Vec::new();
let mut column_offset = 0usize;
for (index, rendered) in rendered.into_iter().enumerate() {
images.extend(rendered.images.into_iter().map(|mut image| {
image.column += column_offset;
image
}));
semantics.extend(rendered.semantics.into_iter().map(|mut semantic| {
semantic.offset(0, column_offset);
semantic
}));
column_offset += widths[index];
if index + 1 < widths.len() {
column_offset += spec.gap;
}
}
let grid_width = widths.iter().sum::<usize>() + gap_total;
let outer_width = grid_width
.saturating_add(padding.x.saturating_mul(2))
.min(self.width);
self.extend_rendered(pad_rendered(
RenderedLines {
lines: output,
images,
semantics,
},
outer_width,
padding,
parent_style,
));
}
fn extend_rendered(&mut self, mut rendered: RenderedLines) {
let row_offset = self.lines.len();
for image in &mut rendered.images {
image.row += row_offset;
}
for semantic in &mut rendered.semantics {
semantic.offset(row_offset, 0);
}
self.lines.extend(rendered.lines);
self.images.extend(rendered.images);
self.semantics.extend(rendered.semantics);
}
fn markdown(&mut self, events: &[mbdown::SpannedEvent<'_>], source_offset: usize) {
let mut index = 0;
while index < events.len() {
let item = &events[index];
if let Event::Start(Container::Table(alignments)) = &item.event {
let end = matching_table_end(events, index);
self.flush();
self.table(alignments, &events[index + 1..end], source_offset);
index = end + 1;
continue;
}
if let Event::Start(Container::CodeBlock(info)) = &item.event {
let end = matching_code_block_end(events, index);
self.flush();
self.code_block(info.as_deref(), &events[index + 1..end]);
self.blank();
index = end + 1;
continue;
}
if let Event::Start(Container::Image { target, title }) = &item.event {
let end = matching_image_end(events, index);
self.flush();
let alt = image_alt_text(&events[index + 1..end]);
if self.image_height == 0 {
let label = if alt.is_empty() {
target.as_ref()
} else {
alt.as_str()
};
self.text(&format!("[image] {label}"));
index = end.saturating_add(1);
continue;
}
let row = self.lines.len();
self.lines
.extend(std::iter::repeat_with(Line::default).take(self.image_height));
self.images.push(ImagePlacement {
source: target.to_string(),
title: title.to_string(),
alt,
row,
column: 0,
width: self.width,
height: self.image_height,
});
index = end.saturating_add(1);
continue;
}
if let Event::DisplayMath(math) = &item.event {
self.display_math(math);
index += 1;
continue;
}
if let Event::Embed(target) = &item.event {
if is_image_embed(target) {
self.flush();
if self.image_height == 0 {
self.text(&format!("[image] {target}"));
} else {
let row = self.lines.len();
self.lines
.extend(std::iter::repeat_with(Line::default).take(self.image_height));
self.images.push(ImagePlacement {
source: target.to_string(),
title: String::new(),
alt: target.to_string(),
row,
column: 0,
width: self.width,
height: self.image_height,
});
}
index += 1;
continue;
}
}
match &item.event {
Event::Start(container) => self.start(container),
Event::End(container) => self.end(*container),
Event::Text(text) => self.text(text),
Event::Hashtag(tag) => {
self.semantic(
SemanticKind::Hashtag {
name: tag.to_string(),
},
source_offset + item.span.start..source_offset + item.span.end,
format!("#{tag}"),
self.theme.hashtag,
);
}
Event::WikiLink(target) => {
self.semantic(
SemanticKind::WikiLink {
target: target.to_string(),
},
source_offset + item.span.start..source_offset + item.span.end,
format!("[[{target}]]"),
self.theme.wikilink,
);
}
Event::Embed(target) => {
self.semantic(
SemanticKind::Embed {
target: target.to_string(),
},
source_offset + item.span.start..source_offset + item.span.end,
format!("![[{target}]]"),
self.theme.wikilink,
);
}
Event::InlineTag(tag) => self.inline_tag(tag),
Event::Code(text) => {
self.push(Span::styled(text.to_string(), self.theme.code));
}
Event::Html(text) | Event::InlineHtml(text) => self.text(text),
Event::InlineMath(text) => {
self.push(Span::styled(format!("${text}$"), self.theme.code));
}
Event::DisplayMath(_) => unreachable!("handled before inline events"),
Event::FootnoteReference(text) => self.text(&format!("[{text}]")),
Event::SoftBreak | Event::HardBreak => {
self.flush();
if let Some(item) = self.items.last_mut() {
item.continues = true;
}
}
Event::Rule => {
self.flush();
self.lines.push(Line::from(Span::styled(
"─".repeat(self.width),
self.theme.rule,
)));
}
Event::TaskListMarker(checked) => {
let replaces_unordered_marker = self
.spans
.last()
.is_some_and(|span| span.content.as_ref() == " • ");
if replaces_unordered_marker {
self.spans.pop();
} else if *checked {
if let Some(marker) = self.spans.last_mut() {
marker.style = marker.style.add_modifier(Modifier::CROSSED_OUT);
}
}
if let Some(item) = self.items.last_mut() {
item.completed = *checked;
if !replaces_unordered_marker {
item.continuation_width += 2;
}
}
let style = if *checked {
self.theme.list.add_modifier(Modifier::CROSSED_OUT)
} else {
self.theme.list
};
let marker = match (replaces_unordered_marker, *checked) {
(true, true) => " ☑ ",
(true, false) => " ☐ ",
(false, true) => "☑ ",
(false, false) => "☐ ",
};
self.push(Span::styled(marker, style));
}
}
index += 1;
}
}
fn code_block(&mut self, info: Option<&str>, events: &[mbdown::SpannedEvent<'_>]) {
let source = events
.iter()
.filter_map(|item| match &item.event {
Event::Text(text)
| Event::Code(text)
| Event::Html(text)
| Event::InlineHtml(text) => Some(text.as_ref()),
_ => None,
})
.collect::<String>();
let language = info.and_then(code_language).unwrap_or("text");
if language.eq_ignore_ascii_case("mermaid") {
match self.mermaid(&source) {
Ok(()) => return,
Err(error) => {
self.code_source_with_status(language, &source, mermaid_error_status(&error));
return;
}
}
}
self.code_source(language, &source);
}
fn mermaid(&mut self, source: &str) -> Result<(), mermaid_text::Error> {
let quote_prefix = " ▌ ".repeat(self.quote_depth);
let quote_width = UnicodeWidthStr::width(quote_prefix.as_str());
let available = self.width.saturating_sub(quote_width).max(1);
let render = |width| {
mermaid_text::render_with_options(
source,
&mermaid_text::RenderOptions {
max_width: Some(width),
max_width_strict: true,
..mermaid_text::RenderOptions::default()
},
)
};
const MAX_LAYOUT_ATTEMPTS: usize = 8;
let mut requested = available;
let mut last_too_wide = None;
let mut diagram = None;
for _ in 0..MAX_LAYOUT_ATTEMPTS {
match render(requested) {
Ok(rendered) => {
diagram = Some(rendered);
break;
}
Err(error @ mermaid_text::Error::TooWide { actual, .. }) => {
last_too_wide = Some(error);
let Some(next) = next_mermaid_width(requested, actual) else {
break;
};
requested = next;
}
Err(error) => return Err(error),
}
}
let diagram = diagram.ok_or_else(|| {
last_too_wide.expect("a missing diagram must follow a too-wide render")
})?;
let style = self
.theme
.get("markdown-mermaid")
.unwrap_or(self.theme.code);
let diagram_width = diagram
.lines()
.map(UnicodeWidthStr::width)
.max()
.unwrap_or(0);
let padding = available.saturating_sub(diagram_width) / 2;
self.blank();
for row in diagram.lines() {
let mut spans = Vec::with_capacity(3);
if !quote_prefix.is_empty() {
spans.push(Span::styled(quote_prefix.clone(), self.theme.quote));
}
if padding > 0 {
spans.push(Span::raw(" ".repeat(padding)));
}
spans.push(Span::styled(row.to_owned(), style));
self.lines.push(Line::from(spans));
}
self.blank();
Ok(())
}
fn front_matter(&mut self, front_matter: &mbdown::FrontMatter<'_>) {
let language = match front_matter.kind() {
mbdown::FrontMatterKind::Yaml => "yaml",
mbdown::FrontMatterKind::Toml => "toml",
};
let source = front_matter
.source()
.strip_suffix("\r\n")
.or_else(|| front_matter.source().strip_suffix(['\r', '\n']))
.unwrap_or_else(|| front_matter.source());
self.flush();
self.code_source(language, source);
self.blank();
}
fn display_math(&mut self, source: &str) {
let source = trim_math_block(source);
let quote_prefix = " ▌ ".repeat(self.quote_depth);
let quote_width = UnicodeWidthStr::width(quote_prefix.as_str());
let available = self.width.saturating_sub(quote_width).max(1);
let style = self.theme.get("markdown-math").unwrap_or(self.theme.code);
let Some((rows, math_width)) = terminal_math_lines(source, available) else {
self.flush();
self.code_source("tex", source);
self.blank();
return;
};
self.blank();
let padding = available.saturating_sub(math_width) / 2;
for row in rows {
let mut spans = Vec::with_capacity(3);
if !quote_prefix.is_empty() {
spans.push(Span::styled(quote_prefix.clone(), self.theme.quote));
}
if padding > 0 {
spans.push(Span::raw(" ".repeat(padding)));
}
spans.push(Span::styled(row, style));
self.lines.push(Line::from(spans));
}
self.blank();
}
fn code_source(&mut self, language: &str, source: &str) {
self.code_source_inner(language, source, None);
}
fn code_source_with_status(&mut self, language: &str, source: &str, status: &str) {
self.code_source_inner(language, source, Some(status));
}
fn code_source_inner(&mut self, language: &str, source: &str, status: Option<&str>) {
let quote_prefix = " ▌ ".repeat(self.quote_depth);
let quote_width = UnicodeWidthStr::width(quote_prefix.as_str());
let block_width = self.width.saturating_sub(quote_width).max(1);
let padding = 2.min(block_width.saturating_sub(1) / 2);
let lines = if matches!(language.to_ascii_lowercase().as_str(), "diff" | "patch") {
diff_code_lines(source, self.theme.code_block)
} else {
highlighted_code_lines(source, language, self.theme.code_block)
.unwrap_or_else(|| plain_code_lines(source, self.theme.code_block))
};
let number_width = lines.len().max(1).to_string().len();
let available = block_width.saturating_sub(padding * 2).max(1);
let gutter_width = (number_width + 3).min(available.saturating_sub(1));
let content_width = available.saturating_sub(gutter_width).max(1);
let label_style = self.theme.code_block.patch(self.theme.code_label);
let mut label_spans = vec![Span::styled(" ".repeat(padding), self.theme.code_block)];
if let Some(status) = status {
let status_label = truncate_to_width(status, available);
let status_width = UnicodeWidthStr::width(status_label.as_str());
let language_budget = available.saturating_sub(status_width.saturating_add(1));
let language_label = truncate_to_width(language, language_budget);
let language_width = UnicodeWidthStr::width(language_label.as_str());
if !language_label.is_empty() {
label_spans.push(Span::styled(language_label, label_style));
}
let gap = available.saturating_sub(language_width + status_width);
if gap > 0 {
label_spans.push(Span::styled(" ".repeat(gap), self.theme.code_block));
}
label_spans.push(Span::styled(status_label, label_style));
label_spans.push(Span::styled(" ".repeat(padding), self.theme.code_block));
} else {
label_spans.push(Span::styled(
truncate_to_width(language, available),
label_style,
));
}
let label = Line::from(label_spans);
self.push_code_block_line(Line::default(), "e_prefix, block_width);
self.push_code_block_line(label, "e_prefix, block_width);
self.push_code_block_line(Line::default(), "e_prefix, block_width);
for (line_index, line) in lines.into_iter().enumerate() {
let wrapped = if line.spans.is_empty() {
vec![Vec::new()]
} else {
wrap_spans(&line.spans, content_width)
};
for (wrap_index, spans) in wrapped.into_iter().enumerate() {
let gutter = if wrap_index == 0 {
truncate_to_width(
&format!("{:>number_width$} │ ", line_index + 1),
gutter_width,
)
} else {
" ".repeat(gutter_width)
};
let mut padded = vec![
Span::styled(" ".repeat(padding), self.theme.code_block),
Span::styled(
pad_to_width(gutter, gutter_width),
self.theme.code_block.patch(self.theme.code_label),
),
];
padded.extend(spans);
self.push_code_block_line(Line::from(padded), "e_prefix, block_width);
}
}
self.push_code_block_line(Line::default(), "e_prefix, block_width);
}
fn push_code_block_line(
&mut self,
mut line: Line<'static>,
quote_prefix: &str,
block_width: usize,
) {
apply_style_to_width(&mut line, self.theme.code_block, block_width);
if !quote_prefix.is_empty() {
line.spans
.insert(0, Span::styled(quote_prefix.to_string(), self.theme.quote));
}
self.lines.push(line);
}
fn table(
&mut self,
alignments: &[Alignment],
events: &[mbdown::SpannedEvent<'_>],
source_offset: usize,
) {
let mut rows: Vec<(bool, Vec<Vec<Span<'static>>>)> = Vec::new();
let mut header = false;
let mut cells = Vec::new();
let mut cell_start = None;
for (index, item) in events.iter().enumerate() {
match item.event {
Event::Start(Container::TableHead) => {
header = true;
cells.clear();
}
Event::Start(Container::TableRow) => cells.clear(),
Event::Start(Container::TableCell) => cell_start = Some(index + 1),
Event::End(ContainerEnd::TableCell) => {
let start = cell_start.take().unwrap_or(index);
let mut cell = Output::new(usize::MAX / 4, self.theme, 0);
cell.markdown(&events[start..index], source_offset);
cell.flush();
let mut spans = Vec::new();
for (line_index, line) in cell.lines.into_iter().enumerate() {
if line_index > 0 {
spans.push(Span::raw(" "));
}
spans.extend(line.spans);
}
self.pending_semantics.extend(cell.pending_semantics);
cells.push(spans);
}
Event::End(ContainerEnd::TableRow) if !header => {
rows.push((false, cells.clone()));
}
Event::End(ContainerEnd::TableHead) => {
rows.push((true, cells.clone()));
cells.clear();
header = false;
}
_ => {}
}
}
let columns = alignments
.len()
.max(rows.iter().map(|(_, cells)| cells.len()).max().unwrap_or(0));
if columns == 0 {
return;
}
let padding = usize::from(self.width > columns.saturating_mul(3));
let overhead = columns + 1 + padding * 2 * columns;
let available = self.width.saturating_sub(overhead).max(columns);
let mut natural = vec![1; columns];
for (_, cells) in &rows {
for (column, cell) in cells.iter().enumerate() {
natural[column] = natural[column].max(spans_width(cell));
}
}
let widths = allocate_widths(&natural, available);
self.lines.push(Line::raw(table_border(
&widths,
padding,
self.theme.corner_style.top_left(),
'┬',
self.theme.corner_style.top_right(),
'─',
)));
for (row_index, (is_header, cells)) in rows.iter().enumerate() {
let wrapped: Vec<_> = (0..columns)
.map(|column| {
wrap_spans(
cells.get(column).map(Vec::as_slice).unwrap_or_default(),
widths[column],
)
})
.collect();
let height = wrapped.iter().map(Vec::len).max().unwrap_or(1);
for line_index in 0..height {
let mut line = vec![Span::raw("│")];
for column in 0..columns {
line.extend(std::iter::repeat_n(Span::raw(" "), padding));
let content = wrapped[column].get(line_index).cloned().unwrap_or_default();
let content_width = spans_width(&content);
let remaining = widths[column].saturating_sub(content_width);
let alignment = alignments.get(column).copied().unwrap_or(Alignment::None);
let left = match alignment {
Alignment::Right => remaining,
Alignment::Center => remaining / 2,
Alignment::None | Alignment::Left => 0,
};
let right = remaining - left;
if left > 0 {
line.push(Span::raw(" ".repeat(left)));
}
line.extend(content);
if right > 0 {
line.push(Span::raw(" ".repeat(right)));
}
line.extend(std::iter::repeat_n(Span::raw(" "), padding));
line.push(Span::raw("│"));
}
self.lines.push(Line::from(line));
}
if *is_header && row_index + 1 < rows.len() {
self.lines.push(Line::raw(table_border(
&widths, padding, '├', '┼', '┤', '─',
)));
}
}
self.lines.push(Line::raw(table_border(
&widths,
padding,
self.theme.corner_style.bottom_left(),
'┴',
self.theme.corner_style.bottom_right(),
'─',
)));
}
fn start(&mut self, container: &Container<'_>) {
match container {
Container::Heading(level) => {
self.flush();
let (prefix, style) = self.theme.heading(*level);
self.push(Span::styled(prefix, style));
self.styles
.push(("markdown-heading".into(), self.style().patch(style)));
}
Container::Strong => {
self.styles.push((
"markdown-bold".into(),
self.style().add_modifier(Modifier::BOLD),
));
}
Container::Emphasis => {
self.styles.push((
"markdown-italic".into(),
self.style().add_modifier(Modifier::ITALIC),
));
}
Container::Strikethrough => {
self.styles.push((
"markdown-strike".into(),
self.style().add_modifier(Modifier::CROSSED_OUT),
));
}
Container::CodeBlock(_) => {
self.flush();
self.styles
.push(("markdown-code-block".into(), self.theme.code));
}
Container::BlockQuote => self.quote_depth += 1,
Container::List(first) => self.lists.push(*first),
Container::Item => {
self.flush();
let ancestor_indent = self.items.last().map_or(0, |item| item.continuation_width);
let marker = match self.lists.last_mut() {
Some(Some(next)) => {
let marker = format!(" {next}. ");
*next += 1;
marker
}
_ => " • ".to_string(),
};
self.items.push(ItemState {
continuation_width: ancestor_indent + UnicodeWidthStr::width(marker.as_str()),
..ItemState::default()
});
if ancestor_indent > 0 {
self.push(Span::styled(" ".repeat(ancestor_indent), self.theme.list));
}
self.push(Span::styled(marker, self.theme.list));
}
Container::Link { .. } => {
self.styles
.push(("markdown-link".into(), self.style().patch(self.theme.link)));
}
Container::Image { .. } => {}
_ => {}
}
}
fn end(&mut self, container: ContainerEnd) {
match container {
ContainerEnd::Heading => {
self.styles.pop();
self.blank();
}
ContainerEnd::CodeBlock => {
self.flush();
self.styles.pop();
self.blank();
}
ContainerEnd::Strong
| ContainerEnd::Emphasis
| ContainerEnd::Strikethrough
| ContainerEnd::Link => {
self.styles.pop();
}
ContainerEnd::Paragraph => self.blank(),
ContainerEnd::BlockQuote => {
self.flush();
self.quote_depth = self.quote_depth.saturating_sub(1);
self.blank();
}
ContainerEnd::List(_) => {
self.lists.pop();
if self.lists.is_empty() {
self.blank();
} else {
self.flush();
}
}
ContainerEnd::Item => {
self.flush();
self.items.pop();
}
_ => {}
}
}
fn text(&mut self, text: &str) {
for (index, part) in text.split('\n').enumerate() {
if index > 0 {
self.flush();
}
if !part.is_empty() {
self.push(Span::styled(part.to_string(), self.style()));
}
}
}
fn inline_tag(&mut self, tag: &InlineTag<'_>) {
if tag.closing {
if self
.styles
.last()
.is_some_and(|(active, _)| tag.name.is_empty() || active == &tag.name)
&& self.styles.len() > 1
{
self.styles.pop();
} else {
self.text(&tag.raw);
}
} else if tag.name == "br" && tag.value.is_none() {
self.flush();
} else if tag.name == "reset" && tag.value.is_none() {
self.styles.truncate(1);
} else if let Some(style) = self.inline_style(&tag.name, tag.value.as_deref()) {
self.styles.push((tag.name.clone(), style));
} else {
self.text(&tag.raw);
}
}
fn inline_style(&self, name: &str, value: Option<&str>) -> Option<Style> {
let style = self.style();
Some(match (name, value) {
("b" | "bold", None) => style.add_modifier(Modifier::BOLD),
("dim", None) => style.add_modifier(Modifier::DIM),
("i" | "italic", None) => style.add_modifier(Modifier::ITALIC),
("u" | "underline", None | Some("single")) => style.add_modifier(Modifier::UNDERLINED),
("u" | "underline", Some("double" | "curly" | "dotted" | "dashed")) => {
style.add_modifier(Modifier::UNDERLINED)
}
("underline-color", Some(_)) | ("overline", None) => style,
("blink", None | Some("slow")) => style.add_modifier(Modifier::SLOW_BLINK),
("blink", Some("rapid")) => style.add_modifier(Modifier::RAPID_BLINK),
("s" | "strike", None) => style.add_modifier(Modifier::CROSSED_OUT),
("inverse", None) => style.add_modifier(Modifier::REVERSED),
("link", Some(_)) => style.patch(self.theme.link),
("color" | "fg", Some(value)) => {
style.fg(parse_color(value).or_else(|| self.theme.get(value)?.fg)?)
}
("bg", Some(value)) => {
style.bg(parse_color(value).or_else(|| self.theme.get(value)?.bg)?)
}
(name, None) => {
if let Some(color) = parse_color(name) {
style.fg(color)
} else {
style.patch(self.theme.get(name)?)
}
}
_ => return None,
})
}
fn style(&self) -> Style {
let style = self.styles.last().expect("base style").1;
if self.items.last().is_some_and(|item| item.completed) {
style.add_modifier(Modifier::CROSSED_OUT)
} else {
style
}
}
fn push(&mut self, span: Span<'static>) {
if self.spans.is_empty() {
if self.quote_depth > 0 {
self.spans.push(Span::styled(
" ▌ ".repeat(self.quote_depth),
self.theme.quote,
));
}
if let Some(item) = self.items.last_mut().filter(|item| item.continues) {
self.spans.push(Span::styled(
" ".repeat(item.continuation_width),
self.theme.list,
));
item.continues = false;
}
}
self.spans.push(span);
}
fn semantic(
&mut self,
kind: SemanticKind,
source_span: Range<usize>,
text: String,
style: Style,
) {
self.pending_semantics.push(PendingSemantic {
kind,
source_span,
style,
});
self.push(Span::raw(SEMANTIC_START));
self.push(Span::styled(text, style));
self.push(Span::raw(SEMANTIC_END));
}
fn flush(&mut self) {
if !self.spans.is_empty() {
self.lines.push(Line::from(std::mem::take(&mut self.spans)));
}
}
fn blank(&mut self) {
self.flush();
if self.lines.last().is_some_and(|line| !line.spans.is_empty()) {
self.lines.push(Line::default());
}
}
fn finish(mut self) -> RenderedLines {
self.flush();
let reserved_rows = self
.images
.iter()
.map(|image| image.row.saturating_add(image.height))
.max()
.unwrap_or(0);
while self.lines.len() > reserved_rows
&& self.lines.last().is_some_and(|line| line.spans.is_empty())
{
self.lines.pop();
}
let mut lines = Vec::new();
let mut row_map = Vec::with_capacity(self.lines.len());
for (source_row, line) in self.lines.into_iter().enumerate() {
debug_assert_eq!(row_map.len(), source_row);
row_map.push(lines.len());
if line.spans.is_empty() {
lines.push(line);
} else {
lines.extend(
wrap_line_spans(&line.spans, self.width)
.into_iter()
.map(Line::from),
);
}
}
for image in &mut self.images {
image.row = row_map.get(image.row).copied().unwrap_or(lines.len());
}
for semantic in &mut self.semantics {
for region in &mut semantic.regions {
region.row = row_map.get(region.row).copied().unwrap_or(lines.len());
}
}
self.semantics
.extend(resolve_semantics(&mut lines, self.pending_semantics));
RenderedLines {
lines,
images: self.images,
semantics: self.semantics,
}
}
}
fn child_output(
width: usize,
theme: &Theme,
children: &[Node<'_>],
image_height: usize,
) -> RenderedLines {
let mut output = Output::new(width.max(1), theme, image_height);
output.nodes(children);
output.finish()
}
fn render_column_output(
column: &mbdown::ColumnSpec,
children: &[Node<'_>],
width: usize,
parent_bg: Option<Color>,
theme: &Theme,
image_height: usize,
) -> RenderedLines {
let background = column
.bg
.as_deref()
.and_then(|value| parse_color(value).or_else(|| theme.get(value)?.bg))
.or(parent_bg);
let style = background.map_or_else(Style::default, |bg| Style::default().bg(bg));
let padding = constrained_padding(width, column.padding);
let content_width = width.saturating_sub(padding.x.saturating_mul(2)).max(1);
pad_rendered(
child_output(content_width, theme, children, image_height),
width,
padding,
style,
)
}
fn constrained_padding(width: usize, padding: mbdown::Padding) -> mbdown::Padding {
mbdown::Padding {
x: padding.x.min(width.saturating_sub(1) / 2),
y: padding.y,
}
}
fn pad_lines(
lines: Vec<Line<'static>>,
width: usize,
padding: mbdown::Padding,
style: Style,
) -> Vec<Line<'static>> {
let mut output = Vec::with_capacity(lines.len() + padding.y.saturating_mul(2));
for _ in 0..padding.y {
output.push(Line::from(Span::styled(" ".repeat(width), style)));
}
for mut line in lines {
line.spans
.insert(0, Span::styled(" ".repeat(padding.x), style));
apply_style_to_width(&mut line, style, width);
output.push(line);
}
for _ in 0..padding.y {
output.push(Line::from(Span::styled(" ".repeat(width), style)));
}
output
}
fn pad_rendered(
mut rendered: RenderedLines,
width: usize,
padding: mbdown::Padding,
style: Style,
) -> RenderedLines {
for image in &mut rendered.images {
image.row += padding.y;
image.column += padding.x;
}
for semantic in &mut rendered.semantics {
semantic.offset(padding.y, padding.x);
}
RenderedLines {
lines: pad_lines(rendered.lines, width, padding, style),
images: rendered.images,
semantics: rendered.semantics,
}
}
fn resolve_semantics(
lines: &mut [Line<'static>],
pending: Vec<PendingSemantic>,
) -> Vec<SemanticPlacement> {
let mut pending = pending.into_iter();
let mut current = None;
let mut resolved = Vec::new();
for (row, line) in lines.iter_mut().enumerate() {
let mut column = 0usize;
line.spans.retain(|span| {
if span.content == SEMANTIC_START {
current = pending.next().map(|semantic| (semantic, Vec::new()));
return false;
}
if span.content == SEMANTIC_END {
if let Some((semantic, regions)) = current.take() {
resolved.push(SemanticPlacement {
kind: semantic.kind,
source_span: semantic.source_span,
regions,
});
}
return false;
}
let width = UnicodeWidthStr::width(span.content.as_ref());
if let Some((semantic, regions)) = &mut current {
if span.style == semantic.style && width > 0 {
regions.push(CellRegion { row, column, width });
}
}
column += width;
true
});
}
resolved
}
fn apply_background(line: &mut Line<'static>, background: Color, width: usize) {
for span in &mut line.spans {
span.style = span.style.bg(background);
}
let remaining = width.saturating_sub(spans_width(&line.spans));
if remaining > 0 {
line.spans.push(Span::styled(
" ".repeat(remaining),
Style::default().bg(background),
));
}
}
fn apply_style_to_width(line: &mut Line<'static>, style: Style, width: usize) {
for span in &mut line.spans {
span.style = style.patch(span.style);
}
let remaining = width.saturating_sub(spans_width(&line.spans));
if remaining > 0 {
line.spans.push(Span::styled(" ".repeat(remaining), style));
}
}
fn truncate_to_width(value: &str, width: usize) -> String {
let mut used = 0;
UnicodeSegmentation::graphemes(value, true)
.take_while(|grapheme| {
let grapheme_width = UnicodeWidthStr::width(*grapheme);
if used + grapheme_width > width {
false
} else {
used += grapheme_width;
true
}
})
.collect()
}
fn pad_to_width(mut value: String, width: usize) -> String {
let remaining = width.saturating_sub(UnicodeWidthStr::width(value.as_str()));
value.push_str(&" ".repeat(remaining));
value
}
fn parse_color(value: &str) -> Option<Color> {
let normalized = value.trim().to_ascii_lowercase();
Some(match normalized.as_str() {
"black" => Color::Black,
"red" => Color::Red,
"green" => Color::Green,
"yellow" => Color::Yellow,
"blue" => Color::Blue,
"magenta" => Color::Magenta,
"cyan" => Color::Cyan,
"white" => Color::White,
"gray" | "grey" => Color::DarkGray,
"bright-red" => Color::LightRed,
"bright-green" => Color::LightGreen,
"bright-yellow" => Color::LightYellow,
"bright-blue" => Color::LightBlue,
"bright-magenta" => Color::LightMagenta,
"bright-cyan" => Color::LightCyan,
"bright-white" => Color::White,
_ if normalized.starts_with('#') && normalized.len() == 7 => Color::Rgb(
u8::from_str_radix(&normalized[1..3], 16).ok()?,
u8::from_str_radix(&normalized[3..5], 16).ok()?,
u8::from_str_radix(&normalized[5..7], 16).ok()?,
),
_ => Color::Indexed(normalized.parse().ok()?),
})
}
fn matching_table_end(events: &[mbdown::SpannedEvent<'_>], start: usize) -> usize {
let mut depth = 0;
for (index, item) in events.iter().enumerate().skip(start) {
match item.event {
Event::Start(Container::Table(_)) => depth += 1,
Event::End(ContainerEnd::Table) => {
depth -= 1;
if depth == 0 {
return index;
}
}
_ => {}
}
}
events.len().saturating_sub(1)
}
fn matching_code_block_end(events: &[mbdown::SpannedEvent<'_>], start: usize) -> usize {
events
.iter()
.enumerate()
.skip(start + 1)
.find_map(|(index, item)| {
matches!(item.event, Event::End(ContainerEnd::CodeBlock)).then_some(index)
})
.unwrap_or_else(|| events.len().saturating_sub(1))
}
fn matching_image_end(events: &[mbdown::SpannedEvent<'_>], start: usize) -> usize {
events
.iter()
.enumerate()
.skip(start + 1)
.find_map(|(index, item)| {
matches!(item.event, Event::End(ContainerEnd::Image)).then_some(index)
})
.unwrap_or_else(|| events.len().saturating_sub(1))
}
fn image_alt_text(events: &[mbdown::SpannedEvent<'_>]) -> String {
events
.iter()
.filter_map(|item| match &item.event {
Event::Text(text) | Event::Code(text) => Some(text.as_ref()),
Event::SoftBreak | Event::HardBreak => Some(" "),
_ => None,
})
.collect::<String>()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}
fn is_image_embed(target: &str) -> bool {
std::path::Path::new(target)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
matches!(
extension.to_ascii_lowercase().as_str(),
"png" | "jpg" | "jpeg" | "gif" | "webp"
)
})
}
fn code_language(info: &str) -> Option<&str> {
let language = info
.split_whitespace()
.next()?
.trim_matches(|character| matches!(character, '{' | '}' | '.'));
(!language.is_empty()).then_some(language)
}
fn next_mermaid_width(requested: usize, actual: usize) -> Option<usize> {
if requested <= 1 {
return None;
}
let proportional = requested
.saturating_mul(requested)
.checked_div(actual.max(1))
.unwrap_or(1);
let geometric = requested.saturating_mul(3) / 4;
Some(proportional.min(geometric).clamp(1, requested - 1))
}
fn mermaid_error_status(error: &mermaid_text::Error) -> &'static str {
match error {
mermaid_text::Error::UnsupportedDiagram(_) => "unsupported",
mermaid_text::Error::ParseError(message) if message.contains("not yet supported") => {
"unsupported"
}
mermaid_text::Error::ParseError(_) | mermaid_text::Error::EmptyInput => "syntax error",
mermaid_text::Error::TooWide { .. } => "too wide",
}
}
fn trim_math_block(source: &str) -> &str {
let source = source
.strip_prefix("\r\n")
.or_else(|| source.strip_prefix(['\r', '\n']))
.unwrap_or(source);
source
.strip_suffix("\r\n")
.or_else(|| source.strip_suffix(['\r', '\n']))
.unwrap_or(source)
}
fn terminal_math_lines(source: &str, available: usize) -> Option<(Vec<String>, usize)> {
let compatible = txm_compatible_source(source)?;
let rendered = strip_ansi_escapes::strip_str(txm::render(&compatible.encoded).ok()?);
let rendered = compatible.restore(rendered);
let width = rendered.lines().map(UnicodeWidthStr::width).max()?;
if width == 0 || width > available {
return None;
}
let rows = rendered
.lines()
.map(|line| line.trim_end_matches(' ').to_string())
.collect();
Some((rows, width))
}
struct TxmSource {
encoded: String,
replacements: Vec<(char, String)>,
}
impl TxmSource {
fn restore(&self, rendered: String) -> String {
let mut rendered = rendered.replace(TXM_WIDE_FILLER, "");
for (placeholder, grapheme) in &self.replacements {
rendered = rendered.replace(*placeholder, grapheme);
}
rendered
}
}
fn txm_compatible_source(source: &str) -> Option<TxmSource> {
let mut output = String::with_capacity(source.len());
let mut replacements = Vec::new();
let mut cursor = 0;
while cursor < source.len() {
if source.as_bytes()[cursor] != b'\\' {
let grapheme = source[cursor..]
.graphemes(true)
.next()
.expect("cursor remains on a UTF-8 boundary");
push_txm_grapheme(source, &mut output, &mut replacements, grapheme)?;
cursor += grapheme.len();
continue;
}
if source.as_bytes().get(cursor + 1) == Some(&b'\\') {
output.push_str("\\\\");
cursor += 2;
continue;
}
let command_start = cursor + 1;
let command_end = source.as_bytes()[command_start..]
.iter()
.position(|byte| !byte.is_ascii_alphabetic())
.map_or(source.len(), |offset| command_start + offset);
let mut argument_start = command_end;
while source
.as_bytes()
.get(argument_start)
.is_some_and(u8::is_ascii_whitespace)
{
argument_start += 1;
}
let command = &source[command_start..command_end];
if matches!(command, "text" | "operatorname")
&& source.as_bytes().get(argument_start) == Some(&b'{')
{
output.push_str("\\mathrm");
cursor = command_end;
continue;
}
output.push('\\');
cursor += 1;
}
Some(TxmSource {
encoded: output,
replacements,
})
}
fn push_txm_grapheme(
source: &str,
output: &mut String,
replacements: &mut Vec<(char, String)>,
grapheme: &str,
) -> Option<()> {
let width = UnicodeWidthStr::width(grapheme);
let scalar_count = grapheme.chars().count();
if scalar_count <= width {
output.push_str(grapheme);
output.extend(std::iter::repeat_n(TXM_WIDE_FILLER, width - scalar_count));
return Some(());
}
if width == 0 {
return Some(());
}
let placeholder = ('\u{e000}'..='\u{f8ff}').find(|candidate| {
!source.contains(*candidate)
&& replacements
.iter()
.all(|(existing, _)| existing != candidate)
})?;
output.push(placeholder);
output.extend(std::iter::repeat_n(TXM_WIDE_FILLER, width - 1));
replacements.push((placeholder, grapheme.to_string()));
Some(())
}
struct SyntaxAssets {
syntaxes: SyntaxSet,
theme: SyntaxTheme,
}
fn syntax_assets() -> &'static SyntaxAssets {
static ASSETS: OnceLock<SyntaxAssets> = OnceLock::new();
ASSETS.get_or_init(|| {
let syntaxes = SyntaxSet::load_defaults_newlines();
let mut themes = ThemeSet::load_defaults().themes;
let theme = themes
.remove("base16-ocean.dark")
.expect("syntect default theme");
SyntaxAssets { syntaxes, theme }
})
}
fn highlighted_code_lines(source: &str, language: &str, base: Style) -> Option<Vec<Line<'static>>> {
let assets = syntax_assets();
let syntax = assets.syntaxes.find_syntax_by_token(language)?;
let mut highlighter = HighlightLines::new(syntax, &assets.theme);
let mut lines = Vec::new();
for line in LinesWithEndings::from(source) {
let ranges = highlighter.highlight_line(line, &assets.syntaxes).ok()?;
let spans = ranges
.into_iter()
.filter_map(|(style, text)| {
let text = text.trim_end_matches(['\r', '\n']);
(!text.is_empty())
.then(|| Span::styled(text.to_string(), syntax_style(style, base)))
})
.collect::<Vec<_>>();
lines.push(Line::from(spans));
}
Some(lines)
}
fn plain_code_lines(source: &str, style: Style) -> Vec<Line<'static>> {
let mut lines = source
.lines()
.map(|line| Line::from(Span::styled(line.to_string(), style)))
.collect::<Vec<_>>();
if lines.is_empty() && !source.is_empty() {
lines.push(Line::default());
}
lines
}
fn diff_code_lines(source: &str, base: Style) -> Vec<Line<'static>> {
let mut lines = source
.lines()
.map(|line| {
let style = if line.starts_with("+++") || line.starts_with("---") {
base.fg(catppuccin::YELLOW).add_modifier(Modifier::BOLD)
} else if line.starts_with("@@") {
base.fg(catppuccin::SAPPHIRE).add_modifier(Modifier::BOLD)
} else if line.starts_with('+') {
base.fg(catppuccin::GREEN)
} else if line.starts_with('-') {
base.fg(catppuccin::RED)
} else if line.starts_with("diff ")
|| line.starts_with("index ")
|| line.starts_with("new file ")
|| line.starts_with("deleted file ")
{
base.fg(catppuccin::OVERLAY_0).add_modifier(Modifier::BOLD)
} else {
base
};
Line::from(Span::styled(line.to_string(), style))
})
.collect::<Vec<_>>();
if lines.is_empty() && !source.is_empty() {
lines.push(Line::default());
}
lines
}
fn syntax_style(style: syntect::highlighting::Style, base: Style) -> Style {
let mut output = base.fg(nearest_catppuccin(style.foreground));
if style.font_style.contains(FontStyle::BOLD) {
output = output.add_modifier(Modifier::BOLD);
}
if style.font_style.contains(FontStyle::ITALIC) {
output = output.add_modifier(Modifier::ITALIC);
}
if style.font_style.contains(FontStyle::UNDERLINE) {
output = output.add_modifier(Modifier::UNDERLINED);
}
output
}
fn nearest_catppuccin(color: syntect::highlighting::Color) -> Color {
match (color.r, color.g, color.b) {
(191, 97, 106) => return catppuccin::RED,
(208, 135, 112) => return catppuccin::PEACH,
(235, 203, 139) => return catppuccin::YELLOW,
(163, 190, 140) => return catppuccin::GREEN,
(150, 181, 180) => return catppuccin::TEAL,
(143, 161, 179) => return catppuccin::BLUE,
(180, 142, 173) => return catppuccin::MAUVE,
_ => {}
}
catppuccin::SYNTAX
.into_iter()
.min_by_key(|candidate| {
let Color::Rgb(red, green, blue) = *candidate else {
unreachable!("Catppuccin syntax colors are RGB")
};
let red = i32::from(red) - i32::from(color.r);
let green = i32::from(green) - i32::from(color.g);
let blue = i32::from(blue) - i32::from(color.b);
red * red + green * green + blue * blue
})
.expect("Catppuccin syntax palette is not empty")
}
fn allocate_widths(natural: &[usize], available: usize) -> Vec<usize> {
let mut widths = vec![1; natural.len()];
let mut remaining = available.saturating_sub(natural.len());
while remaining > 0 {
let candidate = widths
.iter()
.enumerate()
.filter(|(index, width)| **width < natural[*index])
.min_by_key(|(_, width)| **width)
.map(|(index, _)| index);
let index = candidate.unwrap_or_else(|| {
widths
.iter()
.enumerate()
.min_by_key(|(_, width)| **width)
.map(|(index, _)| index)
.unwrap_or(0)
});
widths[index] += 1;
remaining -= 1;
}
widths
}
fn table_border(
widths: &[usize],
padding: usize,
left: char,
junction: char,
right: char,
fill: char,
) -> String {
let mut output = String::new();
output.push(left);
for (index, width) in widths.iter().enumerate() {
output.extend(std::iter::repeat_n(fill, width + padding * 2));
output.push(if index + 1 == widths.len() {
right
} else {
junction
});
}
output
}
fn spans_width(spans: &[Span<'_>]) -> usize {
spans
.iter()
.map(|span| UnicodeWidthStr::width(span.content.as_ref()))
.sum()
}
fn wrap_line_spans(spans: &[Span<'_>], width: usize) -> Vec<Vec<Span<'static>>> {
let quote = spans.first().filter(|span| {
span.content.contains('▌')
&& span
.content
.chars()
.all(|character| matches!(character, ' ' | '▌'))
});
let prefix_start = usize::from(quote.is_some());
let list_index = prefix_start
+ usize::from(spans.get(prefix_start).is_some_and(|span| {
!span.content.is_empty() && span.content.chars().all(|ch| ch == ' ')
}));
let list_prefix_count = spans
.get(list_index)
.filter(|span| is_list_marker(&span.content))
.map(|_| {
1 + usize::from(
spans
.get(list_index + 1)
.is_some_and(|span| is_task_marker(&span.content)),
)
})
.or_else(|| {
spans
.get(list_index)
.filter(|span| is_task_marker(&span.content))
.map(|_| 1)
})
.unwrap_or(0);
if quote.is_none() && list_prefix_count == 0 {
return wrap_spans(spans, width);
}
let content_start = list_index + list_prefix_count;
let quote_width = quote.map_or(0, |prefix| spans_width(std::slice::from_ref(prefix)));
let list_width = spans_width(&spans[prefix_start..content_start]);
let prefix_width = quote_width + list_width;
let mut lines = wrap_spans(
&spans[content_start..],
width.saturating_sub(prefix_width).max(1),
);
for (line_index, line) in lines.iter_mut().enumerate() {
if list_width > 0 {
if line_index == 0 {
for prefix in spans[prefix_start..content_start].iter().rev() {
line.insert(0, Span::styled(prefix.content.to_string(), prefix.style));
}
} else {
line.insert(
0,
Span::styled(" ".repeat(list_width), spans[prefix_start].style),
);
}
}
if let Some(prefix) = quote {
line.insert(0, Span::styled(prefix.content.to_string(), prefix.style));
}
}
lines
}
fn is_list_marker(content: &str) -> bool {
if content == " • " {
return true;
}
let Some(number) = content
.strip_prefix(' ')
.and_then(|value| value.strip_suffix(". "))
else {
return false;
};
!number.is_empty() && number.chars().all(|character| character.is_ascii_digit())
}
fn is_task_marker(content: &str) -> bool {
matches!(content, " ☐ " | " ☑ " | "☐ " | "☑ ")
}
fn wrap_spans(spans: &[Span<'_>], width: usize) -> Vec<Vec<Span<'static>>> {
let mut lines = vec![Vec::new()];
let mut current_width = 0;
for span in spans {
let mut fragment = String::new();
for grapheme in UnicodeSegmentation::graphemes(span.content.as_ref(), true) {
let grapheme_width = UnicodeWidthStr::width(grapheme);
if grapheme_width > 0 && current_width > 0 && current_width + grapheme_width > width {
if !fragment.is_empty() {
lines
.last_mut()
.expect("initial line")
.push(Span::styled(std::mem::take(&mut fragment), span.style));
}
lines.push(Vec::new());
current_width = 0;
}
fragment.push_str(grapheme);
current_width += grapheme_width;
}
if !fragment.is_empty() {
lines
.last_mut()
.expect("initial line")
.push(Span::styled(fragment, span.style));
}
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
fn plain(text: &Text<'_>) -> String {
text.lines
.iter()
.map(|line| {
line.spans
.iter()
.map(|span| span.content.as_ref())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn renders_directly_to_ratatui_with_inline_styles() {
let document = mbdown::parse("# Title\n\n[red][b]alert[/b][/red]").unwrap();
let text = Renderer::new(30).render(&document);
let alert = text
.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == "alert")
.unwrap();
assert_eq!(alert.style.fg, Some(Color::Red));
assert!(alert.style.add_modifier.contains(Modifier::BOLD));
}
#[test]
fn front_matter_is_returned_but_hidden_by_default() {
let source = "---\ntitle: Shown\ntags: [one, two]\n---\n# Visible";
let rendered = {
let document = mbdown::parse(source).unwrap();
Renderer::new(40).render(&document)
};
let text = plain(&rendered.text);
assert!(text.ends_with("◆ Visible"));
assert!(!text.contains("yaml"));
assert!(!text.contains("title: Shown"));
assert!(!text.contains("---"));
assert!(rendered.images.is_empty());
let metadata = rendered.front_matter.unwrap();
assert_eq!(metadata.kind, mbdown::FrontMatterKind::Yaml);
assert_eq!(metadata.source, "title: Shown\ntags: [one, two]\n");
assert_eq!(metadata.raw, "---\ntitle: Shown\ntags: [one, two]\n---\n");
assert_eq!(metadata.span, 0..metadata.raw.len());
}
#[test]
fn front_matter_can_be_rendered_as_a_labeled_metadata_block() {
let document =
mbdown::parse("---\ntitle: Shown\ntags: [one, two]\n---\n# Visible").unwrap();
let rendered = Renderer::new(40).with_front_matter(true).render(&document);
let text = plain(&rendered.text);
assert!(text.contains("yaml"));
assert!(text.contains("title: Shown"));
assert!(text.contains("tags: [one, two]"));
assert!(text.ends_with("◆ Visible"));
assert!(!text.contains("---"));
assert!(rendered.front_matter.is_some());
let document = mbdown::parse("+++\ntitle = \"Shown\"\n+++\nVisible").unwrap();
let text = plain(
&Renderer::new(40)
.with_front_matter(true)
.render(&document)
.text,
);
assert!(text.contains("toml"));
assert!(text.contains("title = \"Shown\""));
assert!(text.ends_with("Visible"));
assert!(!text.contains("+++"));
}
#[test]
fn math_has_native_display_and_source_fallbacks() {
let document = mbdown::parse("Inline $x + 1$.\n\n$$\n\\frac{a}{b}\n$$").unwrap();
let rendered = Renderer::new(40).render(&document);
let text = plain(&rendered.text);
assert!(text.contains("Inline $x + 1$."));
assert!(!text.contains("tex"));
assert!(text.contains('─'));
assert!(text.contains('a'));
assert!(text.contains('b'));
assert!(rendered.images.is_empty());
let document = mbdown::parse(concat!(
"$$\n",
"\\frac{\\text{营业收入}}{\\text{总资产}} \\times ",
"\\frac{\\text{净利润}}{\\text{营业收入}} = ",
"\\frac{\\text{净利润}}{\\text{总资产}} = ",
"\\operatorname{ROA}\n",
"$$"
))
.unwrap();
let labels = plain(&Renderer::new(80).render(&document).text);
assert!(labels.contains("营业收入"));
assert!(labels.contains("总资产"));
assert!(labels.contains("ROA"));
assert!(!labels.contains("text营业收入"));
assert!(!labels.contains("operatorname"));
assert!(labels.contains("──────────×────────── = ──────── = ROA"));
let document = mbdown::parse("$$\n\\frac{🧑💻👩💻}{👥} = \\text{程序员浓度}\n$$").unwrap();
let emoji = plain(&Renderer::new(80).render(&document).text);
assert!(emoji.contains("🧑💻👩💻"));
assert!(emoji.contains("👥"));
assert!(emoji.contains("────── = 程序员浓度"));
let equation = emoji
.lines()
.find(|line| line.contains("程序员浓度"))
.unwrap();
assert_eq!(equation.chars().filter(|ch| *ch == '─').count(), 6);
let document = mbdown::parse("$$\n\\left( x\n$$").unwrap();
let text = plain(&Renderer::new(40).render(&document).text);
assert!(text.contains("tex"));
assert!(text.contains("\\left( x"));
let document = mbdown::parse("$$\nabcdefghijk\n$$").unwrap();
let text = plain(&Renderer::new(10).render(&document).text);
assert!(text.contains("tex"));
assert!(text.contains('a'));
assert!(text.contains('k'));
}
#[test]
fn front_matter_offsets_following_image_placements() {
let document = mbdown::parse(concat!(
"---\n",
"title: Diagram\n",
"---\n",
""
))
.unwrap();
let hidden = Renderer::new(30).with_image_height(3).render(&document);
let rendered = Renderer::new(30)
.with_image_height(3)
.with_front_matter(true)
.render(&document);
assert_eq!(rendered.images.len(), 1);
let image_row = rendered.images[0].row;
assert!(hidden.images[0].row < image_row);
assert!(!plain(&hidden.text).contains("yaml"));
assert!(hidden.front_matter.is_some());
assert!(image_row >= 5);
let preceding = Text::from(rendered.text.lines[..image_row].to_vec());
assert!(plain(&preceding).contains("yaml"));
}
#[test]
fn markdown_images_reserve_rows_and_report_terminal_placement() {
let document = mbdown::parse(concat!(
"A paragraph long enough to wrap before the image.\n\n",
"\n\n",
"After"
))
.unwrap();
let rendered = Renderer::new(20).with_image_height(5).render(&document);
assert_eq!(rendered.images.len(), 1);
let image = &rendered.images[0];
assert_eq!(image.source, "https://example.com/diagram.png");
assert_eq!(image.title, "System");
assert_eq!(image.alt, "Architecture diagram");
assert_eq!((image.column, image.width, image.height), (0, 20, 5));
assert_eq!(rendered.lines[image.row].to_string(), "");
assert_eq!(rendered.lines[image.row + image.height - 1].to_string(), "");
assert_eq!(
rendered.lines[image.row + image.height].to_string(),
"After"
);
}
#[test]
fn image_embeds_use_image_placements_and_other_embeds_use_semantics() {
let image = Renderer::new(24)
.with_image_height(4)
.render(&mbdown::parse("![[assets/Cover.PNG]]").unwrap());
assert_eq!(image.images.len(), 1);
assert_eq!(image.images[0].source, "assets/Cover.PNG");
assert_eq!(image.images[0].alt, "assets/Cover.PNG");
assert_eq!(image.images[0].height, 4);
assert!(image.semantics.is_empty());
let source = "Open ![[attachments/report.pdf]]";
let file = Renderer::new(40).render(&mbdown::parse(source).unwrap());
assert!(plain(&file.text).contains("![[attachments/report.pdf]]"));
let embed = file
.semantics
.iter()
.find(|semantic| matches!(semantic.kind, SemanticKind::Embed { .. }))
.expect("Embed placement");
assert_eq!(
embed.kind,
SemanticKind::Embed {
target: "attachments/report.pdf".to_string()
}
);
assert_eq!(
&source[embed.source_span.clone()],
"![[attachments/report.pdf]]"
);
assert!(!embed.regions.is_empty());
}
#[test]
fn terminal_image_placements_follow_boxes_columns_and_document_end() {
let boxed =
mbdown::parse("[box width=20 border=single px=2 py=1][/box]")
.unwrap();
let boxed = Renderer::new(30).with_image_height(3).render(&boxed);
assert_eq!(boxed.images.len(), 1);
assert_eq!(
(
boxed.images[0].row,
boxed.images[0].column,
boxed.images[0].width,
boxed.images[0].height,
),
(2, 3, 14, 3)
);
assert_eq!(boxed.lines.len(), 7);
let columns = mbdown::parse(concat!(
"[columns gap=2]",
"[column width=10][/column]",
"[column width=10][/column]",
"[/columns]"
))
.unwrap();
let columns = Renderer::new(22).with_image_height(2).render(&columns);
assert_eq!(
columns.lines.len(),
2,
"terminal image rows must survive at EOF"
);
assert_eq!(columns.images.len(), 2);
assert_eq!((columns.images[0].row, columns.images[0].column), (0, 0));
assert_eq!((columns.images[1].row, columns.images[1].column), (0, 12));
}
#[test]
fn images_in_tables_fall_back_to_alt_text() {
let document = mbdown::parse(concat!(
"| Asset |\n",
"| --- |\n",
"|  |"
))
.unwrap();
let rendered = Renderer::new(40).render(&document);
assert!(rendered.images.is_empty());
assert!(rendered
.lines
.iter()
.any(|line| line.to_string().contains("[image] Architecture")));
}
#[test]
fn rounded_corners_apply_to_boxes_and_tables() {
let document = mbdown::parse(concat!(
"[box]box[/box]\n\n",
"| A | B |\n| --- | --- |\n| one | two |"
))
.unwrap();
let theme = Theme::default().with_corner_style(CornerStyle::Rounded);
let rendered = plain(&Renderer::with_theme(40, theme).render(&document));
assert_eq!(rendered.matches('╭').count(), 2, "{rendered:?}");
assert_eq!(rendered.matches('╮').count(), 2, "{rendered:?}");
assert_eq!(rendered.matches('╰').count(), 2, "{rendered:?}");
assert_eq!(rendered.matches('╯').count(), 2, "{rendered:?}");
}
#[test]
fn renders_hashtags_and_wikilinks_with_semantic_styles() {
let document = mbdown::parse("Related: #rust [[Language Notes]]").unwrap();
let text = Renderer::new(40).render(&document);
let hashtag = text
.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == "#rust")
.expect("hashtag span");
let wikilink = text
.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == "[[Language Notes]]")
.expect("wikilink span");
assert_eq!(hashtag.style, Theme::default().hashtag);
assert_eq!(wikilink.style, Theme::default().wikilink);
assert!(wikilink.style.add_modifier.contains(Modifier::UNDERLINED));
let table = Renderer::new(50).render(
&mbdown::parse("| Tag | Link |\n| --- | --- |\n| #rust | [[Language Notes]] |")
.unwrap(),
);
assert!(plain(&table).contains("#rust"));
assert!(plain(&table).contains("[[Language Notes]]"));
assert_eq!(table.semantics.len(), 2);
assert!(table
.semantics
.iter()
.all(|semantic| !semantic.regions.is_empty()));
}
#[test]
fn semantic_placements_follow_wrapping_and_layout_offsets() {
let source = "[box width=18 border=single px=1 py=1]> prefix #very-long-tag\n[/box]";
let document = mbdown::parse(source).unwrap();
let rendered = Renderer::new(24).render(&document);
let hashtag = rendered
.semantics
.iter()
.find(|semantic| matches!(semantic.kind, SemanticKind::Hashtag { .. }))
.expect("Hashtag placement");
assert_eq!(
hashtag.kind,
SemanticKind::Hashtag {
name: "very-long-tag".to_string()
}
);
assert_eq!(&source[hashtag.source_span.clone()], "#very-long-tag");
assert!(hashtag.regions.len() >= 2, "the Hashtag should wrap");
assert!(hashtag
.regions
.iter()
.all(|region| region.row >= 2 && region.column >= 2));
assert_eq!(
hashtag
.regions
.iter()
.map(|region| region.width)
.sum::<usize>(),
UnicodeWidthStr::width("#very-long-tag")
);
assert!(!plain(&rendered.text).contains(SEMANTIC_START));
assert!(!plain(&rendered.text).contains(SEMANTIC_END));
}
#[test]
fn links_have_a_distinct_semantic_underline_color() {
let document = mbdown::parse(
"# heading\n\n[site](https://example.test) [link=https://example.test]bb[/link]",
)
.unwrap();
let text = Renderer::new(60).render(&document);
let find = |needle: &str| {
text.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == needle)
.expect("styled span")
};
assert_eq!(find("heading").style.underline_color, None);
assert_eq!(
find("site").style.underline_color,
Theme::default().link.underline_color
);
assert_eq!(
find("bb").style.underline_color,
Theme::default().link.underline_color
);
}
#[test]
fn note_table_and_rule_fill_available_width() {
let document = mbdown::parse("| A | B |\n| --- | ---: |\n| one | two |\n\n---").unwrap();
let text = Renderer::new(32).render(&document);
let output = plain(&text);
assert!(output
.lines()
.filter(|line| line.starts_with('┌'))
.all(|line| { UnicodeWidthStr::width(line) == 32 }));
assert!(output.lines().any(|line| line == "─".repeat(32)));
assert!(!output.contains('═'));
}
#[test]
fn emoji_table_rows_keep_the_same_terminal_width() {
let document = mbdown::parse(concat!(
"| 项目 | 内容 |\n",
"| --- | --- |\n",
"| **日期** | 2026年7月28日(周二) |\n",
"| **天气** | ☀️ **天晴 (Fine)** |\n",
"| **气温** | **24°C ~ 34°C** |\n",
"| **来源** | 香港天文台 7月27日12:15发布 |",
))
.unwrap();
let rendered = plain(&Renderer::new(60).render(&document));
assert!(
rendered
.lines()
.all(|line| UnicodeWidthStr::width(line) == 60),
"{rendered}"
);
}
#[test]
fn boxes_and_columns_apply_axis_padding() {
let document = mbdown::parse("[box width=12 px=2 py=1]x[/box]").unwrap();
let text = Renderer::new(20).render(&document);
assert_eq!(
plain(&text),
"┌──────────┐\n│ │\n│ x │\n│ │\n└──────────┘"
);
let document = mbdown::parse(concat!(
"[columns gap=1 px=1 py=1]",
"[column width=8 p=1]A[/column]",
"[column width=8 px=2 py=1]B[/column]",
"[/columns]"
))
.unwrap();
let text = Renderer::new(24).render(&document);
let rendered = plain(&text);
let lines = rendered.lines().collect::<Vec<_>>();
assert_eq!(lines.len(), 5);
assert!(lines[0].trim().is_empty());
assert!(lines[2].contains('A'));
assert!(lines[2].contains('B'));
assert!(lines[4].trim().is_empty());
assert!(lines.iter().all(|line| UnicodeWidthStr::width(*line) == 19));
}
#[test]
fn nested_box_unicode_background_stays_inside_its_frame() {
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::widgets::{Paragraph, Widget};
let document = mbdown::parse(concat!(
"[box title=outer width=full border=single bg=16 px=2 py=1]\n",
"[box title=inner width=36 border=single bg=17 px=1 py=1]\n",
"**🃏 扑克花色** ♠ ♡ ♢ ♣ ♤ ♥ ♦ ♧\n\n",
"**♟ 棋类** ♔♕♖♗♘♙ ♚♛♜♝♞♟ ☖☗ 🀆🀅🀄\n\n",
"**🎲 骰子** ⚀ ⚁ ⚂ ⚃ ⚄ ⚅\n\n",
"**☯ 哲学符号** ☯ ☰ ☱ ☲ ☳ ☴ ☵ ☶ ☷ ⚊ ⚋ ⚌ ⚍ ⚎ ⚏\n",
"[/box]\n[/box]",
))
.unwrap();
assert_eq!(UnicodeWidthStr::width("☰"), 2);
assert_eq!(UnicodeWidthStr::width("⚊"), 2);
assert_eq!(UnicodeWidthStr::width("☀️"), 2);
let text = Renderer::new(80).render(&document);
let height = u16::try_from(text.lines.len()).unwrap();
let area = Rect::new(0, 0, 80, height);
let mut buffer = Buffer::empty(area);
Paragraph::new(text.text).render(area, &mut buffer);
for y in 0..height {
let blue_cells = (0..80)
.filter(|&x| buffer[(x, y)].bg == Color::Indexed(17))
.collect::<Vec<_>>();
if let (Some(first), Some(last)) = (blue_cells.first(), blue_cells.last()) {
assert_eq!((*first, *last), (3, 38), "blue overflow on row {y}");
}
}
}
#[test]
fn note_quotes_use_prominent_bar() {
let document = mbdown::parse("> quoted").unwrap();
assert_eq!(plain(&Renderer::new(20).render(&document)), " ▌ quoted");
}
#[test]
fn headings_have_scannable_level_prefixes_and_styles() {
let document = mbdown::parse("# One\n\n## Two\n\n### Three\n\n#### Four").unwrap();
let text = Renderer::new(30).render(&document);
assert_eq!(plain(&text), "◆ One\n\n◇ Two\n\n› Three\n\n· Four");
let headings: Vec<_> = text
.lines
.iter()
.filter_map(|line| line.spans.first())
.filter(|span| ["◆ ", "◇ ", "› ", "· "].contains(&span.content.as_ref()))
.collect();
assert_eq!(headings.len(), 4);
assert!(headings[0]
.style
.add_modifier
.contains(Modifier::UNDERLINED));
}
#[test]
fn fenced_code_blocks_use_language_aware_syntax_colors() {
let document = mbdown::parse("```rust\nfn main() {\n let answer = 42;\n}\n```").unwrap();
let text = Renderer::new(40).render(&document);
let rendered = plain(&text);
let lines = rendered.lines().collect::<Vec<_>>();
assert_eq!(lines.len(), 7);
assert!(lines[0].trim().is_empty());
assert_eq!(lines[1].trim_end(), " rust");
assert!(lines[2].trim().is_empty());
assert_eq!(lines[3].trim_end(), " 1 │ fn main() {");
assert_eq!(lines[4].trim_end(), " 2 │ let answer = 42;");
assert_eq!(lines[5].trim_end(), " 3 │ }");
assert!(lines[6].trim().is_empty());
assert!(lines.iter().all(|line| UnicodeWidthStr::width(*line) == 40));
assert!(text
.lines
.iter()
.flat_map(|line| &line.spans)
.all(|span| span.style.bg == Theme::default().code_block.bg));
let label = text
.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == "rust")
.expect("language label");
assert_eq!(label.style.fg, Some(catppuccin::OVERLAY_1));
assert!(!label.style.add_modifier.contains(Modifier::BOLD));
let line_number = text
.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == "1 │ ")
.expect("line number");
assert_eq!(line_number.style.fg, Some(catppuccin::OVERLAY_1));
let keyword = text
.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == "fn")
.expect("Rust keyword span");
let function = text
.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == "main")
.expect("Rust function span");
assert_ne!(keyword.style.fg, function.style.fg);
assert_ne!(keyword.style.fg, Theme::default().code.fg);
}
#[test]
fn mermaid_width_retry_makes_bounded_adaptive_progress() {
assert_eq!(next_mermaid_width(100, 125), Some(75));
assert_eq!(next_mermaid_width(100, 200), Some(50));
assert_eq!(next_mermaid_width(2, usize::MAX), Some(1));
assert_eq!(next_mermaid_width(1, 2), None);
}
#[test]
fn mermaid_fences_render_as_width_bounded_unicode_diagrams() {
let source = "```mermaid\ngraph LR\n A[Draft] --> B[Published]\n```";
let document = mbdown::parse(source).unwrap();
let rendered = Renderer::new(40).render(&document);
let output = plain(&rendered.text);
assert!(output.contains("Draft"));
assert!(output.contains("Published"));
assert!(output.contains('┌'));
assert!(output.contains('▸'));
assert!(!output.contains("graph LR"));
assert!(!output.contains("mermaid"));
assert!(output
.lines()
.all(|line| UnicodeWidthStr::width(line) <= 40));
}
#[test]
fn mermaid_fences_use_one_shared_diagram_offset() {
let sources = [
"graph LR\n A[开始] --> B{条件判断}\n B -->|是| C(执行操作 A)\n B -->|否| D(执行操作 B)\n C --> E[结束]\n D --> E\n C --> F((检查点))\n F --> B\n",
"stateDiagram-v2\n [*] --> Idle\n Idle --> Processing: 接收任务\n Processing --> Running: 开始执行\n Running --> Success: 完成\n Running --> Error: 失败\n Success --> [*]\n Error --> Retry: 重试\n Retry --> Processing\n Error --> [*]: 放弃\n",
"mindmap\n root((Nole))\n 核心\n 编辑器\n MBDown 渲染\n Mermaid 图表\n BBCode 样式\n 文件管理\n data 笔记\n daily 日志\n archives 归档\n AI Agent\n 工具\n 文件读写\n 搜索\n 网络请求\n 记忆\n MEMORY.md\n 每日笔记\n 主题\n TOML 配置\n 自定义颜色\n",
];
for source in sources {
let width = 120;
let options = mermaid_text::RenderOptions {
max_width: Some(width),
max_width_strict: true,
..mermaid_text::RenderOptions::default()
};
let diagram = mermaid_text::render_with_options(source, &options).unwrap();
let diagram_width = diagram.lines().map(UnicodeWidthStr::width).max().unwrap();
let padding = " ".repeat((width - diagram_width) / 2);
let expected = diagram
.lines()
.map(|line| format!("{padding}{line}"))
.collect::<Vec<_>>();
let fenced = format!("```mermaid\n{source}```");
let document = mbdown::parse(&fenced).unwrap();
let rendered = Renderer::new(width).render(&document);
let actual = plain(&rendered.text)
.lines()
.map(str::to_owned)
.collect::<Vec<_>>();
assert!(
actual
.windows(expected.len())
.any(|window| window == expected),
"MBTUI changed Mermaid row coordinates:\n{actual:#?}"
);
}
}
#[test]
fn mermaid_fences_preserve_cjk_display_width() {
for (source, labels) in [
(
"```mermaid\nflowchart LR\n A[开始] --> B{是否满意?}\n B -->|否| C[继续改进]\n```",
&["开始", "是否满意?", "继续改进"][..],
),
(
"```mermaid\nsequenceDiagram\n participant U as 用户\n participant N as Nole\n U->>N: 输入指令\n N-->>U: 展示响应\n```",
&["用户", "输入指令", "展示响应"][..],
),
(
"```mermaid\ngantt\n dateFormat YYYY-MM-DD\n section 核心功能\n Markdown 支持: 2026-01-01, 30d\n AI 集成: 2026-01-15, 30d\n```",
&["核心功能", "Markdown 支持", "AI 集成"][..],
),
] {
let document = mbdown::parse(source).unwrap();
let rendered = Renderer::new(80).render(&document);
let output = plain(&rendered.text);
for label in labels {
assert!(output.contains(label), "missing {label:?}:\n{output}");
}
assert!(!output.contains("开 始"));
assert!(!output.contains("输 入"));
assert!(!output.contains("支 持"));
assert!(!output.contains("mermaid"));
assert!(output
.lines()
.all(|line| UnicodeWidthStr::width(line) <= 80));
}
}
#[test]
fn invalid_mermaid_fences_fall_back_to_source_code() {
let document = mbdown::parse("```mermaid\nnot-a-diagram\n```").unwrap();
let rendered = Renderer::new(40).render(&document);
let output = plain(&rendered.text);
assert!(output.contains("mermaid"));
assert!(output.contains("not-a-diagram"));
let label = output
.lines()
.find(|line| line.contains("mermaid"))
.unwrap();
assert!(label.trim_end().ends_with("unsupported"));
assert_eq!(UnicodeWidthStr::width(label), 40);
}
#[test]
fn mermaid_fallbacks_show_concise_statuses_without_parser_details() {
let unsupported =
mbdown::parse("```mermaid\nclassDiagram\nclass Agent~T~ {\n +run() T\n}\n```")
.unwrap();
let output = plain(&Renderer::new(80).render(&unsupported).text);
let label = output
.lines()
.find(|line| line.contains("mermaid"))
.unwrap();
assert!(label.trim_end().ends_with("unsupported"));
assert!(!output.contains("generics not yet supported"));
let invalid = mbdown::parse(
r#"```mermaid
pie showData
title Broken pie
"A" : 1
```"#,
)
.unwrap();
let output = plain(&Renderer::new(80).render(&invalid).text);
let label = output
.lines()
.find(|line| line.contains("mermaid"))
.unwrap();
assert!(label.trim_end().ends_with("syntax error"));
assert!(!output.contains("pie slice must start with a quoted label"));
}
#[test]
fn too_wide_mermaid_retries_a_compact_layout_before_falling_back() {
let source = concat!(
"```mermaid\n",
"erDiagram\n",
" NOTE ||--o{ TAG : has\n",
" NOTE ||--|| WORKSPACE : belongs_to\n",
" NOTE {\n",
" string path PK\n",
" string content\n",
" datetime created_at\n",
" datetime modified_at\n",
" int line_count\n",
" }\n",
" TAG {\n",
" string name PK\n",
" int doc_count\n",
" int mention_count\n",
" }\n",
" WORKSPACE {\n",
" string root PK\n",
" string theme\n",
" }\n",
"```",
);
let document = mbdown::parse(source).unwrap();
let output = plain(&Renderer::new(90).render(&document).text);
assert!(output.contains("NOTE"));
assert!(output.contains("WORKSPACE"));
assert!(!output.contains("erDiagram"));
assert!(!output.contains("Mermaid needs"));
assert!(output
.lines()
.all(|line| UnicodeWidthStr::width(line) <= 90));
let output = plain(&Renderer::new(60).render(&document).text);
assert!(output.contains("erDiagram"));
let label = output
.lines()
.find(|line| line.contains("mermaid"))
.unwrap();
assert!(label.trim_end().ends_with("too wide"));
}
#[test]
fn unknown_code_languages_fall_back_to_the_code_style() {
let document = mbdown::parse("```not-a-language\nplain code\n```").unwrap();
let text = Renderer::new(40).render(&document);
let rendered = plain(&text);
let lines = rendered.lines().collect::<Vec<_>>();
assert!(lines[0].trim().is_empty());
assert_eq!(lines[1].trim_end(), " not-a-language");
assert!(lines[2].trim().is_empty());
assert_eq!(lines[3].trim_end(), " 1 │ plain code");
let code = text
.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == "plain code")
.expect("plain code span");
assert_eq!(code.style, Theme::default().code_block);
}
#[test]
fn diff_code_blocks_style_semantic_lines() {
let source = concat!(
"```diff\n",
"--- a/note.md\n",
"+++ b/note.md\n",
"@@ -1,2 +1,2 @@\n",
"-old value\n",
"+new value\n",
" context\n",
"```",
);
let document = mbdown::parse(source).unwrap();
let text = Renderer::new(50).render(&document);
let find = |needle: &str| {
text.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == needle)
.expect("diff span")
};
assert_eq!(find("-old value").style.fg, Some(catppuccin::RED));
assert_eq!(find("-old value").style.bg, Some(catppuccin::SURFACE_0));
assert_eq!(find("+new value").style.fg, Some(catppuccin::GREEN));
assert_eq!(find("+new value").style.bg, Some(catppuccin::SURFACE_0));
assert_eq!(find("@@ -1,2 +1,2 @@").style.fg, Some(catppuccin::SAPPHIRE));
assert_eq!(find(" context").style, Theme::default().code_block);
}
#[test]
fn code_blocks_wrap_inside_their_horizontal_padding() {
let document = mbdown::parse("```text\nabcdefghijkl\n```").unwrap();
let text = Renderer::new(14).render(&document);
let rendered = plain(&text);
let lines = rendered.lines().collect::<Vec<_>>();
assert!(lines[0].trim().is_empty());
assert_eq!(lines[1].trim_end(), " text");
assert!(lines[2].trim().is_empty());
assert_eq!(lines[3].trim_end(), " 1 │ abcdef");
assert_eq!(lines[4].trim_end(), " ghijkl");
assert!(lines.iter().all(|line| UnicodeWidthStr::width(*line) == 14));
}
#[test]
fn task_items_replace_unordered_bullets_and_cross_out_completed_rows() {
let document =
mbdown::parse("- [ ] open\n- [x] done\n- ordinary\n1. [x] numbered").unwrap();
let text = Renderer::new(30).render(&document);
let output = plain(&text);
assert_eq!(output, " ☐ open\n ☑ done\n • ordinary\n\n 1. ☑ numbered");
assert!(!output.contains("• ☐"));
assert!(!output.contains("• ☑"));
let span = |content: &str| {
text.lines
.iter()
.flat_map(|line| &line.spans)
.find(|span| span.content == content)
.unwrap()
};
assert!(!span(" ☐ ")
.style
.add_modifier
.contains(Modifier::CROSSED_OUT));
assert!(!span("open")
.style
.add_modifier
.contains(Modifier::CROSSED_OUT));
assert!(span(" ☑ ")
.style
.add_modifier
.contains(Modifier::CROSSED_OUT));
assert!(span("done")
.style
.add_modifier
.contains(Modifier::CROSSED_OUT));
}
#[test]
fn wrapped_list_items_align_continuations_with_their_content() {
let document = mbdown::parse(
"- abcdefghijk\n\n- [ ] abcdefghijk\n\n1. abcdefghijk\n\n1. [x] abcdefghijk",
)
.unwrap();
let output = plain(&Renderer::new(10).render(&document));
assert_eq!(
output,
" • abcdefg\n hijk\n\n ☐ abcdefg\n hijk\n\n 1. abcdef\n ghijk\n\n 2. ☑ abcd\n efgh\n ijk"
);
}
#[test]
fn markdown_list_continuation_lines_keep_the_hanging_indent() {
let document = mbdown::parse("- first\n second\n\n> - abcdefgh").unwrap();
let output = plain(&Renderer::new(10).render(&document));
assert_eq!(
output,
" • first\n second\n\n ▌ • abc\n ▌ def\n ▌ gh"
);
}
#[test]
fn nested_lists_indent_items_and_wrapped_continuations() {
let document = mbdown::parse("- AAA\n - BBBBBBBB\n- CCC").unwrap();
assert_eq!(
plain(&Renderer::new(10).render(&document)),
" • AAA\n • BBBB\n BBBB\n • CCC"
);
}
#[test]
fn wrapped_quotes_keep_indent_and_rail() {
let document = mbdown::parse("> abcdefghijkl").unwrap();
let output = plain(&Renderer::new(10).render(&document));
assert_eq!(output, " ▌ abcdef\n ▌ ghijkl");
}
#[test]
fn right_aligned_blocks_pad_each_rendered_line() {
let document = mbdown::parse("[right]right\nline[/right]").unwrap();
let output = plain(&Renderer::new(10).render(&document));
assert_eq!(output, " right\n line");
}
}