mod ansi;
mod bbcode;
mod frame;
mod layout;
mod markdown;
mod syntax;
mod table;
use std::collections::BTreeMap;
pub use ansi::{strip_osc8_sequences, strip_terminal_sequences};
pub use bbcode::{
escape, strip_bbcode, BasicColor, BlinkStyle, Color, ParseColorError, TextStyle, UnderlineStyle,
};
mod catppuccin {
use crate::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 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 {
pub(crate) const fn top_left(self) -> char {
match self {
Self::Square => '┌',
Self::Rounded => '╭',
}
}
pub(crate) const fn top_right(self) -> char {
match self {
Self::Square => '┐',
Self::Rounded => '╮',
}
}
pub(crate) const fn bottom_left(self) -> char {
match self {
Self::Square => '└',
Self::Rounded => '╰',
}
}
pub(crate) const fn bottom_right(self) -> char {
match self {
Self::Square => '┘',
Self::Rounded => '╯',
}
}
}
#[derive(Clone, Debug)]
pub struct Theme {
styles: BTreeMap<String, TextStyle>,
corner_style: CornerStyle,
}
impl Default for Theme {
fn default() -> Self {
let styles = BTreeMap::from([
(
"markdown-heading".to_string(),
TextStyle::new().foreground(catppuccin::LAVENDER),
),
(
"markdown-quote".to_string(),
TextStyle::new().foreground(catppuccin::MAUVE),
),
(
"markdown-list".to_string(),
TextStyle::new().foreground(catppuccin::TEAL).bold(),
),
(
"markdown-rule".to_string(),
TextStyle::new().foreground(catppuccin::OVERLAY_0),
),
(
"markdown-code".to_string(),
TextStyle::new().foreground(catppuccin::OVERLAY_1),
),
(
"markdown-inline-code".to_string(),
TextStyle::new().foreground(catppuccin::PEACH),
),
(
"markdown-box".to_string(),
TextStyle::new().foreground(catppuccin::BLUE),
),
(
"markdown-hashtag".to_string(),
TextStyle::new().foreground(catppuccin::PINK).bold(),
),
(
"markdown-wikilink".to_string(),
TextStyle::new().foreground(catppuccin::SKY),
),
]);
Self {
styles,
corner_style: CornerStyle::Square,
}
}
}
impl Theme {
pub fn new() -> Self {
Self::default()
}
pub fn with_corner_style(mut self, corner_style: CornerStyle) -> Self {
self.corner_style = corner_style;
self
}
pub fn corner_style(&self) -> CornerStyle {
self.corner_style
}
pub fn insert(
&mut self,
name: impl AsRef<str>,
style: TextStyle,
) -> Result<Option<TextStyle>, ThemeError> {
let name = name.as_ref().to_ascii_lowercase();
if name.is_empty()
|| !name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
{
return Err(ThemeError {
name,
kind: ThemeErrorKind::InvalidSyntax,
});
}
if bbcode::is_reserved_style_name(&name) || mbdown::is_structural_tag_name(&name) {
return Err(ThemeError {
name,
kind: ThemeErrorKind::Reserved,
});
}
Ok(self.styles.insert(name, style))
}
pub(crate) fn get(&self, name: &str) -> Option<&TextStyle> {
self.styles.get(name)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ThemeError {
name: String,
kind: ThemeErrorKind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ThemeErrorKind {
InvalidSyntax,
Reserved,
}
impl std::fmt::Display for ThemeError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.kind {
ThemeErrorKind::InvalidSyntax => {
write!(formatter, "invalid theme style name {:?}", self.name)
}
ThemeErrorKind::Reserved => {
write!(
formatter,
"theme style name {:?} is reserved by BBCode",
self.name
)
}
}
}
}
impl std::error::Error for ThemeError {}
#[derive(Clone, Debug)]
pub struct Renderer {
width: usize,
theme: Theme,
render_front_matter: bool,
}
impl Renderer {
pub fn new(width: usize) -> Self {
Self {
width,
theme: Theme::new(),
render_front_matter: false,
}
}
pub fn with_theme(width: usize, theme: Theme) -> Self {
Self {
width,
theme,
render_front_matter: false,
}
}
pub fn with_front_matter(mut self, enabled: bool) -> Self {
self.render_front_matter = enabled;
self
}
pub fn width(&self) -> usize {
self.width
}
pub fn theme(&self) -> &Theme {
&self.theme
}
pub fn render(&self, input: &str) -> String {
match mbdown::parse(input) {
Ok(document) => self.render_document(&document),
Err(error) => markdown::render_error(&error, &self.theme),
}
}
pub fn render_document(&self, document: &mbdown::Document<'_>) -> String {
markdown::render_document(document, self.width, &self.theme, self.render_front_matter)
}
pub fn render_at_width(&self, input: &str, width: usize) -> String {
match mbdown::parse(input) {
Ok(document) => self.render_document_at_width(&document, width),
Err(error) => markdown::render_error(&error, &self.theme),
}
}
pub fn render_document_at_width(
&self,
document: &mbdown::Document<'_>,
width: usize,
) -> String {
markdown::render_document(document, width, &self.theme, self.render_front_matter)
}
pub fn render_bbcode(&self, input: &str) -> String {
bbcode::render(input, true, &self.theme)
}
pub fn strip_bbcode(&self, input: &str) -> String {
bbcode::render(input, false, &self.theme)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn theme_rejects_invalid_and_reserved_style_names() {
let mut theme = Theme::new();
for name in [
"bad=name",
"",
"red",
"BOLD",
"color",
"blink",
"inverse",
"overline",
"underline-color",
"link",
"box",
"center",
"right",
"indent",
"Columns",
"column",
] {
assert!(
theme.insert(name, TextStyle::default()).is_err(),
"{name} should be rejected"
);
}
assert!(theme.insert("mob", TextStyle::default()).is_ok());
assert!(theme.insert("quest-target", TextStyle::default()).is_ok());
}
#[test]
fn public_extended_style_builders_render_exact_sgr() {
let mut theme = Theme::new();
theme
.insert(
"extended",
TextStyle::new()
.blink(BlinkStyle::Rapid)
.inverse()
.overline()
.underline_style(UnderlineStyle::Dashed)
.underline_color(Color::Basic(BasicColor::BrightCyan)),
)
.unwrap();
assert_eq!(
Renderer::with_theme(80, theme).render_bbcode("[extended]x[/extended]"),
"\x1b[4:5;6;7;53;58;5;14mx\x1b[0m"
);
}
#[test]
fn semantic_tags_render_and_strip_with_their_theme() {
let mut theme = Theme::new();
theme
.insert(
"mob",
TextStyle::new()
.bold()
.foreground(Color::Basic(BasicColor::BrightMagenta)),
)
.unwrap();
let renderer = Renderer::with_theme(80, theme);
assert_eq!(
renderer.render_bbcode("[mob]木人[/mob]"),
"\x1b[1;95m木人\x1b[0m"
);
assert_eq!(renderer.strip_bbcode("[mob]木人[/mob]"), "木人");
assert_eq!(
renderer.render_bbcode("[color=mob]木人[/color]"),
"\x1b[1;95m木人\x1b[0m"
);
}
#[test]
fn per_call_width_preserves_the_configured_width_and_theme() {
let mut theme = Theme::new();
theme
.insert(
"accent",
TextStyle::new().foreground(Color::Basic(BasicColor::Red)),
)
.unwrap();
let renderer = Renderer::with_theme(10, theme);
let source = "[accent]天地玄黄[/accent]";
let configured = renderer.render(source);
let narrow = renderer.render_at_width(source, 6);
assert_eq!(renderer.width(), 10);
assert!(!configured.contains('\n'));
assert!(narrow.contains('\n'));
assert!(configured.contains("\x1b[31m"));
assert!(narrow.contains("\x1b[31m"));
}
#[test]
fn front_matter_is_hidden_by_default_and_can_be_rendered() {
let source = "---\ntitle: Shown\ntags: [one, two]\n---\n# Visible";
let hidden = strip_terminal_sequences(&Renderer::new(80).render(source));
assert!(hidden.ends_with("Visible"));
assert!(!hidden.contains("yaml"));
assert!(!hidden.contains("title: Shown"));
let renderer = Renderer::new(80).with_front_matter(true);
let yaml = strip_terminal_sequences(&renderer.render(source));
assert!(yaml.contains("yaml"));
assert!(yaml.contains("title: Shown"));
assert!(yaml.contains("tags: [one, two]"));
assert!(yaml.ends_with("Visible"));
assert!(!yaml.contains("---"));
let toml =
strip_terminal_sequences(&renderer.render("+++\ntitle = \"Shown\"\n+++\nVisible"));
assert!(toml.contains("toml"));
assert!(toml.contains("title = \"Shown\""));
assert!(toml.ends_with("Visible"));
assert!(!toml.contains("+++"));
}
#[test]
fn math_has_native_display_and_source_fallbacks() {
let rendered = strip_terminal_sequences(
&Renderer::new(40).render("Inline $x + 1$.\n\n$$\n\\frac{a}{b}\n$$"),
);
assert!(rendered.contains("Inline $x + 1$."));
assert!(rendered.contains("math"));
assert!(rendered.contains('─'));
assert!(rendered.contains('a'));
assert!(rendered.contains('b'));
let labels = strip_terminal_sequences(&Renderer::new(80).render(concat!(
"$$\n",
"\\frac{\\text{营业收入}}{\\text{总资产}} \\times ",
"\\frac{\\text{净利润}}{\\text{营业收入}} = ",
"\\frac{\\text{净利润}}{\\text{总资产}} = ",
"\\operatorname{ROA}\n",
"$$"
)));
assert!(labels.contains("营业收入"));
assert!(labels.contains("总资产"));
assert!(labels.contains("ROA"));
assert!(!labels.contains("text营业收入"));
assert!(!labels.contains("operatorname"));
assert!(labels.contains("──────────×────────── = ──────── = ROA"));
let emoji = strip_terminal_sequences(
&Renderer::new(80).render("$$\n\\frac{🧑💻👩💻}{👥} = \\text{程序员浓度}\n$$"),
);
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 fallback = strip_terminal_sequences(&Renderer::new(40).render("$$\n\\left( x\n$$"));
assert!(fallback.contains("tex"));
assert!(fallback.contains("\\left( x"));
let too_wide = strip_terminal_sequences(&Renderer::new(10).render("$$\nabcdefghijk\n$$"));
assert!(too_wide.contains("tex"));
assert!(too_wide.contains('a'));
assert!(too_wide.contains('k'));
}
}