use std::collections::BTreeMap;
use std::io::{self, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use clap::{Parser, ValueEnum};
use mbterm::{
strip_terminal_sequences, BlinkStyle, Color, CornerStyle, Renderer, TextStyle, Theme,
UnderlineStyle,
};
use serde::Deserialize;
use terminal_size::{terminal_size, Width};
const DEFAULT_WIDTH: usize = 80;
#[derive(Debug, Parser)]
#[command(
name = "mbterm",
version,
about = "Render Markdown or MBDown as terminal text"
)]
struct Args {
#[arg(value_name = "FILE")]
input: Option<PathBuf>,
#[arg(short, long, value_name = "COLUMNS", value_parser = parse_width)]
width: Option<usize>,
#[arg(short, long, value_name = "FILE")]
theme: Option<PathBuf>,
#[arg(long, value_enum, default_value_t = ColorMode::Auto)]
color: ColorMode,
#[arg(long, value_enum)]
corners: Option<CornerConfig>,
#[arg(long)]
front_matter: bool,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)]
enum ColorMode {
#[default]
Auto,
Always,
Never,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, ValueEnum)]
#[serde(rename_all = "kebab-case")]
enum CornerConfig {
Square,
Rounded,
}
impl From<CornerConfig> for CornerStyle {
fn from(value: CornerConfig) -> Self {
match value {
CornerConfig::Square => Self::Square,
CornerConfig::Rounded => Self::Rounded,
}
}
}
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct ThemeConfig {
corners: Option<CornerConfig>,
styles: BTreeMap<String, StyleConfig>,
}
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum BlinkConfig {
Slow,
Rapid,
}
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum UnderlineKind {
Single,
Double,
Curly,
Dotted,
Dashed,
}
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(untagged)]
enum UnderlineConfig {
Legacy(bool),
Style(UnderlineKind),
}
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct StyleConfig {
foreground: Option<String>,
background: Option<String>,
underline_color: Option<String>,
bold: bool,
dim: bool,
italic: bool,
underline: Option<UnderlineConfig>,
blink: Option<BlinkConfig>,
inverse: bool,
strike: bool,
overline: bool,
}
impl StyleConfig {
fn build(&self, name: &str) -> Result<TextStyle, String> {
let underline_enabled =
!matches!(self.underline, None | Some(UnderlineConfig::Legacy(false)));
if self.foreground.is_none()
&& self.background.is_none()
&& self.underline_color.is_none()
&& !self.bold
&& !self.dim
&& !self.italic
&& !underline_enabled
&& self.blink.is_none()
&& !self.inverse
&& !self.strike
&& !self.overline
{
return Err(format!(
"theme style {name:?} must set a color or text attribute"
));
}
let mut style = TextStyle::new();
if let Some(value) = &self.foreground {
style = style.foreground(parse_color(name, "foreground", value)?);
}
if let Some(value) = &self.background {
style = style.background(parse_color(name, "background", value)?);
}
if self.bold {
style = style.bold();
}
if self.dim {
style = style.dim();
}
if self.italic {
style = style.italic();
}
match self.underline {
None | Some(UnderlineConfig::Legacy(false)) => {}
Some(UnderlineConfig::Legacy(true))
| Some(UnderlineConfig::Style(UnderlineKind::Single)) => {
style = style.underline();
}
Some(UnderlineConfig::Style(UnderlineKind::Double)) => {
style = style.underline_style(UnderlineStyle::Double);
}
Some(UnderlineConfig::Style(UnderlineKind::Curly)) => {
style = style.underline_style(UnderlineStyle::Curly);
}
Some(UnderlineConfig::Style(UnderlineKind::Dotted)) => {
style = style.underline_style(UnderlineStyle::Dotted);
}
Some(UnderlineConfig::Style(UnderlineKind::Dashed)) => {
style = style.underline_style(UnderlineStyle::Dashed);
}
}
match self.blink {
None => {}
Some(BlinkConfig::Slow) => style = style.blink(BlinkStyle::Slow),
Some(BlinkConfig::Rapid) => style = style.blink(BlinkStyle::Rapid),
}
if self.inverse {
style = style.inverse();
}
if self.strike {
style = style.strike();
}
if self.overline {
style = style.overline();
}
if let Some(value) = &self.underline_color {
style = style.underline_color(parse_color(name, "underline_color", value)?);
}
Ok(style)
}
}
fn main() -> ExitCode {
match run(Args::parse()) {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("mbterm: {error}");
ExitCode::FAILURE
}
}
}
fn run(args: Args) -> Result<(), String> {
let (source, source_label) = read_source(args.input.as_deref())?;
let document = mbdown::parse(&source).map_err(|error| format!("{source_label}: {error}"))?;
let mut theme = load_theme(args.theme.as_deref())?;
if let Some(corners) = args.corners {
theme = theme.with_corner_style(corners.into());
}
let width = args.width.unwrap_or_else(detected_width);
let renderer = Renderer::with_theme(width, theme).with_front_matter(args.front_matter);
let rendered = renderer.render_document(&document);
let output = if emit_control_sequences(args.color) {
rendered
} else {
strip_terminal_sequences(&rendered)
};
write_output(&output)
}
fn read_source(path: Option<&Path>) -> Result<(String, String), String> {
match path {
None => read_stdin(),
Some(path) if path == Path::new("-") => read_stdin(),
Some(path) => std::fs::read_to_string(path)
.map(|source| (source, path.display().to_string()))
.map_err(|error| format!("failed to read {}: {error}", path.display())),
}
}
fn read_stdin() -> Result<(String, String), String> {
let mut source = String::new();
io::stdin()
.read_to_string(&mut source)
.map_err(|error| format!("failed to read stdin: {error}"))?;
Ok((source, "stdin".to_string()))
}
fn load_theme(path: Option<&Path>) -> Result<Theme, String> {
let mut theme = Theme::new();
let Some(path) = path else {
return Ok(theme);
};
let source = std::fs::read_to_string(path)
.map_err(|error| format!("failed to read theme {}: {error}", path.display()))?;
let config: ThemeConfig = toml::from_str(&source)
.map_err(|error| format!("failed to parse theme {}: {error}", path.display()))?;
if let Some(corners) = config.corners {
theme = theme.with_corner_style(corners.into());
}
for (name, config) in config.styles {
theme
.insert(&name, config.build(&name)?)
.map_err(|error| format!("theme {}: {error}", path.display()))?;
}
Ok(theme)
}
fn emit_control_sequences(mode: ColorMode) -> bool {
match mode {
ColorMode::Always => true,
ColorMode::Never => false,
ColorMode::Auto => io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none(),
}
}
fn write_output(output: &str) -> Result<(), String> {
let mut stdout = io::stdout().lock();
let result = stdout
.write_all(output.as_bytes())
.and_then(|()| {
(!output.ends_with('\n'))
.then(|| stdout.write_all(b"\n"))
.transpose()
})
.and_then(|_| stdout.flush());
match result {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::BrokenPipe => Ok(()),
Err(error) => Err(format!("failed to write output: {error}")),
}
}
fn parse_color(style: &str, field: &str, value: &str) -> Result<Color, String> {
value.parse().map_err(|_| {
format!(
"theme style {style:?} has invalid {field} color {value:?}; expected a named, indexed, or #RRGGBB color"
)
})
}
fn parse_width(value: &str) -> Result<usize, String> {
let width = value
.parse::<usize>()
.map_err(|_| format!("invalid display width {value:?}"))?;
if width == 0 {
return Err("display width must be greater than zero".to_string());
}
Ok(width)
}
fn detected_width() -> usize {
terminal_size()
.map(|(Width(width), _)| usize::from(width))
.filter(|width| *width > 0)
.unwrap_or(DEFAULT_WIDTH)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn command_line_accepts_files_stdin_width_and_color_policy() {
let args = Args::try_parse_from([
"mbterm",
"--width",
"72",
"--color",
"never",
"--corners",
"rounded",
"--front-matter",
"document.mb",
])
.unwrap();
assert_eq!(args.input.as_deref(), Some(Path::new("document.mb")));
assert_eq!(args.width, Some(72));
assert_eq!(args.color, ColorMode::Never);
assert_eq!(args.corners, Some(CornerConfig::Rounded));
assert!(args.front_matter);
let stdin = Args::try_parse_from(["mbterm", "-"]).unwrap();
assert_eq!(stdin.input.as_deref(), Some(Path::new("-")));
}
#[test]
fn fixed_width_must_be_positive() {
assert_eq!(parse_width("1").unwrap(), 1);
assert!(parse_width("0").is_err());
assert!(parse_width("wide").is_err());
}
#[test]
fn plain_output_removes_terminal_sequences_without_losing_text() {
let rendered = Renderer::new(80).render("[red]warning[/red]");
assert!(rendered.contains("\x1b["));
assert_eq!(strip_terminal_sequences(&rendered), "warning");
}
#[test]
fn malformed_structural_markup_is_an_input_error() {
let error = mbdown::parse("[box]open").unwrap_err();
assert!(error.to_string().contains("missing [/box]"));
}
#[test]
fn rounded_corners_apply_to_boxes_code_blocks_and_tables() {
let theme = Theme::new().with_corner_style(CornerStyle::Rounded);
let rendered = Renderer::with_theme(40, theme).render(concat!(
"[box]box[/box]\n\n",
"```text\ncode\n```\n\n",
"| A | B |\n| --- | --- |\n| one | two |"
));
assert_eq!(rendered.matches('â•').count(), 3, "{rendered:?}");
assert_eq!(rendered.matches('â•®').count(), 3, "{rendered:?}");
assert_eq!(rendered.matches('â•°').count(), 3, "{rendered:?}");
assert_eq!(rendered.matches('╯').count(), 3, "{rendered:?}");
}
#[test]
fn theme_file_supports_extended_styles_and_emits_exact_sgr() {
let config: ThemeConfig = toml::from_str(
r##"
[styles.notice]
foreground = "#ff1200"
background = "17"
bold = true
dim = true
italic = true
underline = "curly"
blink = "rapid"
inverse = true
strike = true
overline = true
underline_color = "bright-white"
"##,
)
.unwrap();
let mut theme = Theme::new();
theme
.insert("notice", config.styles["notice"].build("notice").unwrap())
.unwrap();
assert_eq!(
Renderer::with_theme(80, theme).render_bbcode("[notice]x[/notice]"),
"\x1b[1;2;3;4:3;6;7;9;53;38;2;255;18;0;48;5;17;58;5;15mx\x1b[0m"
);
}
#[test]
fn theme_file_supports_legacy_and_named_style_values() {
let config: ThemeConfig = toml::from_str(concat!(
"[styles.legacy]\nunderline = true\n",
"[styles.disabled]\nforeground = \"red\"\nunderline = false\n",
"[styles.single]\nunderline = \"single\"\n",
"[styles.double]\nunderline = \"double\"\n",
"[styles.curly]\nunderline = \"curly\"\n",
"[styles.dotted]\nunderline = \"dotted\"\n",
"[styles.dashed]\nunderline = \"dashed\"\n",
"[styles.slow]\nblink = \"slow\"\n",
"[styles.rapid]\nblink = \"rapid\"\n",
"[styles.named]\nunderline_color = \"blue\"\n",
"[styles.indexed]\nunderline_color = \"196\"\n",
"[styles.rgb]\nunderline_color = \"#12abef\"\n",
"[styles.flags]\ninverse = true\noverline = true\n"
))
.unwrap();
let mut theme = Theme::new();
for (name, style) in config.styles {
theme.insert(&name, style.build(&name).unwrap()).unwrap();
}
let renderer = Renderer::with_theme(80, theme);
for (name, expected) in [
("legacy", "4"),
("disabled", "31"),
("single", "4"),
("double", "4:2"),
("curly", "4:3"),
("dotted", "4:4"),
("dashed", "4:5"),
("slow", "5"),
("rapid", "6"),
("named", "58;5;4"),
("indexed", "58;5;196"),
("rgb", "58;2;18;171;239"),
("flags", "7;53"),
] {
assert_eq!(
renderer.render_bbcode(&format!("[{name}]x[/{name}]")),
format!("\x1b[{expected}mx\x1b[0m"),
"{name}"
);
}
}
#[test]
fn theme_file_shape_and_values_are_strict() {
for (label, source, parses) in [
("top-level unknown", "unknown = true\n", false),
(
"style unknown",
"[styles.notice]\nforeground = \"yellow\"\nunknown = true\n",
false,
),
(
"invalid underline",
"[styles.notice]\nunderline = \"wavy\"\n",
false,
),
(
"invalid underline type",
"[styles.notice]\nunderline = 1\n",
false,
),
(
"invalid blink",
"[styles.notice]\nblink = \"medium\"\n",
false,
),
("boolean blink", "[styles.notice]\nblink = true\n", false),
("empty", "[styles.notice]\nunderline = false\n", true),
(
"invalid underline color",
"[styles.notice]\nunderline_color = \"not-a-color\"\n",
true,
),
] {
let parsed = toml::from_str::<ThemeConfig>(source);
assert_eq!(parsed.is_ok(), parses, "{label}: {parsed:?}");
if let Ok(config) = parsed {
assert!(config.styles["notice"].build("notice").is_err(), "{label}");
}
}
}
#[test]
fn theme_file_configures_rounded_corners() {
let config: ThemeConfig = toml::from_str("corners = \"rounded\"\n").unwrap();
assert_eq!(config.corners, Some(CornerConfig::Rounded));
}
}