use crate::ansi;
use crate::Theme;
pub(crate) const RESET: &str = "\x1b[0m";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BasicColor {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
BrightBlack,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
BrightWhite,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Color {
Basic(BasicColor),
Indexed(u8),
Rgb(u8, u8, u8),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BlinkStyle {
Slow,
Rapid,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnderlineStyle {
Single,
Double,
Curly,
Dotted,
Dashed,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TextStyle {
foreground: Option<Color>,
background: Option<Color>,
bold: bool,
dim: bool,
italic: bool,
underline: Option<UnderlineStyle>,
blink: Option<BlinkStyle>,
inverse: bool,
strike: bool,
overline: bool,
underline_color: Option<Color>,
}
impl TextStyle {
pub fn new() -> Self {
Self::default()
}
pub fn foreground(mut self, color: Color) -> Self {
self.foreground = Some(color);
self
}
pub fn background(mut self, color: Color) -> Self {
self.background = Some(color);
self
}
pub(crate) fn background_color(&self) -> Option<Color> {
self.background
}
pub fn bold(mut self) -> Self {
self.bold = true;
self
}
pub fn dim(mut self) -> Self {
self.dim = true;
self
}
pub fn italic(mut self) -> Self {
self.italic = true;
self
}
pub fn underline(mut self) -> Self {
self.underline = Some(UnderlineStyle::Single);
self
}
pub fn underline_style(mut self, style: UnderlineStyle) -> Self {
self.underline = Some(style);
self
}
pub fn blink(mut self, style: BlinkStyle) -> Self {
self.blink = Some(style);
self
}
pub fn inverse(mut self) -> Self {
self.inverse = true;
self
}
pub fn strike(mut self) -> Self {
self.strike = true;
self
}
pub fn overline(mut self) -> Self {
self.overline = true;
self
}
pub fn underline_color(mut self, color: Color) -> Self {
self.underline_color = Some(color);
self
}
pub(crate) fn underline_color_value(&self) -> Option<Color> {
self.underline_color
}
pub(crate) fn sgr(&self) -> String {
let mut codes = Vec::with_capacity(11);
if self.bold {
codes.push("1".to_string());
}
if self.dim {
codes.push("2".to_string());
}
if self.italic {
codes.push("3".to_string());
}
if let Some(style) = self.underline {
codes.push(style.sgr().to_string());
}
if let Some(style) = self.blink {
codes.push(style.sgr().to_string());
}
if self.inverse {
codes.push("7".to_string());
}
if self.strike {
codes.push("9".to_string());
}
if self.overline {
codes.push("53".to_string());
}
if let Some(color) = self.foreground {
codes.push(color.sgr(ColorTarget::Foreground));
}
if let Some(color) = self.background {
codes.push(color.sgr(ColorTarget::Background));
}
if let Some(color) = self.underline_color {
codes.push(color.sgr(ColorTarget::Underline));
}
codes.join(";")
}
}
impl BlinkStyle {
fn sgr(self) -> &'static str {
match self {
Self::Slow => "5",
Self::Rapid => "6",
}
}
}
impl UnderlineStyle {
fn sgr(self) -> &'static str {
match self {
Self::Single => "4",
Self::Double => "4:2",
Self::Curly => "4:3",
Self::Dotted => "4:4",
Self::Dashed => "4:5",
}
}
}
#[derive(Clone, Copy)]
enum ColorTarget {
Foreground,
Background,
Underline,
}
impl Color {
fn sgr(self, target: ColorTarget) -> String {
match (self, target) {
(Self::Basic(color), ColorTarget::Foreground) => color.sgr(false).to_string(),
(Self::Basic(color), ColorTarget::Background) => color.sgr(true).to_string(),
(Self::Basic(color), ColorTarget::Underline) => {
format!("58;5;{}", color.index())
}
(Self::Indexed(index), target) => format!("{};5;{index}", target.extended_code()),
(Self::Rgb(red, green, blue), target) => {
format!("{};2;{red};{green};{blue}", target.extended_code())
}
}
}
}
impl ColorTarget {
fn extended_code(self) -> u8 {
match self {
Self::Foreground => 38,
Self::Background => 48,
Self::Underline => 58,
}
}
}
impl std::str::FromStr for Color {
type Err = ParseColorError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
parse_color(&value.to_ascii_lowercase()).ok_or_else(|| ParseColorError {
value: value.to_string(),
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParseColorError {
value: String,
}
impl std::fmt::Display for ParseColorError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "invalid terminal color {:?}", self.value)
}
}
impl std::error::Error for ParseColorError {}
impl BasicColor {
fn index(self) -> u8 {
match self {
Self::Black => 0,
Self::Red => 1,
Self::Green => 2,
Self::Yellow => 3,
Self::Blue => 4,
Self::Magenta => 5,
Self::Cyan => 6,
Self::White => 7,
Self::BrightBlack => 8,
Self::BrightRed => 9,
Self::BrightGreen => 10,
Self::BrightYellow => 11,
Self::BrightBlue => 12,
Self::BrightMagenta => 13,
Self::BrightCyan => 14,
Self::BrightWhite => 15,
}
}
fn sgr(self, background: bool) -> u8 {
let index = self.index();
match (background, index >= 8) {
(false, false) => 30 + index,
(true, false) => 40 + index,
(false, true) => 90 + index - 8,
(true, true) => 100 + index - 8,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum LinkOwner {
Markup,
Typed(u64),
}
#[derive(Clone, Debug)]
enum ActiveFormat {
Sgr { tag: String, sgr: String },
Link { target: String, owner: LinkOwner },
}
impl ActiveFormat {
fn markup_tag(&self) -> Option<&str> {
match self {
Self::Sgr { tag, .. } => Some(tag),
Self::Link {
owner: LinkOwner::Markup,
..
} => Some("link"),
Self::Link {
owner: LinkOwner::Typed(_),
..
} => None,
}
}
}
pub(crate) struct FormatSession<'a> {
ansi_enabled: bool,
theme: &'a Theme,
output: String,
formats: Vec<ActiveFormat>,
}
impl<'a> FormatSession<'a> {
pub(crate) fn new(ansi_enabled: bool, theme: &'a Theme) -> Self {
Self {
ansi_enabled,
theme,
output: String::new(),
formats: Vec::new(),
}
}
pub(crate) fn push_markup(&mut self, input: &str) {
self.output.reserve(input.len());
let mut index = 0;
while index < input.len() {
let rest = &input[index..];
let mut chars = rest.chars();
let Some(ch) = chars.next() else { break };
let char_len = ch.len_utf8();
if ch == '\\' {
if let Some(next) = chars.next() {
if matches!(next, '[' | ']' | '\\') {
self.output.push(next);
index += char_len + next.len_utf8();
continue;
}
}
}
if ch == '[' {
if let Some(end) = find_tag_end(input, index + char_len) {
let body = &input[index + char_len..end];
if apply_tag(
body,
self.ansi_enabled,
self.theme,
&mut self.formats,
&mut self.output,
) {
index = end + 1;
continue;
}
}
}
if matches!(ch, '\x1b' | '\u{0080}'..='\u{009f}') {
if let Some(ansi::Token::Sequence(sequence)) = ansi::tokens(rest).next() {
index += sequence.as_str().len();
continue;
}
}
if ch == '\n' {
boundary(&self.formats, self.ansi_enabled, &mut self.output, '\n');
} else if is_filtered_text_control(ch) {
} else {
self.output.push(ch);
}
index += char_len;
}
}
pub(crate) fn link_start(&mut self, id: u64, target: &str) {
if self.ansi_enabled {
close_current_link(&self.formats, &mut self.output);
push_link_open(target, &mut self.output);
}
self.formats.push(ActiveFormat::Link {
target: target.to_string(),
owner: LinkOwner::Typed(id),
});
}
pub(crate) fn link_end(&mut self, id: u64) {
let Some(index) = self.formats.iter().rposition(|format| {
matches!(
format,
ActiveFormat::Link {
owner: LinkOwner::Typed(candidate),
..
} if *candidate == id
)
}) else {
return;
};
let has_sgr = self
.formats
.iter()
.any(|format| matches!(format, ActiveFormat::Sgr { .. }));
if self.ansi_enabled {
close_current_link(&self.formats, &mut self.output);
}
self.formats.truncate(index);
if self.ansi_enabled {
if has_sgr {
rebuild_sgr(&self.formats, &mut self.output);
}
open_current_link(&self.formats, &mut self.output);
}
}
pub(crate) fn finish(mut self) -> String {
close_at_end(&self.formats, self.ansi_enabled, &mut self.output);
self.output
}
}
pub(crate) fn render(input: &str, ansi_enabled: bool, theme: &Theme) -> String {
let mut formatter = FormatSession::new(ansi_enabled, theme);
formatter.push_markup(input);
formatter.finish()
}
pub fn strip_bbcode(input: &str) -> String {
render(input, false, &Theme::new())
}
pub fn escape(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for ch in value.chars() {
if ch.is_ascii_punctuation() {
escaped.push('\\');
}
escaped.push(ch);
}
escaped
}
pub(crate) fn find_tag_end(input: &str, start: usize) -> Option<usize> {
let mut quoted = false;
let mut escaped = false;
for (offset, ch) in input.get(start..)?.char_indices() {
if escaped {
escaped = false;
} else if quoted && ch == '\\' {
escaped = true;
} else if ch == '"' {
quoted = !quoted;
} else if ch == ']' && !quoted {
return Some(start + offset);
}
}
None
}
pub(crate) fn is_tag(body: &str, theme: &Theme) -> bool {
let body = body.trim();
if body.is_empty() {
return false;
}
if body.eq_ignore_ascii_case("br") || body.eq_ignore_ascii_case("reset") || body == "/" {
return true;
}
if let Some(closing) = body.strip_prefix('/') {
let closing = closing.trim();
return !closing.contains('=') && is_closing_tag(closing, theme);
}
parse_format(body, theme).is_some()
}
fn is_closing_tag(name: &str, theme: &Theme) -> bool {
let name = name.to_ascii_lowercase();
matches!(
name.as_str(),
"b" | "bold"
| "dim"
| "i"
| "italic"
| "u"
| "underline"
| "underline-color"
| "blink"
| "inverse"
| "s"
| "strike"
| "overline"
| "color"
| "fg"
| "bg"
| "link"
) || named_color(&name).is_some()
|| theme.get(&name).is_some()
}
fn apply_tag(
body: &str,
ansi_enabled: bool,
theme: &Theme,
formats: &mut Vec<ActiveFormat>,
output: &mut String,
) -> bool {
let body = body.trim();
if body.is_empty() {
return false;
}
if body.eq_ignore_ascii_case("br") {
boundary(formats, ansi_enabled, output, '\n');
return true;
}
if body.eq_ignore_ascii_case("reset") {
if ansi_enabled {
close_current_link(formats, output);
output.push_str(RESET);
}
let typed_depth = formats
.iter()
.rposition(|format| {
matches!(
format,
ActiveFormat::Link {
owner: LinkOwner::Typed(_),
..
}
)
})
.map_or(0, |index| index + 1);
formats.truncate(typed_depth);
if ansi_enabled {
open_current_link(formats, output);
}
return true;
}
if let Some(closing) = body.strip_prefix('/') {
let closing = closing.trim();
let matches = formats.last().is_some_and(|format| {
format
.markup_tag()
.is_some_and(|tag| closing.is_empty() || tag.eq_ignore_ascii_case(closing))
});
if !matches {
return false;
}
let removed = formats.pop().expect("a matching format exists");
if ansi_enabled {
match removed {
ActiveFormat::Sgr { .. } => rebuild_sgr(formats, output),
ActiveFormat::Link { target, .. } => {
if !target.is_empty() {
output.push_str(ansi::OSC8_CLOSE);
}
open_current_link(formats, output);
}
}
}
return true;
}
let Some(format) = parse_format(body, theme) else {
return false;
};
if ansi_enabled {
match &format {
ActiveFormat::Sgr { sgr, .. } => push_sgr(sgr, output),
ActiveFormat::Link { target, .. } => {
close_current_link(formats, output);
push_link_open(target, output);
}
}
}
formats.push(format);
true
}
fn parse_format(tag: &str, theme: &Theme) -> Option<ActiveFormat> {
let (name, value) = tag
.split_once('=')
.map_or((tag.trim(), None), |(name, value)| {
(name.trim(), Some(value.trim()))
});
let lower_name = name.to_ascii_lowercase();
let (canonical, sgr) = match (lower_name.as_str(), value) {
("b" | "bold", None) => (lower_name.as_str(), "1".to_string()),
("dim", None) => ("dim", "2".to_string()),
("i" | "italic", None) => (lower_name.as_str(), "3".to_string()),
("u" | "underline", None) => (lower_name.as_str(), "4".to_string()),
("u" | "underline", Some(value)) => (
lower_name.as_str(),
parse_underline_style(value)?.sgr().to_string(),
),
("blink", None) => ("blink", "5".to_string()),
("blink", Some(value)) => ("blink", parse_blink_style(value)?.sgr().to_string()),
("inverse", None) => ("inverse", "7".to_string()),
("s" | "strike", None) => (lower_name.as_str(), "9".to_string()),
("overline", None) => ("overline", "53".to_string()),
("color" | "fg", Some(value)) => (
lower_name.as_str(),
color_or_theme(value, ColorTarget::Foreground, theme)?,
),
("bg", Some(value)) => ("bg", color_or_theme(value, ColorTarget::Background, theme)?),
("underline-color", Some(value)) => (
"underline-color",
underline_color(value, theme)?.sgr(ColorTarget::Underline),
),
("link", Some(value)) => {
return Some(ActiveFormat::Link {
target: parse_link_target(value)?,
owner: LinkOwner::Markup,
});
}
(name, None) => (name, named_style(name, theme)?),
_ => return None,
};
Some(ActiveFormat::Sgr {
tag: canonical.to_string(),
sgr,
})
}
fn parse_underline_style(value: &str) -> Option<UnderlineStyle> {
Some(match value.to_ascii_lowercase().as_str() {
"single" => UnderlineStyle::Single,
"double" => UnderlineStyle::Double,
"curly" => UnderlineStyle::Curly,
"dotted" => UnderlineStyle::Dotted,
"dashed" => UnderlineStyle::Dashed,
_ => return None,
})
}
fn parse_blink_style(value: &str) -> Option<BlinkStyle> {
Some(match value.to_ascii_lowercase().as_str() {
"slow" => BlinkStyle::Slow,
"rapid" => BlinkStyle::Rapid,
_ => return None,
})
}
fn parse_link_target(value: &str) -> Option<String> {
if !value.starts_with('"') {
return Some(value.to_string());
}
let mut target = String::with_capacity(value.len().saturating_sub(2));
let mut chars = value[1..].char_indices();
while let Some((offset, ch)) = chars.next() {
match ch {
'"' => {
let rest = &value[1 + offset + ch.len_utf8()..];
return rest.trim().is_empty().then_some(target);
}
'\\' => match chars.next() {
Some((_, escaped @ ('"' | '\\'))) => target.push(escaped),
Some((_, other)) => {
target.push('\\');
target.push(other);
}
None => return None,
},
_ => target.push(ch),
}
}
None
}
fn named_style(name: &str, theme: &Theme) -> Option<String> {
if let Some(style) = theme.get(name) {
return Some(style.sgr());
}
Some(
TextStyle::new()
.foreground(Color::Basic(named_color(name)?))
.sgr(),
)
}
fn color_or_theme(value: &str, target: ColorTarget, theme: &Theme) -> Option<String> {
let normalized = value.trim().to_ascii_lowercase();
match target {
ColorTarget::Foreground => {
if let Some(style) = theme.get(&normalized) {
return Some(style.sgr());
}
parse_color(&normalized).map(|color| color.sgr(target))
}
ColorTarget::Background => {
background_color(&normalized, theme).map(|color| color.sgr(target))
}
ColorTarget::Underline => {
underline_color(&normalized, theme).map(|color| color.sgr(target))
}
}
}
fn underline_color(value: &str, theme: &Theme) -> Option<Color> {
let value = value.trim().to_ascii_lowercase();
parse_color(&value).or_else(|| theme.get(&value)?.underline_color_value())
}
pub(crate) fn background_color(value: &str, theme: &Theme) -> Option<Color> {
let value = value.trim().to_ascii_lowercase();
parse_color(&value).or_else(|| theme.get(&value)?.background_color())
}
pub(crate) fn background_sequence(color: Color) -> String {
format!("\x1b[{}m", color.sgr(ColorTarget::Background))
}
pub(crate) fn color_value(color: Color) -> String {
match color {
Color::Basic(color) => match color {
BasicColor::Black => "black".to_string(),
BasicColor::Red => "red".to_string(),
BasicColor::Green => "green".to_string(),
BasicColor::Yellow => "yellow".to_string(),
BasicColor::Blue => "blue".to_string(),
BasicColor::Magenta => "magenta".to_string(),
BasicColor::Cyan => "cyan".to_string(),
BasicColor::White => "white".to_string(),
BasicColor::BrightBlack => "gray".to_string(),
BasicColor::BrightRed => "bright-red".to_string(),
BasicColor::BrightGreen => "bright-green".to_string(),
BasicColor::BrightYellow => "bright-yellow".to_string(),
BasicColor::BrightBlue => "bright-blue".to_string(),
BasicColor::BrightMagenta => "bright-magenta".to_string(),
BasicColor::BrightCyan => "bright-cyan".to_string(),
BasicColor::BrightWhite => "bright-white".to_string(),
},
Color::Indexed(index) => index.to_string(),
Color::Rgb(red, green, blue) => format!("#{red:02x}{green:02x}{blue:02x}"),
}
}
pub(crate) fn is_foreground_value(value: &str, theme: &Theme) -> bool {
color_or_theme(value, ColorTarget::Foreground, theme).is_some()
}
fn parse_color(value: &str) -> Option<Color> {
if let Some(color) = named_color(value) {
return Some(Color::Basic(color));
}
if let Ok(index) = value.parse::<u8>() {
return Some(Color::Indexed(index));
}
let hex = value.strip_prefix('#')?;
if hex.len() != 6 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return None;
}
Some(Color::Rgb(
u8::from_str_radix(&hex[0..2], 16).ok()?,
u8::from_str_radix(&hex[2..4], 16).ok()?,
u8::from_str_radix(&hex[4..6], 16).ok()?,
))
}
pub(crate) fn is_reserved_style_name(name: &str) -> bool {
matches!(
name,
"b" | "bold"
| "dim"
| "i"
| "italic"
| "u"
| "underline"
| "underline-color"
| "blink"
| "inverse"
| "s"
| "strike"
| "overline"
| "color"
| "fg"
| "bg"
| "link"
| "br"
| "reset"
) || named_color(name).is_some()
}
fn named_color(name: &str) -> Option<BasicColor> {
Some(match name {
"black" => BasicColor::Black,
"red" => BasicColor::Red,
"green" => BasicColor::Green,
"yellow" => BasicColor::Yellow,
"blue" => BasicColor::Blue,
"magenta" => BasicColor::Magenta,
"cyan" => BasicColor::Cyan,
"white" => BasicColor::White,
"gray" | "grey" => BasicColor::BrightBlack,
"bright-red" => BasicColor::BrightRed,
"bright-green" => BasicColor::BrightGreen,
"bright-yellow" => BasicColor::BrightYellow,
"bright-blue" => BasicColor::BrightBlue,
"bright-magenta" => BasicColor::BrightMagenta,
"bright-cyan" => BasicColor::BrightCyan,
"bright-white" => BasicColor::BrightWhite,
_ => return None,
})
}
fn push_sgr(sgr: &str, output: &mut String) {
if !sgr.is_empty() {
output.push_str("\x1b[");
output.push_str(sgr);
output.push('m');
}
}
fn rebuild_sgr(formats: &[ActiveFormat], output: &mut String) {
output.push_str(RESET);
for format in formats {
if let ActiveFormat::Sgr { sgr, .. } = format {
push_sgr(sgr, output);
}
}
}
fn current_link_index(formats: &[ActiveFormat]) -> Option<usize> {
formats
.iter()
.rposition(|format| matches!(format, ActiveFormat::Link { .. }))
}
fn current_link(formats: &[ActiveFormat]) -> Option<&str> {
current_link_index(formats).and_then(|index| match &formats[index] {
ActiveFormat::Link { target, .. } => Some(target.as_str()),
ActiveFormat::Sgr { .. } => None,
})
}
fn close_current_link(formats: &[ActiveFormat], output: &mut String) {
if current_link(formats).is_some_and(|target| !target.is_empty()) {
output.push_str(ansi::OSC8_CLOSE);
}
}
fn open_current_link(formats: &[ActiveFormat], output: &mut String) {
if let Some(target) = current_link(formats) {
push_link_open(target, output);
}
}
fn push_link_open(target: &str, output: &mut String) {
if target.is_empty() {
return;
}
output.push_str("\x1b]8;;");
for ch in target.chars() {
if is_framing_control(ch) {
let mut bytes = [0; 4];
for byte in ch.encode_utf8(&mut bytes).bytes() {
use std::fmt::Write as _;
write!(output, "%{byte:02X}").expect("writing to a string cannot fail");
}
} else {
output.push(ch);
}
}
output.push_str("\x1b\\");
}
fn boundary(formats: &[ActiveFormat], ansi_enabled: bool, output: &mut String, separator: char) {
if ansi_enabled {
close_current_link(formats, output);
if formats
.iter()
.any(|format| matches!(format, ActiveFormat::Sgr { .. }))
{
output.push_str(RESET);
}
}
output.push(separator);
if ansi_enabled {
for format in formats {
if let ActiveFormat::Sgr { sgr, .. } = format {
push_sgr(sgr, output);
}
}
open_current_link(formats, output);
}
}
fn close_at_end(formats: &[ActiveFormat], ansi_enabled: bool, output: &mut String) {
if !ansi_enabled {
return;
}
close_current_link(formats, output);
if formats
.iter()
.any(|format| matches!(format, ActiveFormat::Sgr { .. }))
{
output.push_str(RESET);
}
}
fn is_filtered_text_control(ch: char) -> bool {
(ch.is_control() && !matches!(ch, '\n' | '\t')) || ('\u{80}'..='\u{9f}').contains(&ch)
}
fn is_framing_control(ch: char) -> bool {
matches!(ch, '\u{0}'..='\u{1f}' | '\u{7f}' | '\u{80}'..='\u{9f}')
}
pub(crate) fn sanitize_terminal_controls(input: &str) -> String {
let mut output = String::with_capacity(input.len());
for token in ansi::tokens(input) {
if let ansi::Token::Char(ch) = token {
if !is_filtered_text_control(ch) {
output.push(ch);
}
}
}
output
}
#[cfg(test)]
mod tests {
use super::*;
fn render_ansi(input: &str) -> String {
render(input, true, &Theme::new())
}
#[test]
fn text_style_emits_exact_extended_sgr() {
let style = TextStyle::new()
.bold()
.dim()
.italic()
.underline_style(UnderlineStyle::Curly)
.blink(BlinkStyle::Rapid)
.inverse()
.strike()
.overline()
.foreground(Color::Basic(BasicColor::BrightRed))
.background(Color::Indexed(42))
.underline_color(Color::Basic(BasicColor::BrightWhite));
assert_eq!(style.sgr(), "1;2;3;4:3;6;7;9;53;91;48;5;42;58;5;15");
assert_eq!(TextStyle::new().underline().sgr(), "4");
}
#[test]
fn renders_all_new_style_tags_case_insensitively() {
assert_eq!(
render_ansi(concat!(
"[inverse]i[/inverse]",
"[OVERLINE]o[/OVERLINE]",
"[blink]s[/blink]",
"[blink=RAPID]r[/blink]",
"[u=single]1[/u]",
"[underline=double]2[/underline]",
"[u=curly]3[/u]",
"[u=dotted]4[/u]",
"[u=dashed]5[/u]"
)),
concat!(
"\x1b[7mi\x1b[0m",
"\x1b[53mo\x1b[0m",
"\x1b[5ms\x1b[0m",
"\x1b[6mr\x1b[0m",
"\x1b[4m1\x1b[0m",
"\x1b[4:2m2\x1b[0m",
"\x1b[4:3m3\x1b[0m",
"\x1b[4:4m4\x1b[0m",
"\x1b[4:5m5\x1b[0m"
)
);
}
#[test]
fn underline_colors_use_58_and_extract_only_theme_underline_color() {
let mut theme = Theme::new();
theme
.insert(
"accent",
TextStyle::new()
.bold()
.foreground(Color::Basic(BasicColor::Red))
.underline_color(Color::Rgb(1, 2, 3)),
)
.unwrap();
theme
.insert(
"no-underline",
TextStyle::new().foreground(Color::Basic(BasicColor::Green)),
)
.unwrap();
assert_eq!(
render("[underline-color=blue]x[/underline-color]", true, &theme),
"\x1b[58;5;4mx\x1b[0m"
);
assert_eq!(
render("[underline-color=accent]x[/underline-color]", true, &theme),
"\x1b[58;2;1;2;3mx\x1b[0m"
);
assert_eq!(
render(
"[underline-color=no-underline]x[/underline-color]",
true,
&theme
),
"[underline-color=no-underline]x[/underline-color]"
);
}
#[test]
fn link_targets_are_unrestricted_and_preserve_spelling() {
for (target, label) in [
("HTTPS://Example.COM/A?Q=One#Two", "absolute"),
("custom+Thing:Value", "custom"),
("../Relative/Path", "relative"),
] {
assert_eq!(
render_ansi(&format!("[LiNk={target}]{label}[/lInK]")),
format!("\x1b]8;;{target}\x1b\\{label}{}", ansi::OSC8_CLOSE)
);
}
}
#[test]
fn quoted_link_targets_allow_brackets_quotes_and_backslashes() {
assert_eq!(
render_ansi(r#"[link="A]B\"C\\D"]label[/link]"#),
format!("\x1b]8;;A]B\"C\\D\x1b\\label{}", ansi::OSC8_CLOSE)
);
assert_eq!(
find_tag_end(r#"[link="A]B"]x"#, 1),
Some(r#"[link="A]B"]"#.len() - 1)
);
}
#[test]
fn malformed_and_empty_links_have_defined_behavior() {
assert_eq!(render_ansi("[link]x[/link]"), "[link]x[/link]");
assert_eq!(
render_ansi("[link=\"unterminated]x[/link]"),
"[link=\"unterminated]x[/link]"
);
assert_eq!(render_ansi("[link=]x[/link]"), "x");
assert_eq!(render_ansi("[link=\"\"]x[/link]"), "x");
assert_eq!(strip_bbcode("[link=../Path]label[/link]"), "label");
}
#[test]
fn osc8_percent_encodes_only_framing_controls_as_utf8_bytes() {
let target = "A\0\x1b\x7f\u{80}\u{9f} Z%[]";
assert_eq!(
render_ansi(&format!("[link=\"{target}\"]x[/link]")),
format!(
"\x1b]8;;A%00%1B%7F%C2%80%C2%9F Z%[]\x1b\\x{}",
ansi::OSC8_CLOSE
)
);
}
#[test]
fn nested_links_suspend_and_restore_the_outer_target() {
let close = ansi::OSC8_CLOSE;
assert_eq!(
render_ansi("[link=outer]a[link=inner]b[/link]c[/link]"),
format!(
"\x1b]8;;outer\x1b\\a{close}\x1b]8;;inner\x1b\\b{close}\x1b]8;;outer\x1b\\c{close}"
)
);
assert_eq!(
render_ansi("[link=outer]a[link=]b[/]c[/]"),
format!("\x1b]8;;outer\x1b\\a{close}b\x1b]8;;outer\x1b\\c{close}")
);
}
#[test]
fn links_and_styles_close_and_reopen_at_boundaries() {
let close = ansi::OSC8_CLOSE;
assert_eq!(
render_ansi("[b][link=T]a\nb[br]c[/link][/b]"),
format!(
"\x1b[1m\x1b]8;;T\x1b\\a{close}\x1b[0m\n\x1b[1m\x1b]8;;T\x1b\\b{close}\x1b[0m\n\x1b[1m\x1b]8;;T\x1b\\c{close}\x1b[0m"
)
);
assert_eq!(
render_ansi("[b][link=T]x[reset]y"),
format!("\x1b[1m\x1b]8;;T\x1b\\x{close}\x1b[0my")
);
assert_eq!(
render_ansi("[red][link=T]x[/link]y[/red]"),
format!("\x1b[31m\x1b]8;;T\x1b\\x{close}y\x1b[0m")
);
assert_eq!(
render_ansi("[link=T]unterminated"),
format!("\x1b]8;;T\x1b\\unterminated{close}")
);
}
#[test]
fn closing_sgr_rebuilds_remaining_styles_without_disturbing_link() {
assert_eq!(
render_ansi("[red][link=T][b]x[/b]y[/link]z[/red]"),
format!(
"\x1b[31m\x1b]8;;T\x1b\\\x1b[1mx\x1b[0m\x1b[31my{}z\x1b[0m",
ansi::OSC8_CLOSE
)
);
}
#[test]
fn incremental_typed_links_ignore_markup_closes_and_restore_outer_links() {
let close = ansi::OSC8_CLOSE;
let theme = Theme::new();
let mut formatter = FormatSession::new(true, &theme);
formatter.push_markup("[link=outer]a");
formatter.link_start(7, "typed[/link][reset]\u{e000}");
formatter.push_markup("b[/link][reset]c");
formatter.link_end(7);
formatter.push_markup("d[/link]");
assert_eq!(
formatter.finish(),
format!(
"\x1b]8;;outer\x1b\\a{close}\x1b]8;;typed[/link][reset]\u{e000}\x1b\\b[/link]{close}\x1b[0m\x1b]8;;typed[/link][reset]\u{e000}\x1b\\c{close}\x1b]8;;outer\x1b\\d{close}"
)
);
}
#[test]
fn typed_link_end_discards_unclosed_formats_and_restores_outer_state() {
let close = ansi::OSC8_CLOSE;
let theme = Theme::new();
let mut formatter = FormatSession::new(true, &theme);
formatter.push_markup("[red][bg=blue][blink][link=outer]a");
formatter.link_start(7, "typed");
formatter.push_markup("b[green][bg=yellow][blink=rapid][link=source]c");
formatter.link_end(7);
formatter.push_markup("d[/link][/blink][/bg][/red]");
assert_eq!(
formatter.finish(),
format!(
concat!(
"\x1b[31m\x1b[44m\x1b[5m\x1b]8;;outer\x1b\\a",
"{close}\x1b]8;;typed\x1b\\b\x1b[32m\x1b[43m\x1b[6m",
"{close}\x1b]8;;source\x1b\\c{close}",
"\x1b[0m\x1b[31m\x1b[44m\x1b[5m\x1b]8;;outer\x1b\\d{close}",
"\x1b[0m\x1b[31m\x1b[44m\x1b[0m\x1b[31m\x1b[0m"
),
close = close
)
);
}
#[test]
fn ansi_false_keeps_only_link_labels_and_strips_supported_tags() {
assert_eq!(
render(
"[inverse]a[/inverse][link=Target]b[blink=rapid]c[/blink][/link][br]d",
false,
&Theme::new()
),
"abc\nd"
);
assert_eq!(
strip_bbcode("[underline=dotted]u[/underline][overline]o[/overline]"),
"uo"
);
}
#[test]
fn semantic_backgrounds_extract_only_the_theme_background() {
let mut theme = Theme::new();
theme
.insert(
"panel",
TextStyle::new()
.bold()
.foreground(Color::Basic(BasicColor::Red))
.background(Color::Rgb(1, 2, 3)),
)
.unwrap();
theme
.insert(
"foreground-only",
TextStyle::new().foreground(Color::Basic(BasicColor::Green)),
)
.unwrap();
assert_eq!(
render("[bg=panel]内容[/bg]", true, &theme),
"\x1b[48;2;1;2;3m内容\x1b[0m"
);
assert_eq!(
render("[bg=foreground-only]内容[/bg]", true, &theme),
"[bg=foreground-only]内容[/bg]"
);
}
#[test]
fn escaped_unknown_and_hostile_controls_are_literal_or_removed() {
assert_eq!(
render(
r"\[red]原样[/red] [unknown]x[/unknown]",
false,
&Theme::new()
),
"[red]原样[/red] [unknown]x[/unknown]"
);
assert_eq!(
render("安全\x1b[31m伪造\x1b[0m\x07", true, &Theme::new()),
"安全伪造"
);
}
}