use mbdown::{Container as Tag, ContainerEnd as TagEnd, Event, InlineTag};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use crate::bbcode;
use crate::frame;
use crate::layout;
use crate::syntax;
use crate::table::{self, Row};
use crate::Theme;
mod wrapping;
#[cfg(test)]
mod layout_tests;
const QUOTE_STYLE: &str = "markdown-quote";
const LIST_STYLE: &str = "markdown-list";
const RULE_STYLE: &str = "markdown-rule";
const CODE_STYLE: &str = "markdown-code";
const INLINE_CODE_STYLE: &str = "markdown-inline-code";
const HEADING_STYLE: &str = "markdown-heading";
const HASHTAG_STYLE: &str = "markdown-hashtag";
const WIKILINK_STYLE: &str = "markdown-wikilink";
const TXM_WIDE_FILLER: char = '\u{200b}';
struct Tokens {
literal_open: char,
literal_close: char,
tag_open: char,
tag_close: char,
}
impl Tokens {
fn for_input(input: &str) -> Option<Self> {
let mut available = ('\u{e000}'..='\u{f8ff}')
.chain('\u{f0000}'..='\u{ffffd}')
.chain('\u{100000}'..='\u{10fffd}')
.filter(|candidate| !input.contains(*candidate));
Some(Self {
literal_open: available.next()?,
literal_close: available.next()?,
tag_open: available.next()?,
tag_close: available.next()?,
})
}
}
#[cfg(test)]
pub(crate) fn render(input: &str, width: usize, theme: &Theme) -> String {
match mbdown::parse(input) {
Ok(document) => render_document(&document, width, theme, false),
Err(error) => render_error(&error, theme),
}
}
pub(crate) fn render_document(
document: &mbdown::Document<'_>,
width: usize,
theme: &Theme,
include_front_matter: bool,
) -> String {
let body = layout::render(
document.nodes(),
width,
theme,
|markdown, available, paragraph_indent| {
render_markdown(markdown, available, paragraph_indent, theme)
},
)
.unwrap_or_else(|error| {
bbcode::render(
&format!("[red]MBTerm structural BBCode error: {error}[/red]"),
true,
theme,
)
});
let Some(front_matter) = document.front_matter().filter(|_| include_front_matter) else {
return body;
};
let metadata = render_front_matter(front_matter, width, theme);
if body.is_empty() {
metadata
} else {
format!("{metadata}\n\n{body}")
}
}
fn render_front_matter(
front_matter: &mbdown::FrontMatter<'_>,
width: usize,
theme: &Theme,
) -> String {
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());
let content = syntax::render(source, Some(language));
let style = code_border_style(theme, Some(language));
frame::render(
language,
&content,
width,
theme,
frame::FrameStyle::Semantic(&style),
)
}
pub(crate) fn render_error(error: &mbdown::ParseError, theme: &Theme) -> String {
bbcode::render(
&format!("[red]MBTerm structural BBCode error: {error}[/red]"),
true,
theme,
)
}
fn render_markdown(
markdown: &mbdown::Markdown<'_>,
width: usize,
paragraph_indent: usize,
theme: &Theme,
) -> String {
let Some(tokens) = Tokens::for_input(markdown.source()) else {
return bbcode::sanitize_terminal_controls(markdown.source());
};
let events: Vec<_> = markdown
.events()
.iter()
.map(|item| item.event.clone())
.collect();
let mut renderer = MarkdownRenderer::new(width, theme, &tokens);
let mut index = 0;
while index < events.len() {
if let Event::DisplayMath(math) = &events[index] {
renderer.flush_markup();
let prefix = render_fragment(
"e_prefix_markup(renderer.quote_depth, theme),
theme,
&tokens,
);
let frame_width = width.saturating_sub(quote_prefix_width(renderer.quote_depth));
let framed = render_display_math(math, frame_width, theme);
append_prefixed(&mut renderer.output, &prefix, &framed);
renderer.ensure_output_newlines(2);
index += 1;
continue;
}
if let Event::Start(Tag::CodeBlock(kind)) = &events[index] {
renderer.flush_markup();
let end = matching_code_block_end(&events, index);
let language = kind.as_deref().and_then(code_language);
let mut content = code_block_text(&events[index + 1..end]);
if content.ends_with('\n') {
content.pop();
}
let content = syntax::render(&content, language);
let style = code_border_style(theme, language);
let prefix = render_fragment(
"e_prefix_markup(renderer.quote_depth, theme),
theme,
&tokens,
);
let frame_width = width.saturating_sub(quote_prefix_width(renderer.quote_depth));
let framed = frame::render(
language.unwrap_or_default(),
&content,
frame_width,
theme,
frame::FrameStyle::Semantic(&style),
);
append_prefixed(&mut renderer.output, &prefix, &framed);
renderer.ensure_output_newlines(2);
index = end + 1;
continue;
}
if let Event::Start(Tag::Table(alignments)) = &events[index] {
renderer.flush_markup();
let end = matching_table_end(&events, index);
let rows = table_rows(&events[index + 1..end], theme, &tokens);
let quote_prefix = render_fragment(
"e_prefix_markup(renderer.quote_depth, theme),
theme,
&tokens,
);
let table_width = width.saturating_sub(quote_prefix_width(renderer.quote_depth));
let rendered = table::render(alignments, &rows, table_width, theme.corner_style());
for (line_index, line) in rendered.lines().enumerate() {
if line_index > 0 {
renderer.output.push('\n');
}
renderer.output.push_str("e_prefix);
renderer.output.push_str(line);
}
renderer.ensure_output_newlines(2);
index = end + 1;
continue;
}
renderer.event(&events[index]);
index += 1;
}
wrapping::wrap_lines(&renderer.finish(), width, paragraph_indent)
}
struct MarkdownRenderer<'a> {
width: usize,
theme: &'a Theme,
tokens: &'a Tokens,
output: String,
markup: InlineBuffer,
lists: Vec<ListState>,
quote_depth: usize,
images: Vec<String>,
pending_item_marker: Option<std::ops::Range<usize>>,
}
#[derive(Debug)]
enum InlinePart {
Markup(String),
LinkStart { id: u64, target: String },
LinkEnd { id: u64 },
}
#[derive(Debug, Default)]
struct InlineBuffer {
parts: Vec<InlinePart>,
markup: String,
links: Vec<u64>,
next_link_id: u64,
flushed_markup: bool,
flushed_trailing_newlines: usize,
}
impl InlineBuffer {
fn is_empty(&self) -> bool {
self.parts.is_empty() && self.markup.is_empty()
}
fn has_markup(&self) -> bool {
self.flushed_markup || !self.markup.is_empty()
}
fn trailing_newlines(&self) -> usize {
if self.markup.is_empty() {
self.flushed_trailing_newlines
} else {
self.markup
.chars()
.rev()
.take_while(|ch| *ch == '\n')
.count()
}
}
fn flush_markup(&mut self) {
if !self.markup.is_empty() {
self.flushed_trailing_newlines = self
.markup
.chars()
.rev()
.take_while(|ch| *ch == '\n')
.count();
self.flushed_markup = true;
self.parts
.push(InlinePart::Markup(std::mem::take(&mut self.markup)));
}
}
fn ensure_newlines(&mut self, count: usize) {
if !self.has_markup() || count == 0 {
return;
}
self.markup.extend(std::iter::repeat_n(
'\n',
count.saturating_sub(self.trailing_newlines()),
));
}
fn link_start(&mut self, target: &str) {
self.flush_markup();
let id = self.next_link_id;
self.next_link_id = self.next_link_id.wrapping_add(1);
self.parts.push(InlinePart::LinkStart {
id,
target: target.to_string(),
});
self.links.push(id);
}
fn link_end(&mut self) {
let Some(id) = self.links.pop() else { return };
self.flush_markup();
self.parts.push(InlinePart::LinkEnd { id });
}
}
struct ListState {
next: Option<u64>,
}
impl<'a> MarkdownRenderer<'a> {
fn new(width: usize, theme: &'a Theme, tokens: &'a Tokens) -> Self {
Self {
width,
theme,
tokens,
output: String::new(),
markup: InlineBuffer::default(),
lists: Vec::new(),
quote_depth: 0,
images: Vec::new(),
pending_item_marker: None,
}
}
fn event(&mut self, event: &Event<'_>) {
if !matches!(event, Event::TaskListMarker(_)) {
self.pending_item_marker = None;
}
match event {
Event::Start(tag) => self.start(tag),
Event::End(tag) => self.end(*tag),
Event::Text(text) => self.push_prefixed_text(text),
Event::Hashtag(tag) => {
self.push_line_prefix();
let style = semantic_style(self.theme, HASHTAG_STYLE, "bright-magenta");
push_styled(&mut self.markup.markup, &style, &format!("#{tag}"));
}
Event::WikiLink(target) => {
self.push_line_prefix();
let style = semantic_style(self.theme, WIKILINK_STYLE, "bright-cyan");
self.markup.markup.push_str("[u]");
push_style_open(&mut self.markup.markup, &style);
push_text(
&mut self.markup.markup,
&format!("[[{target}]]"),
self.tokens,
);
push_style_close(&mut self.markup.markup, &style);
self.markup.markup.push_str("[/u]");
}
Event::Embed(target) => {
self.push_line_prefix();
let style = semantic_style(self.theme, WIKILINK_STYLE, "bright-cyan");
self.markup.markup.push_str("[u]");
push_style_open(&mut self.markup.markup, &style);
push_text(
&mut self.markup.markup,
&format!("![[{target}]]"),
self.tokens,
);
push_style_close(&mut self.markup.markup, &style);
self.markup.markup.push_str("[/u]");
}
Event::InlineTag(tag) => {
self.push_line_prefix();
push_inline_tag(&mut self.markup.markup, tag, self.theme, self.tokens);
}
Event::Code(code) => {
self.push_line_prefix();
let style = semantic_style(self.theme, INLINE_CODE_STYLE, "cyan");
push_style_open(&mut self.markup.markup, &style);
push_literal(&mut self.markup.markup, code, self.tokens);
push_style_close(&mut self.markup.markup, &style);
}
Event::InlineMath(math) => {
self.push_line_prefix();
let style = semantic_style(self.theme, INLINE_CODE_STYLE, "cyan");
push_style_open(&mut self.markup.markup, &style);
push_literal(&mut self.markup.markup, "$", self.tokens);
push_literal(&mut self.markup.markup, math, self.tokens);
push_literal(&mut self.markup.markup, "$", self.tokens);
push_style_close(&mut self.markup.markup, &style);
}
Event::Html(html) | Event::InlineHtml(html) => {
self.push_line_prefix();
push_literal(&mut self.markup.markup, html, self.tokens);
}
Event::SoftBreak => self.newline_with_prefix(),
Event::HardBreak => self.newline_with_prefix(),
Event::Rule => {
self.ensure_markup_newlines(1);
self.push_line_prefix();
let prefix_width = quote_prefix_width(self.quote_depth);
let rule_width = self.width.saturating_sub(prefix_width).max(3);
let style = semantic_style(self.theme, RULE_STYLE, "gray");
push_style_open(&mut self.markup.markup, &style);
self.markup
.markup
.extend(std::iter::repeat_n('─', rule_width));
push_style_close(&mut self.markup.markup, &style);
self.ensure_markup_newlines(2);
}
Event::TaskListMarker(checked) => {
self.push_line_prefix();
if let Some(marker) = self.pending_item_marker.take() {
if marker.end == self.markup.markup.len() {
self.markup.markup.replace_range(marker, "");
}
}
let style = semantic_style(self.theme, LIST_STYLE, "bright-cyan");
push_styled(
&mut self.markup.markup,
&style,
if *checked { "☑" } else { "☐" },
);
self.markup.markup.push(' ');
}
Event::FootnoteReference(reference) => {
self.push_line_prefix();
self.markup.markup.push('[');
push_literal(&mut self.markup.markup, reference, self.tokens);
self.markup.markup.push(']');
}
_ => {}
}
}
fn start(&mut self, tag: &Tag<'_>) {
match tag {
Tag::Paragraph => {}
Tag::Heading(_) => {
self.push_line_prefix();
let style = semantic_style(self.theme, HEADING_STYLE, "bright-cyan");
push_style_open(&mut self.markup.markup, &style);
self.markup.markup.push_str("[b]");
}
Tag::BlockQuote => {
self.ensure_markup_newlines(1);
self.quote_depth += 1;
}
Tag::List(first) => {
self.ensure_markup_newlines(usize::from(self.lists.is_empty()));
self.lists.push(ListState { next: *first });
}
Tag::Item => {
self.ensure_markup_newlines(1);
self.push_line_prefix();
self.markup.markup.extend(std::iter::repeat_n(
' ',
1 + self.lists.len().saturating_sub(1) * 2,
));
let marker_start = self.markup.markup.len();
let marker = if let Some(list) = self.lists.last_mut() {
if let Some(next) = &mut list.next {
let marker = format!("{next}.");
*next += 1;
marker
} else {
"•".to_string()
}
} else {
String::new()
};
let style = semantic_style(self.theme, LIST_STYLE, "bright-cyan");
push_styled(&mut self.markup.markup, &style, &marker);
self.markup.markup.push(' ');
self.pending_item_marker = Some(marker_start..self.markup.markup.len());
}
Tag::Emphasis => {
self.push_line_prefix();
self.markup.markup.push_str("[i]");
}
Tag::Strong => {
self.push_line_prefix();
self.markup.markup.push_str("[b]");
}
Tag::Strikethrough => {
self.push_line_prefix();
self.markup.markup.push_str("[s]");
}
Tag::Link { target, .. } => {
self.push_line_prefix();
self.markup.link_start(target);
}
Tag::Image { target, .. } => {
self.push_line_prefix();
self.markup.markup.push_str("image: ");
self.images.push(target.to_string());
}
_ => {}
}
}
fn end(&mut self, tag: TagEnd) {
match tag {
TagEnd::Paragraph => {
if self.lists.is_empty() {
self.ensure_markup_newlines(2);
}
}
TagEnd::Heading => {
self.markup.markup.push_str("[/b]");
let style = semantic_style(self.theme, HEADING_STYLE, "bright-cyan");
push_style_close(&mut self.markup.markup, &style);
self.ensure_markup_newlines(2);
}
TagEnd::BlockQuote => {
self.ensure_markup_newlines(2);
self.quote_depth = self.quote_depth.saturating_sub(1);
}
TagEnd::List(_) => {
self.lists.pop();
self.ensure_markup_newlines(if self.lists.is_empty() { 2 } else { 1 });
}
TagEnd::Item => self.ensure_markup_newlines(1),
TagEnd::Emphasis => self.markup.markup.push_str("[/i]"),
TagEnd::Strong => self.markup.markup.push_str("[/b]"),
TagEnd::Strikethrough => self.markup.markup.push_str("[/s]"),
TagEnd::Link => self.markup.link_end(),
TagEnd::Image => {
if let Some(destination) = self.images.pop() {
self.push_line_prefix();
self.markup.markup.push_str(" [dim](");
push_literal(&mut self.markup.markup, &destination, self.tokens);
self.markup.markup.push_str(")[/dim]");
}
}
_ => {}
}
}
fn newline_with_prefix(&mut self) {
self.ensure_markup_newlines(1);
self.push_line_prefix();
if !self.lists.is_empty() {
self.markup
.markup
.extend(std::iter::repeat_n(' ', 1 + self.lists.len() * 2));
}
}
fn push_line_prefix(&mut self) {
if self.markup.has_markup() && self.markup.trailing_newlines() == 0 {
return;
}
self.markup
.markup
.push_str("e_prefix_markup(self.quote_depth, self.theme));
}
fn push_prefixed_text(&mut self, text: &str) {
for ch in text.chars() {
if ch != '\n' {
self.push_line_prefix();
}
push_text_char(&mut self.markup.markup, ch, self.tokens);
}
}
fn ensure_markup_newlines(&mut self, count: usize) {
self.markup.ensure_newlines(count);
}
fn ensure_output_newlines(&mut self, count: usize) {
ensure_newlines(&mut self.output, count);
}
fn flush_markup(&mut self) {
if self.markup.is_empty() {
return;
}
self.output.push_str(&render_inline(
std::mem::take(&mut self.markup),
self.theme,
self.tokens,
));
}
fn finish(mut self) -> String {
self.flush_markup();
self.output
.truncate(self.output.trim_end_matches('\n').len());
self.output
}
}
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 render_display_math(source: &str, width: usize, theme: &Theme) -> String {
let source = trim_math_block(source);
let inner_width = width.max(4).saturating_sub(4).max(1);
if let Some(content) = terminal_math(source, inner_width) {
let style = code_border_style(theme, Some("tex"));
return frame::render(
"math",
&content,
width,
theme,
frame::FrameStyle::Semantic(&style),
);
}
let content = syntax::render(source, Some("tex"));
let style = code_border_style(theme, Some("tex"));
frame::render(
"tex",
&content,
width,
theme,
frame::FrameStyle::Semantic(&style),
)
}
fn terminal_math(source: &str, width: usize) -> Option<String> {
let compatible = txm_compatible_source(source)?;
let rendered = txm::render(&compatible.encoded).ok()?;
let rendered = crate::ansi::strip_terminal_sequences(&rendered);
let rendered = compatible.restore(rendered);
let lines: Vec<_> = rendered
.lines()
.map(|line| line.trim_end_matches(' '))
.collect();
if lines.is_empty()
|| lines
.iter()
.any(|line| UnicodeWidthStr::width(*line) > width)
{
return None;
}
Some(lines.join("\n"))
}
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(())
}
fn append_prefixed(output: &mut String, prefix: &str, value: &str) {
if !output.is_empty() {
ensure_newlines(output, 1);
}
for (index, line) in value.lines().enumerate() {
if index > 0 {
output.push('\n');
}
output.push_str(prefix);
output.push_str(line);
}
}
fn matching_code_block_end(events: &[Event<'_>], start: usize) -> usize {
events
.iter()
.enumerate()
.skip(start + 1)
.find_map(|(index, event)| matches!(event, Event::End(TagEnd::CodeBlock)).then_some(index))
.unwrap_or_else(|| events.len().saturating_sub(1))
}
fn code_block_text(events: &[Event<'_>]) -> String {
let mut output = String::new();
for event in events {
match event {
Event::Text(text) | Event::Code(text) => output.push_str(text),
Event::SoftBreak | Event::HardBreak => output.push('\n'),
_ => {}
}
}
output
}
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 semantic_style(theme: &Theme, name: &str, fallback: &str) -> String {
if theme.get(name).is_some() {
name.to_string()
} else {
fallback.to_string()
}
}
fn quote_prefix_markup(depth: usize, theme: &Theme) -> String {
let style = semantic_style(theme, QUOTE_STYLE, "gray");
let mut output = String::with_capacity(depth.saturating_mul(style.len() * 2 + 6));
if depth > 0 {
output.push(' ');
}
for _ in 0..depth {
push_styled(&mut output, &style, "│");
output.push(' ');
}
output
}
fn quote_prefix_width(depth: usize) -> usize {
usize::from(depth > 0) + depth.saturating_mul(2)
}
fn code_border_style(theme: &Theme, language: Option<&str>) -> String {
if let Some(language) = language.and_then(normalize_language) {
let language_style = format!("{CODE_STYLE}-{language}");
if theme.get(&language_style).is_some() {
return language_style;
}
}
semantic_style(theme, CODE_STYLE, "gray")
}
fn normalize_language(info: &str) -> Option<String> {
let language = info.split_whitespace().next()?;
let mut normalized = String::with_capacity(language.len());
for ch in language.chars() {
if ch.is_ascii_alphanumeric() {
normalized.push(ch.to_ascii_lowercase());
} else if matches!(ch, '-' | '_') {
normalized.push(ch);
} else if !normalized.ends_with('-') {
normalized.push('-');
}
}
let normalized = normalized.trim_matches('-');
(!normalized.is_empty()).then(|| normalized.to_string())
}
fn push_styled(output: &mut String, style: &str, value: &str) {
push_style_open(output, style);
output.push_str(value);
push_style_close(output, style);
}
fn push_style_open(output: &mut String, style: &str) {
output.push('[');
output.push_str(style);
output.push(']');
}
fn push_style_close(output: &mut String, style: &str) {
output.push_str("[/");
output.push_str(style);
output.push(']');
}
fn matching_table_end(events: &[Event<'_>], start: usize) -> usize {
let mut depth = 0;
for (index, event) in events.iter().enumerate().skip(start) {
match event {
Event::Start(Tag::Table(_)) => depth += 1,
Event::End(TagEnd::Table) => {
depth -= 1;
if depth == 0 {
return index;
}
}
_ => {}
}
}
events.len().saturating_sub(1)
}
fn table_rows(events: &[Event<'_>], theme: &Theme, tokens: &Tokens) -> Vec<Row> {
let mut rows = Vec::new();
let mut current_row: Option<(Vec<String>, bool)> = None;
let mut cell: Option<InlineBuffer> = None;
for event in events {
match event {
Event::Start(Tag::TableHead) => current_row = Some((Vec::new(), true)),
Event::End(TagEnd::TableHead) => finish_row(&mut rows, &mut current_row),
Event::Start(Tag::TableRow) => current_row = Some((Vec::new(), false)),
Event::End(TagEnd::TableRow) => finish_row(&mut rows, &mut current_row),
Event::Start(Tag::TableCell) => {
let mut value = InlineBuffer::default();
if current_row.as_ref().is_some_and(|(_, header)| *header) {
value.markup.push_str("[b]");
}
cell = Some(value);
}
Event::End(TagEnd::TableCell) => {
if let (Some((cells, header)), Some(mut value)) = (&mut current_row, cell.take()) {
if *header {
value.markup.push_str("[/b]");
}
cells.push(render_inline(value, theme, tokens));
}
}
_ => {
if let Some(value) = &mut cell {
inline_event(value, event, theme, tokens);
}
}
}
}
finish_row(&mut rows, &mut current_row);
rows
}
fn finish_row(rows: &mut Vec<Row>, current: &mut Option<(Vec<String>, bool)>) {
if let Some((cells, header)) = current.take() {
rows.push(Row { cells, header });
}
}
fn inline_event(output: &mut InlineBuffer, event: &Event<'_>, theme: &Theme, tokens: &Tokens) {
match event {
Event::Start(Tag::Emphasis) => output.markup.push_str("[i]"),
Event::End(TagEnd::Emphasis) => output.markup.push_str("[/i]"),
Event::Start(Tag::Strong) => output.markup.push_str("[b]"),
Event::End(TagEnd::Strong) => output.markup.push_str("[/b]"),
Event::Start(Tag::Strikethrough) => output.markup.push_str("[s]"),
Event::End(TagEnd::Strikethrough) => output.markup.push_str("[/s]"),
Event::Start(Tag::Link { target, .. }) => output.link_start(target),
Event::End(TagEnd::Link) => output.link_end(),
Event::Text(text) => push_text(&mut output.markup, text, tokens),
Event::Hashtag(tag) => {
let style = semantic_style(theme, HASHTAG_STYLE, "bright-magenta");
push_styled(&mut output.markup, &style, &format!("#{tag}"));
}
Event::WikiLink(target) => {
let style = semantic_style(theme, WIKILINK_STYLE, "bright-cyan");
output.markup.push_str("[u]");
push_style_open(&mut output.markup, &style);
push_text(&mut output.markup, &format!("[[{target}]]"), tokens);
push_style_close(&mut output.markup, &style);
output.markup.push_str("[/u]");
}
Event::Embed(target) => {
let style = semantic_style(theme, WIKILINK_STYLE, "bright-cyan");
output.markup.push_str("[u]");
push_style_open(&mut output.markup, &style);
push_text(&mut output.markup, &format!("![[{target}]]"), tokens);
push_style_close(&mut output.markup, &style);
output.markup.push_str("[/u]");
}
Event::InlineTag(tag) => {
push_inline_tag(&mut output.markup, tag, theme, tokens);
}
Event::Code(code) => {
let style = semantic_style(theme, INLINE_CODE_STYLE, "cyan");
push_style_open(&mut output.markup, &style);
push_literal(&mut output.markup, code, tokens);
push_style_close(&mut output.markup, &style);
}
Event::SoftBreak => output.markup.push(' '),
Event::HardBreak => output.markup.push('\n'),
Event::Html(html) | Event::InlineHtml(html) => {
push_literal(&mut output.markup, html, tokens);
}
Event::TaskListMarker(checked) => {
output.markup.push_str(if *checked { "☑ " } else { "☐ " });
}
_ => {}
}
}
fn ensure_newlines(output: &mut String, count: usize) {
if output.is_empty() || count == 0 {
return;
}
let existing = output.chars().rev().take_while(|ch| *ch == '\n').count();
output.extend(std::iter::repeat_n('\n', count.saturating_sub(existing)));
}
fn render_fragment(markup: &str, theme: &Theme, tokens: &Tokens) -> String {
let mut buffer = InlineBuffer::default();
buffer.markup.push_str(markup);
render_inline(buffer, theme, tokens)
}
fn render_inline(mut buffer: InlineBuffer, theme: &Theme, tokens: &Tokens) -> String {
buffer.flush_markup();
let mut formatter = bbcode::FormatSession::new(true, theme);
for part in buffer.parts {
match part {
InlinePart::Markup(markup) => {
let trusted = markup
.replace(tokens.tag_open, "[")
.replace(tokens.tag_close, "]");
formatter.push_markup(&trusted);
}
InlinePart::LinkStart { id, target } => {
formatter.link_start(id, &restore_typed_target(&target, tokens));
}
InlinePart::LinkEnd { id } => formatter.link_end(id),
}
}
restore_protected(&formatter.finish(), tokens)
}
fn push_text(output: &mut String, text: &str, tokens: &Tokens) {
for ch in text.chars() {
push_text_char(output, ch, tokens);
}
}
fn push_inline_tag(output: &mut String, tag: &InlineTag<'_>, theme: &Theme, tokens: &Tokens) {
let raw = tag.raw.as_ref();
let body = raw
.strip_prefix('[')
.and_then(|value| value.strip_suffix(']'))
.unwrap_or(raw);
if bbcode::is_tag(body, theme) {
output.push(tokens.tag_open);
output.push_str(body);
output.push(tokens.tag_close);
} else {
push_text(output, raw, tokens);
}
}
fn push_literal(output: &mut String, text: &str, tokens: &Tokens) {
for ch in text.chars() {
push_literal_char(output, ch, tokens);
}
}
fn push_text_char(output: &mut String, ch: char, tokens: &Tokens) {
output.push(match ch {
'[' => tokens.literal_open,
']' => tokens.literal_close,
_ => ch,
});
}
fn push_literal_char(output: &mut String, ch: char, tokens: &Tokens) {
output.push(match ch {
'[' => tokens.literal_open,
']' => tokens.literal_close,
ch if ch == tokens.tag_open => tokens.literal_open,
ch if ch == tokens.tag_close => tokens.literal_close,
_ => ch,
});
}
fn restore_typed_target(input: &str, tokens: &Tokens) -> String {
restore_protected(input, tokens)
.replace(tokens.tag_open, "[")
.replace(tokens.tag_close, "]")
}
fn restore_protected(input: &str, tokens: &Tokens) -> String {
input
.replace(tokens.literal_open, "[")
.replace(tokens.literal_close, "]")
}
#[cfg(test)]
mod tests {
use unicode_width::UnicodeWidthStr;
use super::*;
use crate::{escape, strip_terminal_sequences, BasicColor, Color, TextStyle};
fn plain(input: &str) -> String {
strip_terminal_sequences(input)
}
fn osc8(target: &str, label: &str) -> String {
format!("\x1b]8;;{target}\x1b\\{label}{}", crate::ansi::OSC8_CLOSE)
}
#[test]
fn markdown_inline_reference_and_autolinks_render_label_only_osc8() {
let source = concat!(
"[inline](HTTPS://Example.COM/A) ",
"[reference][target] ",
"<custom+Thing:Value>\n\n",
"[target]: ../Relative/Path"
);
let rendered = render(source, 120, &Theme::new());
assert_eq!(
rendered,
format!(
"{} {} {}",
osc8("HTTPS://Example.COM/A", "inline"),
osc8("../Relative/Path", "reference"),
osc8("custom+Thing:Value", "custom+Thing:Value")
)
);
assert_eq!(plain(&rendered), "inline reference custom+Thing:Value");
}
#[test]
fn markdown_link_destinations_are_typed_data_not_bbcode_or_tokens() {
let private = '\u{e000}';
let cases = [
("[x](<A]B>)".to_string(), "A]B".to_string()),
(r#"[x](<A"B>)"#.to_string(), r#"A"B"#.to_string()),
(r"[x](A\\B)".to_string(), r"A\B".to_string()),
("[x](<A B>)".to_string(), "A B".to_string()),
(
"[x](https://example.test/[reset])".to_string(),
"https://example.test/[reset]".to_string(),
),
(
"[x](https://example.test/[/link])".to_string(),
"https://example.test/[/link]".to_string(),
),
(
format!("[x](https://example.test/{private})"),
format!("https://example.test/{private}"),
),
];
for (source, target) in cases {
let rendered = render(&source, 120, &Theme::new());
assert_eq!(rendered, osc8(&target, "x"), "source: {source:?}");
assert_eq!(plain(&rendered), "x");
}
}
#[test]
fn semantic_tag_pairs_are_not_reinterpreted_as_markdown_links() {
let mut theme = Theme::new();
theme
.insert(
"muted",
TextStyle::new().foreground(Color::Basic(BasicColor::BrightBlack)),
)
.unwrap();
let rendered = render("[muted](e/east)[/muted]", 120, &theme);
assert_eq!(rendered, "\x1b[90m(e/east)\x1b[0m");
assert!(!rendered.contains("\x1b]8;;"), "{rendered:?}");
assert!(!rendered.contains("[/muted]"), "{rendered:?}");
}
#[test]
fn typed_links_scope_markdown_and_bbcode_styles_and_links() {
let close = crate::ansi::OSC8_CLOSE;
let rendered = render(
"[link=outer]a[**bold** [red]red[/red]](inner)c[/link]",
120,
&Theme::new(),
);
assert_eq!(plain(&rendered), "abold redc");
assert_eq!(rendered.matches("\x1b]8;;inner\x1b\\").count(), 1);
assert_eq!(rendered.matches("\x1b]8;;outer\x1b\\").count(), 2);
assert!(
rendered.contains(&format!(
"{close}\x1b]8;;inner\x1b\\\x1b[1mbold\x1b[0m \x1b[31mred\x1b[0m{close}\x1b]8;;outer\x1b\\c"
)),
"{rendered:?}"
);
let reset = render("[before [reset] after](typed) tail", 120, &Theme::new());
assert_eq!(plain(&reset), "before after tail");
assert_eq!(reset.matches("\x1b]8;;typed\x1b\\").count(), 2);
let leaked = render("[label [link=evil]inside](typed) tail", 120, &Theme::new());
assert_eq!(plain(&leaked), "label inside tail");
assert!(!leaked.ends_with(&format!("\x1b]8;;evil\x1b\\{close}")));
let tail_at = leaked.rfind(" tail").expect("tail is rendered");
assert!(!leaked[tail_at..].contains("\x1b]8;;"), "{leaked:?}");
}
#[test]
fn typed_link_boundary_drops_unclosed_label_formats_and_restores_outer_formats() {
let close = crate::ansi::OSC8_CLOSE;
let rendered = render(
concat!(
"[red][bg=blue][blink][link=outer]a",
"[label [green]fg [bg=yellow]bg [blink=rapid]blink ",
"[link=source]source](typed)c[/link][/blink][/bg][/red]"
),
120,
&Theme::new(),
);
assert_eq!(plain(&rendered), "alabel fg bg blink sourcec");
assert_eq!(rendered.matches("\x1b]8;;typed\x1b\\").count(), 1);
assert_eq!(rendered.matches("\x1b]8;;source\x1b\\").count(), 1);
assert_eq!(rendered.matches("\x1b]8;;outer\x1b\\").count(), 2);
assert!(
rendered.contains(&format!(
"source{close}\x1b[0m\x1b[31m\x1b[44m\x1b[5m\x1b]8;;outer\x1b\\c"
)),
"{rendered:?}"
);
}
#[test]
fn wrapped_cjk_links_close_and_reopen_on_every_physical_line() {
let rendered = render("[天地玄黄宇宙](relative)", 4, &Theme::new());
let lines: Vec<_> = rendered.lines().collect();
assert_eq!(lines.len(), 3, "{rendered:?}");
assert_eq!(plain(&rendered), "天地\n玄黄\n宇宙");
for line in lines {
assert!(line.starts_with("\x1b]8;;relative\x1b\\"), "{line:?}");
assert!(line.ends_with(crate::ansi::OSC8_CLOSE), "{line:?}");
assert_eq!(UnicodeWidthStr::width(plain(line).as_str()), 4);
}
}
#[test]
fn typed_links_preserve_inline_paragraph_and_hard_break_boundaries() {
assert_eq!(
plain(&render("开头[天地](target)结尾", 80, &Theme::new())),
"开头天地结尾"
);
assert_eq!(
plain(&render("第一段[天地](target)\n\n第二段", 80, &Theme::new())),
"第一段天地\n\n第二段"
);
assert_eq!(
plain(&render("[天地](target) \n玄黄", 80, &Theme::new())),
"天地\n玄黄"
);
}
#[test]
fn blockquote_links_keep_rails_outside_links_without_duplicate_prefixes() {
let wrapped = render("> [天地玄黄](target)", 5, &Theme::new());
assert_eq!(plain(&wrapped), " │ 天\n │ 地\n │ 玄\n │ 黄");
for line in wrapped.lines() {
assert!(
line.starts_with(" \x1b[38;2;203;166;247m│\x1b[0m "),
"{line:?}"
);
assert_eq!(line.matches("\x1b]8;;target\x1b\\").count(), 1, "{line:?}");
assert_eq!(line.matches(crate::ansi::OSC8_CLOSE).count(), 2, "{line:?}");
let rail_end = line
.find("\x1b[0m ")
.expect("quote rail has a trailing space")
+ "\x1b[0m ".len();
let isolation_close = line[rail_end..]
.strip_prefix(crate::ansi::OSC8_CLOSE)
.expect("quote rail closes any preceding link before linked content");
assert!(
isolation_close.starts_with("\x1b]8;;target\x1b\\"),
"{line:?}"
);
}
let inline = render("> 开头[天地](target)结尾", 80, &Theme::new());
assert_eq!(plain(&inline), " │ 开头天地结尾");
assert_eq!(plain(&inline).matches("│ ").count(), 1, "{inline:?}");
}
#[test]
fn list_links_preserve_item_and_hard_break_boundaries() {
assert_eq!(
plain(&render("- [甲](one)\n- [乙](two)", 80, &Theme::new())),
" • 甲\n • 乙"
);
assert_eq!(
plain(&render("- [天地](target) \n 玄黄", 80, &Theme::new())),
" • 天地\n 玄黄"
);
}
#[test]
fn table_links_measure_labels_and_keep_padding_and_borders_unlinked() {
let source = concat!(
"| 名称 | 状态 |\n",
"| --- | --- |\n",
"| [天地玄黄宇宙](https://example.test/[reset]) | 好 |"
);
let rendered = render(source, 14, &Theme::new());
let plain_rendered = plain(&rendered);
assert!(
!plain_rendered.contains("example.test"),
"{plain_rendered:?}"
);
assert!(plain_rendered
.lines()
.all(|line| UnicodeWidthStr::width(line) <= 14));
let content: Vec<_> = rendered
.lines()
.filter(|line| line.contains("\x1b]8;;https://example.test/[reset]\x1b\\"))
.collect();
assert!(content.len() >= 2, "{rendered:?}");
for line in content {
let open = line.find("\x1b]8;;").expect("link opens");
let close = line.find(crate::ansi::OSC8_CLOSE).expect("link closes");
assert!(open > line.find("│ ").expect("cell starts"), "{line:?}");
assert!(close < line.rfind(" │").expect("cell ends"), "{line:?}");
}
}
#[test]
fn images_keep_alt_and_destination_text_without_osc8() {
let rendered = render("", 80, &Theme::new());
assert_eq!(plain(&rendered), "image: 地图 (../Map.png)");
assert!(!rendered.contains("\x1b]8;;"), "{rendered:?}");
}
#[test]
fn leaves_plain_messages_unchanged() {
assert_eq!(render("风吹过广场。", 80, &Theme::new()), "风吹过广场。");
}
#[test]
fn nests_markdown_with_foreground_and_background_bbcode() {
let rendered = render(
"[red]**危险 [bg=#102030]区域[/bg]**[/red]",
80,
&Theme::new(),
);
assert!(rendered.contains("\x1b[31m\x1b[1m危险 "), "{rendered:?}");
assert!(rendered.contains("\x1b[48;2;16;32;48m区域"));
assert_eq!(plain(&rendered), "危险 区域");
}
#[test]
fn protects_quoted_bbcode_targets_with_closing_brackets() {
let rendered = render(
r#"[link="HTTPS://Example.COM/A]B"]**label**[/link]"#,
80,
&Theme::new(),
);
assert_eq!(
rendered,
format!(
"\x1b]8;;HTTPS://Example.COM/A]B\x1b\\\x1b[1mlabel\x1b[0m{}",
crate::ansi::OSC8_CLOSE
)
);
}
#[test]
fn escaped_and_entity_decoded_tags_cannot_inject_bbcode() {
let source = escape("**名字** [red]危险[/red]");
assert_eq!(
plain(&render(&source, 80, &Theme::new())),
"**名字** [red]危险[/red]"
);
assert_eq!(
render("[red]危险[/red]", 80, &Theme::new()),
"[red]危险[/red]"
);
let private_use = "\u{e000}\u{e001}\u{e002}\u{e003}red\u{e004}\u{e005}!";
assert_eq!(render(private_use, 80, &Theme::new()), private_use);
}
#[test]
fn renders_unicode_quotes_lists_tasks_and_rules() {
let quote = plain(&render(
"> 第一段\n>\n> 第二段\n>\n> > 嵌套\n>\n> - 项目",
24,
&Theme::new(),
));
assert!(quote.contains(" │ 第一段"), "{quote:?}");
assert!(quote.contains(" │ 第二段"), "{quote:?}");
assert!(quote.contains(" │ │ 嵌套"), "{quote:?}");
assert!(quote.contains(" │ • 项目"), "{quote:?}");
assert!(quote
.lines()
.filter(|line| !line.is_empty())
.all(|line| line.starts_with(" │")));
let list = plain(&render("- 普通\n- [ ] 待办\n- [x] 完成", 24, &Theme::new()));
assert_eq!(list, " • 普通\n ☐ 待办\n ☑ 完成");
assert_eq!(plain(&render("---", 12, &Theme::new())), "─".repeat(12));
}
#[test]
fn renders_fenced_code_with_unicode_rail_and_literal_markup() {
let rendered = plain(&render(
"```luau\nctx.msg(\"[red]危险[/red]\")\n\nreturn\n```",
40,
&Theme::new(),
));
assert_eq!(
rendered,
concat!(
"┌─ luau ───────────────────────────────┐\n",
"│ ctx.msg(\"[red]危险[/red]\") │\n",
"│ │\n",
"│ return │\n",
"└──────────────────────────────────────┘"
)
);
}
#[test]
fn renders_hashtags_and_wikilinks_semantically() {
let rendered = render("See #rust and [[Rust Notes]]", 40, &Theme::new());
assert_eq!(plain(&rendered), "See #rust and [[Rust Notes]]");
assert!(
rendered.contains("\x1b[1;38;2;245;194;231m#rust"),
"{rendered:?}"
);
assert!(
rendered.contains("\x1b[4m\x1b[38;2;137;220;235m[[Rust Notes]]"),
"{rendered:?}"
);
let table = plain(&render(
"| Tag | Link |\n| --- | --- |\n| #rust | [[Rust Notes]] |",
40,
&Theme::new(),
));
assert!(table.contains("#rust"));
assert!(table.contains("[[Rust Notes]]"));
}
#[test]
fn renders_embeds_with_wikilink_styling() {
let rendered = render("Open ![[attachments/report.pdf]]", 50, &Theme::new());
assert_eq!(plain(&rendered), "Open ![[attachments/report.pdf]]");
assert!(
rendered.contains("\x1b[4m\x1b[38;2;137;220;235m![[attachments/report.pdf]]"),
"{rendered:?}"
);
}
#[test]
fn renders_fit_full_and_nested_bbcode_boxes() {
let mut theme = Theme::new();
theme
.insert(
"primary",
TextStyle::new()
.bold()
.foreground(Color::Basic(BasicColor::BrightCyan)),
)
.unwrap();
theme
.insert(
"markdown-box",
TextStyle::new().foreground(Color::Basic(BasicColor::BrightBlack)),
)
.unwrap();
let titled = render(
"[box title=\"地图\" width=full]\n**[primary]中央[/primary]**\n[/box]",
20,
&theme,
);
assert!(titled.contains("\x1b[1;96m中央"), "{titled:?}");
assert_eq!(
plain(&titled),
concat!(
"┌─ 地图 ───────────┐\n",
"│ 中央 │\n",
"└──────────────────┘"
)
);
assert_eq!(
plain(&render("[box]\n无标题\n[/box]", 20, &theme)),
"┌────────┐\n│ 无标题 │\n└────────┘"
);
let nested = plain(&render(
"[box title=\"外层\"]\n外\n[box title=\"内层\"]\n内\n[/box]\n[/box]",
24,
&theme,
));
assert_eq!(nested.matches('┌').count(), 2, "{nested:?}");
assert_eq!(nested.matches('└').count(), 2, "{nested:?}");
}
#[test]
fn box_color_is_local_and_code_keeps_structural_tags_literal() {
let mut theme = Theme::new();
for (name, color) in [
("markdown-box", BasicColor::Blue),
("map-border", BasicColor::Green),
] {
theme
.insert(name, TextStyle::new().foreground(Color::Basic(color)))
.unwrap();
}
let map = render(
"[box title=\"地图\" border-color=map-border]\n内容\n[/box]",
20,
&theme,
);
assert!(map.contains("\x1b[32m┌─"), "{map:?}");
let default = render("[box title=\"其他\"]\n内容\n[/box]", 20, &theme);
assert!(default.contains("\x1b[34m┌─"), "{default:?}");
let code = plain(&render(
concat!(
"```text\n",
"[box title=\"地图\"]\n[/box]\n",
"[center]x[/center]\n",
"[indent first=4]x[/indent]\n",
"[columns][column]a[/column][column]b[/column][/columns]\n",
"```"
),
60,
&theme,
));
assert!(code.contains("│ [box title=\"地图\"]"), "{code:?}");
assert!(code.contains("│ [/box]"), "{code:?}");
assert!(code.contains("│ [center]x[/center]"), "{code:?}");
assert!(code.contains("│ [indent first=4]x[/indent]"), "{code:?}");
assert!(code.contains("[columns][column]a[/column]"), "{code:?}");
let indented = plain(&render(" [box]\n [/box]", 32, &theme));
assert!(indented.contains("│ [box]"), "{indented:?}");
assert!(indented.contains("│ [/box]"), "{indented:?}");
}
#[test]
fn aligns_text_and_fit_blocks_at_the_current_available_width() {
let text = plain(&render("[center]中央[/center]", 20, &Theme::new()));
assert_eq!(text, " 中央");
let boxed = plain(&render(
"[center][box title=\"地图\"]o-@-o[/box][/center]",
20,
&Theme::new(),
));
assert!(boxed.lines().all(|line| line.starts_with(" ")));
assert_eq!(boxed.lines().map(UnicodeWidthStr::width).max(), Some(15));
let right = plain(&render("[right]靠右[/right]", 20, &Theme::new()));
assert_eq!(right, format!("{}靠右", " ".repeat(16)));
let right_box = plain(&render(
"[right][box width=8 border=none]box[/box][/right]",
20,
&Theme::new(),
));
assert_eq!(right_box, format!("{}box", " ".repeat(12)));
}
#[test]
fn reports_invalid_structural_bbcode_explicitly() {
for source in [
"[box title=\"地图\"]没有结束",
"[box width=wide]x[/box]",
"[box border=none title=地图]x[/box]",
"[box color=not-a-color]x[/box]",
"[box border-color=not-a-color]x[/box]",
"[box bg=not-a-color]x[/box]",
"[columns bg=not-a-color][column]a[/column][column]b[/column][/columns]",
"[columns][column bg=not-a-color]a[/column][column]b[/column][/columns]",
"[center][box]x[/center][/box]",
"[right gap=2]x[/right]",
"[column]x[/column]",
"[columns][column]x[/column][/columns]",
"[columns]x[column]a[/column][column]b[/column][/columns]",
] {
let rendered = plain(&render(source, 40, &Theme::new()));
assert!(
rendered.contains("MBTerm structural BBCode error"),
"{rendered:?}"
);
}
}
#[test]
fn escaped_and_inline_code_structural_tags_stay_literal() {
assert_eq!(
plain(&render(r"\[box\]literal\[/box\]", 40, &Theme::new())),
"[box]literal[/box]"
);
assert_eq!(
plain(&render("`[box]literal[/box]`", 40, &Theme::new())),
"[box]literal[/box]"
);
assert!(plain(&render(
"unmatched ` marker [box]content[/box]",
40,
&Theme::new()
))
.contains('┌'));
}
#[test]
fn wrapped_blocks_and_quoted_tables_keep_their_rails() {
let quote = plain(&render("> 天地玄黄宇宙洪荒日月盈昃", 10, &Theme::new()));
assert!(quote.lines().count() > 1, "{quote:?}");
assert!(quote.lines().all(|line| line.starts_with(" │ ")));
assert!(quote.lines().all(|line| UnicodeWidthStr::width(line) <= 10));
let code = plain(&render(
"```\n天地玄黄宇宙洪荒日月盈昃\n```",
10,
&Theme::new(),
));
assert!(code.lines().filter(|line| line.starts_with("│ ")).count() > 1);
assert!(code.lines().all(|line| UnicodeWidthStr::width(line) <= 10));
let table = plain(&render(
"> | 名称 | 状态 |\n> | --- | --- |\n> | 长剑 | 完好 |",
24,
&Theme::new(),
));
assert!(table.starts_with(" │ ┌"), "{table:?}");
assert!(table.lines().all(|line| line.starts_with(" │ ")));
assert!(table.lines().all(|line| UnicodeWidthStr::width(line) <= 24));
}
#[test]
fn structural_colors_are_themable_and_code_language_falls_back() {
let mut theme = Theme::new();
for (name, color) in [
(QUOTE_STYLE, BasicColor::Red),
(LIST_STYLE, BasicColor::Green),
(RULE_STYLE, BasicColor::Yellow),
(CODE_STYLE, BasicColor::Blue),
("markdown-code-luau", BasicColor::Magenta),
] {
theme
.insert(name, TextStyle::new().foreground(Color::Basic(color)))
.unwrap();
}
let structures = render("> 引用\n\n1. 有序\n2. [x] 完成\n\n---", 20, &theme);
assert!(structures.contains(" \x1b[31m│\x1b[0m "));
assert!(structures.contains(" \x1b[32m1.\x1b[0m "));
assert!(structures.contains(" \x1b[32m☑\x1b[0m "));
assert!(structures.contains("\x1b[33m────────────────────\x1b[0m"));
let wrapped_quote = render("> 天地玄黄宇宙洪荒日月盈昃", 10, &theme);
assert_eq!(
wrapped_quote.lines().count(),
wrapped_quote.matches("\x1b[31m│").count()
);
let luau = render("```LuAu linenos\n天地玄黄宇宙洪荒日月盈昃\n```", 10, &theme);
assert!(luau.contains("\x1b[35m┌─"), "{luau:?}");
assert!(luau.matches("\x1b[35m│\x1b[0m").count() > 1, "{luau:?}");
assert!(luau.contains("\x1b[35m└────────┘\x1b[0m"), "{luau:?}");
let unknown = render("```unknown\nvalue\n```", 40, &theme);
assert!(unknown.contains("\x1b[34m┌─"), "{unknown:?}");
assert!(!unknown.contains("\x1b[35m┌─"), "{unknown:?}");
}
#[test]
fn renders_aligned_cjk_tables_with_wrapped_colored_cells() {
let mut theme = Theme::new();
theme
.insert(
"warning",
TextStyle::new()
.bold()
.foreground(Color::Basic(BasicColor::BrightYellow)),
)
.unwrap();
let source = concat!(
"| 名称 | 状态 | 说明 |\n",
"| :--- | :---: | ---: |\n",
"| 长剑 | [warning]警告[/warning] | 这是一段需要换行的很长说明 |"
);
let rendered = render(source, 32, &theme);
let plain = plain(&rendered);
assert!(rendered.contains("\x1b[1;93m警告"));
assert!(plain.contains("┌"));
assert!(plain.contains("╞"));
assert!(plain.contains("└"));
for line in plain.lines() {
assert!(UnicodeWidthStr::width(line) <= 32, "{line:?}");
}
}
}