Skip to main content

mbterm/
bbcode.rs

1use crate::ansi;
2use crate::Theme;
3
4pub(crate) const RESET: &str = "\x1b[0m";
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum BasicColor {
8    Black,
9    Red,
10    Green,
11    Yellow,
12    Blue,
13    Magenta,
14    Cyan,
15    White,
16    BrightBlack,
17    BrightRed,
18    BrightGreen,
19    BrightYellow,
20    BrightBlue,
21    BrightMagenta,
22    BrightCyan,
23    BrightWhite,
24}
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum Color {
28    Basic(BasicColor),
29    Indexed(u8),
30    Rgb(u8, u8, u8),
31}
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum BlinkStyle {
35    Slow,
36    Rapid,
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum UnderlineStyle {
41    Single,
42    Double,
43    Curly,
44    Dotted,
45    Dashed,
46}
47
48#[derive(Clone, Debug, Default, PartialEq, Eq)]
49pub struct TextStyle {
50    foreground: Option<Color>,
51    background: Option<Color>,
52    bold: bool,
53    dim: bool,
54    italic: bool,
55    underline: Option<UnderlineStyle>,
56    blink: Option<BlinkStyle>,
57    inverse: bool,
58    strike: bool,
59    overline: bool,
60    underline_color: Option<Color>,
61}
62
63impl TextStyle {
64    pub fn new() -> Self {
65        Self::default()
66    }
67
68    pub fn foreground(mut self, color: Color) -> Self {
69        self.foreground = Some(color);
70        self
71    }
72
73    pub fn background(mut self, color: Color) -> Self {
74        self.background = Some(color);
75        self
76    }
77
78    pub(crate) fn background_color(&self) -> Option<Color> {
79        self.background
80    }
81
82    pub fn bold(mut self) -> Self {
83        self.bold = true;
84        self
85    }
86
87    pub fn dim(mut self) -> Self {
88        self.dim = true;
89        self
90    }
91
92    pub fn italic(mut self) -> Self {
93        self.italic = true;
94        self
95    }
96
97    pub fn underline(mut self) -> Self {
98        self.underline = Some(UnderlineStyle::Single);
99        self
100    }
101
102    pub fn underline_style(mut self, style: UnderlineStyle) -> Self {
103        self.underline = Some(style);
104        self
105    }
106
107    pub fn blink(mut self, style: BlinkStyle) -> Self {
108        self.blink = Some(style);
109        self
110    }
111
112    pub fn inverse(mut self) -> Self {
113        self.inverse = true;
114        self
115    }
116
117    pub fn strike(mut self) -> Self {
118        self.strike = true;
119        self
120    }
121
122    pub fn overline(mut self) -> Self {
123        self.overline = true;
124        self
125    }
126
127    pub fn underline_color(mut self, color: Color) -> Self {
128        self.underline_color = Some(color);
129        self
130    }
131
132    pub(crate) fn underline_color_value(&self) -> Option<Color> {
133        self.underline_color
134    }
135
136    pub(crate) fn sgr(&self) -> String {
137        let mut codes = Vec::with_capacity(11);
138        if self.bold {
139            codes.push("1".to_string());
140        }
141        if self.dim {
142            codes.push("2".to_string());
143        }
144        if self.italic {
145            codes.push("3".to_string());
146        }
147        if let Some(style) = self.underline {
148            codes.push(style.sgr().to_string());
149        }
150        if let Some(style) = self.blink {
151            codes.push(style.sgr().to_string());
152        }
153        if self.inverse {
154            codes.push("7".to_string());
155        }
156        if self.strike {
157            codes.push("9".to_string());
158        }
159        if self.overline {
160            codes.push("53".to_string());
161        }
162        if let Some(color) = self.foreground {
163            codes.push(color.sgr(ColorTarget::Foreground));
164        }
165        if let Some(color) = self.background {
166            codes.push(color.sgr(ColorTarget::Background));
167        }
168        if let Some(color) = self.underline_color {
169            codes.push(color.sgr(ColorTarget::Underline));
170        }
171        codes.join(";")
172    }
173}
174
175impl BlinkStyle {
176    fn sgr(self) -> &'static str {
177        match self {
178            Self::Slow => "5",
179            Self::Rapid => "6",
180        }
181    }
182}
183
184impl UnderlineStyle {
185    fn sgr(self) -> &'static str {
186        match self {
187            Self::Single => "4",
188            Self::Double => "4:2",
189            Self::Curly => "4:3",
190            Self::Dotted => "4:4",
191            Self::Dashed => "4:5",
192        }
193    }
194}
195
196#[derive(Clone, Copy)]
197enum ColorTarget {
198    Foreground,
199    Background,
200    Underline,
201}
202
203impl Color {
204    fn sgr(self, target: ColorTarget) -> String {
205        match (self, target) {
206            (Self::Basic(color), ColorTarget::Foreground) => color.sgr(false).to_string(),
207            (Self::Basic(color), ColorTarget::Background) => color.sgr(true).to_string(),
208            (Self::Basic(color), ColorTarget::Underline) => {
209                format!("58;5;{}", color.index())
210            }
211            (Self::Indexed(index), target) => format!("{};5;{index}", target.extended_code()),
212            (Self::Rgb(red, green, blue), target) => {
213                format!("{};2;{red};{green};{blue}", target.extended_code())
214            }
215        }
216    }
217}
218
219impl ColorTarget {
220    fn extended_code(self) -> u8 {
221        match self {
222            Self::Foreground => 38,
223            Self::Background => 48,
224            Self::Underline => 58,
225        }
226    }
227}
228
229impl std::str::FromStr for Color {
230    type Err = ParseColorError;
231
232    fn from_str(value: &str) -> Result<Self, Self::Err> {
233        parse_color(&value.to_ascii_lowercase()).ok_or_else(|| ParseColorError {
234            value: value.to_string(),
235        })
236    }
237}
238
239#[derive(Clone, Debug, PartialEq, Eq)]
240pub struct ParseColorError {
241    value: String,
242}
243
244impl std::fmt::Display for ParseColorError {
245    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246        write!(formatter, "invalid terminal color {:?}", self.value)
247    }
248}
249
250impl std::error::Error for ParseColorError {}
251
252impl BasicColor {
253    fn index(self) -> u8 {
254        match self {
255            Self::Black => 0,
256            Self::Red => 1,
257            Self::Green => 2,
258            Self::Yellow => 3,
259            Self::Blue => 4,
260            Self::Magenta => 5,
261            Self::Cyan => 6,
262            Self::White => 7,
263            Self::BrightBlack => 8,
264            Self::BrightRed => 9,
265            Self::BrightGreen => 10,
266            Self::BrightYellow => 11,
267            Self::BrightBlue => 12,
268            Self::BrightMagenta => 13,
269            Self::BrightCyan => 14,
270            Self::BrightWhite => 15,
271        }
272    }
273
274    fn sgr(self, background: bool) -> u8 {
275        let index = self.index();
276        match (background, index >= 8) {
277            (false, false) => 30 + index,
278            (true, false) => 40 + index,
279            (false, true) => 90 + index - 8,
280            (true, true) => 100 + index - 8,
281        }
282    }
283}
284
285#[derive(Clone, Debug, PartialEq, Eq)]
286enum LinkOwner {
287    Markup,
288    Typed(u64),
289}
290
291#[derive(Clone, Debug)]
292enum ActiveFormat {
293    Sgr { tag: String, sgr: String },
294    Link { target: String, owner: LinkOwner },
295}
296
297impl ActiveFormat {
298    fn markup_tag(&self) -> Option<&str> {
299        match self {
300            Self::Sgr { tag, .. } => Some(tag),
301            Self::Link {
302                owner: LinkOwner::Markup,
303                ..
304            } => Some("link"),
305            Self::Link {
306                owner: LinkOwner::Typed(_),
307                ..
308            } => None,
309        }
310    }
311}
312
313/// Incremental formatter used by Markdown's typed inline buffer.
314///
315/// Markup parts retain the existing BBCode state, while typed links bypass the
316/// BBCode grammar and can only be closed by their internal identifier.
317pub(crate) struct FormatSession<'a> {
318    ansi_enabled: bool,
319    theme: &'a Theme,
320    output: String,
321    formats: Vec<ActiveFormat>,
322}
323
324impl<'a> FormatSession<'a> {
325    pub(crate) fn new(ansi_enabled: bool, theme: &'a Theme) -> Self {
326        Self {
327            ansi_enabled,
328            theme,
329            output: String::new(),
330            formats: Vec::new(),
331        }
332    }
333
334    pub(crate) fn push_markup(&mut self, input: &str) {
335        self.output.reserve(input.len());
336        let mut index = 0;
337
338        while index < input.len() {
339            let rest = &input[index..];
340            let mut chars = rest.chars();
341            let Some(ch) = chars.next() else { break };
342            let char_len = ch.len_utf8();
343
344            if ch == '\\' {
345                if let Some(next) = chars.next() {
346                    if matches!(next, '[' | ']' | '\\') {
347                        self.output.push(next);
348                        index += char_len + next.len_utf8();
349                        continue;
350                    }
351                }
352            }
353
354            if ch == '[' {
355                if let Some(end) = find_tag_end(input, index + char_len) {
356                    let body = &input[index + char_len..end];
357                    if apply_tag(
358                        body,
359                        self.ansi_enabled,
360                        self.theme,
361                        &mut self.formats,
362                        &mut self.output,
363                    ) {
364                        index = end + 1;
365                        continue;
366                    }
367                }
368            }
369
370            if matches!(ch, '\x1b' | '\u{0080}'..='\u{009f}') {
371                if let Some(ansi::Token::Sequence(sequence)) = ansi::tokens(rest).next() {
372                    index += sequence.as_str().len();
373                    continue;
374                }
375            }
376            if ch == '\n' {
377                boundary(&self.formats, self.ansi_enabled, &mut self.output, '\n');
378            } else if is_filtered_text_control(ch) {
379                // Ignore terminal controls in labels while retaining tabs and line breaks.
380            } else {
381                self.output.push(ch);
382            }
383            index += char_len;
384        }
385    }
386
387    pub(crate) fn link_start(&mut self, id: u64, target: &str) {
388        if self.ansi_enabled {
389            close_current_link(&self.formats, &mut self.output);
390            push_link_open(target, &mut self.output);
391        }
392        self.formats.push(ActiveFormat::Link {
393            target: target.to_string(),
394            owner: LinkOwner::Typed(id),
395        });
396    }
397
398    pub(crate) fn link_end(&mut self, id: u64) {
399        let Some(index) = self.formats.iter().rposition(|format| {
400            matches!(
401                format,
402                ActiveFormat::Link {
403                    owner: LinkOwner::Typed(candidate),
404                    ..
405                } if *candidate == id
406            )
407        }) else {
408            return;
409        };
410        let has_sgr = self
411            .formats
412            .iter()
413            .any(|format| matches!(format, ActiveFormat::Sgr { .. }));
414        if self.ansi_enabled {
415            close_current_link(&self.formats, &mut self.output);
416        }
417        // The typed link is a scope boundary. Discard it and every format
418        // opened inside its label so source markup cannot leak past the
419        // parser-provided link boundary.
420        self.formats.truncate(index);
421        if self.ansi_enabled {
422            if has_sgr {
423                rebuild_sgr(&self.formats, &mut self.output);
424            }
425            open_current_link(&self.formats, &mut self.output);
426        }
427    }
428
429    pub(crate) fn finish(mut self) -> String {
430        close_at_end(&self.formats, self.ansi_enabled, &mut self.output);
431        self.output
432    }
433}
434
435pub(crate) fn render(input: &str, ansi_enabled: bool, theme: &Theme) -> String {
436    let mut formatter = FormatSession::new(ansi_enabled, theme);
437    formatter.push_markup(input);
438    formatter.finish()
439}
440
441pub fn strip_bbcode(input: &str) -> String {
442    render(input, false, &Theme::new())
443}
444
445/// Escape untrusted text so Markdown and BBCode both render it literally.
446pub fn escape(value: &str) -> String {
447    let mut escaped = String::with_capacity(value.len());
448    for ch in value.chars() {
449        if ch.is_ascii_punctuation() {
450            escaped.push('\\');
451        }
452        escaped.push(ch);
453    }
454    escaped
455}
456
457/// Find the closing bracket of a tag, ignoring brackets inside double quotes.
458/// Backslash escapes are recognized while inside a quoted section.
459pub(crate) fn find_tag_end(input: &str, start: usize) -> Option<usize> {
460    let mut quoted = false;
461    let mut escaped = false;
462    for (offset, ch) in input.get(start..)?.char_indices() {
463        if escaped {
464            escaped = false;
465        } else if quoted && ch == '\\' {
466            escaped = true;
467        } else if ch == '"' {
468            quoted = !quoted;
469        } else if ch == ']' && !quoted {
470            return Some(start + offset);
471        }
472    }
473    None
474}
475
476pub(crate) fn is_tag(body: &str, theme: &Theme) -> bool {
477    let body = body.trim();
478    if body.is_empty() {
479        return false;
480    }
481    if body.eq_ignore_ascii_case("br") || body.eq_ignore_ascii_case("reset") || body == "/" {
482        return true;
483    }
484    if let Some(closing) = body.strip_prefix('/') {
485        let closing = closing.trim();
486        return !closing.contains('=') && is_closing_tag(closing, theme);
487    }
488    parse_format(body, theme).is_some()
489}
490
491fn is_closing_tag(name: &str, theme: &Theme) -> bool {
492    let name = name.to_ascii_lowercase();
493    matches!(
494        name.as_str(),
495        "b" | "bold"
496            | "dim"
497            | "i"
498            | "italic"
499            | "u"
500            | "underline"
501            | "underline-color"
502            | "blink"
503            | "inverse"
504            | "s"
505            | "strike"
506            | "overline"
507            | "color"
508            | "fg"
509            | "bg"
510            | "link"
511    ) || named_color(&name).is_some()
512        || theme.get(&name).is_some()
513}
514
515fn apply_tag(
516    body: &str,
517    ansi_enabled: bool,
518    theme: &Theme,
519    formats: &mut Vec<ActiveFormat>,
520    output: &mut String,
521) -> bool {
522    let body = body.trim();
523    if body.is_empty() {
524        return false;
525    }
526    if body.eq_ignore_ascii_case("br") {
527        boundary(formats, ansi_enabled, output, '\n');
528        return true;
529    }
530    if body.eq_ignore_ascii_case("reset") {
531        if ansi_enabled {
532            close_current_link(formats, output);
533            output.push_str(RESET);
534        }
535        let typed_depth = formats
536            .iter()
537            .rposition(|format| {
538                matches!(
539                    format,
540                    ActiveFormat::Link {
541                        owner: LinkOwner::Typed(_),
542                        ..
543                    }
544                )
545            })
546            .map_or(0, |index| index + 1);
547        formats.truncate(typed_depth);
548        if ansi_enabled {
549            open_current_link(formats, output);
550        }
551        return true;
552    }
553    if let Some(closing) = body.strip_prefix('/') {
554        let closing = closing.trim();
555        let matches = formats.last().is_some_and(|format| {
556            format
557                .markup_tag()
558                .is_some_and(|tag| closing.is_empty() || tag.eq_ignore_ascii_case(closing))
559        });
560        if !matches {
561            return false;
562        }
563        let removed = formats.pop().expect("a matching format exists");
564        if ansi_enabled {
565            match removed {
566                ActiveFormat::Sgr { .. } => rebuild_sgr(formats, output),
567                ActiveFormat::Link { target, .. } => {
568                    if !target.is_empty() {
569                        output.push_str(ansi::OSC8_CLOSE);
570                    }
571                    open_current_link(formats, output);
572                }
573            }
574        }
575        return true;
576    }
577
578    let Some(format) = parse_format(body, theme) else {
579        return false;
580    };
581    if ansi_enabled {
582        match &format {
583            ActiveFormat::Sgr { sgr, .. } => push_sgr(sgr, output),
584            ActiveFormat::Link { target, .. } => {
585                close_current_link(formats, output);
586                push_link_open(target, output);
587            }
588        }
589    }
590    formats.push(format);
591    true
592}
593
594fn parse_format(tag: &str, theme: &Theme) -> Option<ActiveFormat> {
595    let (name, value) = tag
596        .split_once('=')
597        .map_or((tag.trim(), None), |(name, value)| {
598            (name.trim(), Some(value.trim()))
599        });
600    let lower_name = name.to_ascii_lowercase();
601    let (canonical, sgr) = match (lower_name.as_str(), value) {
602        ("b" | "bold", None) => (lower_name.as_str(), "1".to_string()),
603        ("dim", None) => ("dim", "2".to_string()),
604        ("i" | "italic", None) => (lower_name.as_str(), "3".to_string()),
605        ("u" | "underline", None) => (lower_name.as_str(), "4".to_string()),
606        ("u" | "underline", Some(value)) => (
607            lower_name.as_str(),
608            parse_underline_style(value)?.sgr().to_string(),
609        ),
610        ("blink", None) => ("blink", "5".to_string()),
611        ("blink", Some(value)) => ("blink", parse_blink_style(value)?.sgr().to_string()),
612        ("inverse", None) => ("inverse", "7".to_string()),
613        ("s" | "strike", None) => (lower_name.as_str(), "9".to_string()),
614        ("overline", None) => ("overline", "53".to_string()),
615        ("color" | "fg", Some(value)) => (
616            lower_name.as_str(),
617            color_or_theme(value, ColorTarget::Foreground, theme)?,
618        ),
619        ("bg", Some(value)) => ("bg", color_or_theme(value, ColorTarget::Background, theme)?),
620        ("underline-color", Some(value)) => (
621            "underline-color",
622            underline_color(value, theme)?.sgr(ColorTarget::Underline),
623        ),
624        ("link", Some(value)) => {
625            return Some(ActiveFormat::Link {
626                target: parse_link_target(value)?,
627                owner: LinkOwner::Markup,
628            });
629        }
630        (name, None) => (name, named_style(name, theme)?),
631        _ => return None,
632    };
633    Some(ActiveFormat::Sgr {
634        tag: canonical.to_string(),
635        sgr,
636    })
637}
638
639fn parse_underline_style(value: &str) -> Option<UnderlineStyle> {
640    Some(match value.to_ascii_lowercase().as_str() {
641        "single" => UnderlineStyle::Single,
642        "double" => UnderlineStyle::Double,
643        "curly" => UnderlineStyle::Curly,
644        "dotted" => UnderlineStyle::Dotted,
645        "dashed" => UnderlineStyle::Dashed,
646        _ => return None,
647    })
648}
649
650fn parse_blink_style(value: &str) -> Option<BlinkStyle> {
651    Some(match value.to_ascii_lowercase().as_str() {
652        "slow" => BlinkStyle::Slow,
653        "rapid" => BlinkStyle::Rapid,
654        _ => return None,
655    })
656}
657
658fn parse_link_target(value: &str) -> Option<String> {
659    if !value.starts_with('"') {
660        return Some(value.to_string());
661    }
662    let mut target = String::with_capacity(value.len().saturating_sub(2));
663    let mut chars = value[1..].char_indices();
664    while let Some((offset, ch)) = chars.next() {
665        match ch {
666            '"' => {
667                let rest = &value[1 + offset + ch.len_utf8()..];
668                return rest.trim().is_empty().then_some(target);
669            }
670            '\\' => match chars.next() {
671                Some((_, escaped @ ('"' | '\\'))) => target.push(escaped),
672                Some((_, other)) => {
673                    target.push('\\');
674                    target.push(other);
675                }
676                None => return None,
677            },
678            _ => target.push(ch),
679        }
680    }
681    None
682}
683
684fn named_style(name: &str, theme: &Theme) -> Option<String> {
685    if let Some(style) = theme.get(name) {
686        return Some(style.sgr());
687    }
688    Some(
689        TextStyle::new()
690            .foreground(Color::Basic(named_color(name)?))
691            .sgr(),
692    )
693}
694
695fn color_or_theme(value: &str, target: ColorTarget, theme: &Theme) -> Option<String> {
696    let normalized = value.trim().to_ascii_lowercase();
697    match target {
698        ColorTarget::Foreground => {
699            if let Some(style) = theme.get(&normalized) {
700                return Some(style.sgr());
701            }
702            parse_color(&normalized).map(|color| color.sgr(target))
703        }
704        ColorTarget::Background => {
705            background_color(&normalized, theme).map(|color| color.sgr(target))
706        }
707        ColorTarget::Underline => {
708            underline_color(&normalized, theme).map(|color| color.sgr(target))
709        }
710    }
711}
712
713fn underline_color(value: &str, theme: &Theme) -> Option<Color> {
714    let value = value.trim().to_ascii_lowercase();
715    parse_color(&value).or_else(|| theme.get(&value)?.underline_color_value())
716}
717
718pub(crate) fn background_color(value: &str, theme: &Theme) -> Option<Color> {
719    let value = value.trim().to_ascii_lowercase();
720    parse_color(&value).or_else(|| theme.get(&value)?.background_color())
721}
722
723pub(crate) fn background_sequence(color: Color) -> String {
724    format!("\x1b[{}m", color.sgr(ColorTarget::Background))
725}
726
727pub(crate) fn color_value(color: Color) -> String {
728    match color {
729        Color::Basic(color) => match color {
730            BasicColor::Black => "black".to_string(),
731            BasicColor::Red => "red".to_string(),
732            BasicColor::Green => "green".to_string(),
733            BasicColor::Yellow => "yellow".to_string(),
734            BasicColor::Blue => "blue".to_string(),
735            BasicColor::Magenta => "magenta".to_string(),
736            BasicColor::Cyan => "cyan".to_string(),
737            BasicColor::White => "white".to_string(),
738            BasicColor::BrightBlack => "gray".to_string(),
739            BasicColor::BrightRed => "bright-red".to_string(),
740            BasicColor::BrightGreen => "bright-green".to_string(),
741            BasicColor::BrightYellow => "bright-yellow".to_string(),
742            BasicColor::BrightBlue => "bright-blue".to_string(),
743            BasicColor::BrightMagenta => "bright-magenta".to_string(),
744            BasicColor::BrightCyan => "bright-cyan".to_string(),
745            BasicColor::BrightWhite => "bright-white".to_string(),
746        },
747        Color::Indexed(index) => index.to_string(),
748        Color::Rgb(red, green, blue) => format!("#{red:02x}{green:02x}{blue:02x}"),
749    }
750}
751
752pub(crate) fn is_foreground_value(value: &str, theme: &Theme) -> bool {
753    color_or_theme(value, ColorTarget::Foreground, theme).is_some()
754}
755
756fn parse_color(value: &str) -> Option<Color> {
757    if let Some(color) = named_color(value) {
758        return Some(Color::Basic(color));
759    }
760    if let Ok(index) = value.parse::<u8>() {
761        return Some(Color::Indexed(index));
762    }
763    let hex = value.strip_prefix('#')?;
764    if hex.len() != 6 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
765        return None;
766    }
767    Some(Color::Rgb(
768        u8::from_str_radix(&hex[0..2], 16).ok()?,
769        u8::from_str_radix(&hex[2..4], 16).ok()?,
770        u8::from_str_radix(&hex[4..6], 16).ok()?,
771    ))
772}
773
774pub(crate) fn is_reserved_style_name(name: &str) -> bool {
775    matches!(
776        name,
777        "b" | "bold"
778            | "dim"
779            | "i"
780            | "italic"
781            | "u"
782            | "underline"
783            | "underline-color"
784            | "blink"
785            | "inverse"
786            | "s"
787            | "strike"
788            | "overline"
789            | "color"
790            | "fg"
791            | "bg"
792            | "link"
793            | "br"
794            | "reset"
795    ) || named_color(name).is_some()
796}
797
798fn named_color(name: &str) -> Option<BasicColor> {
799    Some(match name {
800        "black" => BasicColor::Black,
801        "red" => BasicColor::Red,
802        "green" => BasicColor::Green,
803        "yellow" => BasicColor::Yellow,
804        "blue" => BasicColor::Blue,
805        "magenta" => BasicColor::Magenta,
806        "cyan" => BasicColor::Cyan,
807        "white" => BasicColor::White,
808        "gray" | "grey" => BasicColor::BrightBlack,
809        "bright-red" => BasicColor::BrightRed,
810        "bright-green" => BasicColor::BrightGreen,
811        "bright-yellow" => BasicColor::BrightYellow,
812        "bright-blue" => BasicColor::BrightBlue,
813        "bright-magenta" => BasicColor::BrightMagenta,
814        "bright-cyan" => BasicColor::BrightCyan,
815        "bright-white" => BasicColor::BrightWhite,
816        _ => return None,
817    })
818}
819
820fn push_sgr(sgr: &str, output: &mut String) {
821    if !sgr.is_empty() {
822        output.push_str("\x1b[");
823        output.push_str(sgr);
824        output.push('m');
825    }
826}
827
828fn rebuild_sgr(formats: &[ActiveFormat], output: &mut String) {
829    output.push_str(RESET);
830    for format in formats {
831        if let ActiveFormat::Sgr { sgr, .. } = format {
832            push_sgr(sgr, output);
833        }
834    }
835}
836
837fn current_link_index(formats: &[ActiveFormat]) -> Option<usize> {
838    formats
839        .iter()
840        .rposition(|format| matches!(format, ActiveFormat::Link { .. }))
841}
842
843fn current_link(formats: &[ActiveFormat]) -> Option<&str> {
844    current_link_index(formats).and_then(|index| match &formats[index] {
845        ActiveFormat::Link { target, .. } => Some(target.as_str()),
846        ActiveFormat::Sgr { .. } => None,
847    })
848}
849
850fn close_current_link(formats: &[ActiveFormat], output: &mut String) {
851    if current_link(formats).is_some_and(|target| !target.is_empty()) {
852        output.push_str(ansi::OSC8_CLOSE);
853    }
854}
855
856fn open_current_link(formats: &[ActiveFormat], output: &mut String) {
857    if let Some(target) = current_link(formats) {
858        push_link_open(target, output);
859    }
860}
861
862fn push_link_open(target: &str, output: &mut String) {
863    if target.is_empty() {
864        return;
865    }
866    output.push_str("\x1b]8;;");
867    for ch in target.chars() {
868        if is_framing_control(ch) {
869            let mut bytes = [0; 4];
870            for byte in ch.encode_utf8(&mut bytes).bytes() {
871                use std::fmt::Write as _;
872                write!(output, "%{byte:02X}").expect("writing to a string cannot fail");
873            }
874        } else {
875            output.push(ch);
876        }
877    }
878    output.push_str("\x1b\\");
879}
880
881fn boundary(formats: &[ActiveFormat], ansi_enabled: bool, output: &mut String, separator: char) {
882    if ansi_enabled {
883        close_current_link(formats, output);
884        if formats
885            .iter()
886            .any(|format| matches!(format, ActiveFormat::Sgr { .. }))
887        {
888            output.push_str(RESET);
889        }
890    }
891    output.push(separator);
892    if ansi_enabled {
893        for format in formats {
894            if let ActiveFormat::Sgr { sgr, .. } = format {
895                push_sgr(sgr, output);
896            }
897        }
898        open_current_link(formats, output);
899    }
900}
901
902fn close_at_end(formats: &[ActiveFormat], ansi_enabled: bool, output: &mut String) {
903    if !ansi_enabled {
904        return;
905    }
906    close_current_link(formats, output);
907    if formats
908        .iter()
909        .any(|format| matches!(format, ActiveFormat::Sgr { .. }))
910    {
911        output.push_str(RESET);
912    }
913}
914
915fn is_filtered_text_control(ch: char) -> bool {
916    (ch.is_control() && !matches!(ch, '\n' | '\t')) || ('\u{80}'..='\u{9f}').contains(&ch)
917}
918
919fn is_framing_control(ch: char) -> bool {
920    matches!(ch, '\u{0}'..='\u{1f}' | '\u{7f}' | '\u{80}'..='\u{9f}')
921}
922
923pub(crate) fn sanitize_terminal_controls(input: &str) -> String {
924    let mut output = String::with_capacity(input.len());
925    for token in ansi::tokens(input) {
926        if let ansi::Token::Char(ch) = token {
927            if !is_filtered_text_control(ch) {
928                output.push(ch);
929            }
930        }
931    }
932    output
933}
934
935#[cfg(test)]
936mod tests {
937    use super::*;
938
939    fn render_ansi(input: &str) -> String {
940        render(input, true, &Theme::new())
941    }
942
943    #[test]
944    fn text_style_emits_exact_extended_sgr() {
945        let style = TextStyle::new()
946            .bold()
947            .dim()
948            .italic()
949            .underline_style(UnderlineStyle::Curly)
950            .blink(BlinkStyle::Rapid)
951            .inverse()
952            .strike()
953            .overline()
954            .foreground(Color::Basic(BasicColor::BrightRed))
955            .background(Color::Indexed(42))
956            .underline_color(Color::Basic(BasicColor::BrightWhite));
957        assert_eq!(style.sgr(), "1;2;3;4:3;6;7;9;53;91;48;5;42;58;5;15");
958        assert_eq!(TextStyle::new().underline().sgr(), "4");
959    }
960
961    #[test]
962    fn renders_all_new_style_tags_case_insensitively() {
963        assert_eq!(
964            render_ansi(concat!(
965                "[inverse]i[/inverse]",
966                "[OVERLINE]o[/OVERLINE]",
967                "[blink]s[/blink]",
968                "[blink=RAPID]r[/blink]",
969                "[u=single]1[/u]",
970                "[underline=double]2[/underline]",
971                "[u=curly]3[/u]",
972                "[u=dotted]4[/u]",
973                "[u=dashed]5[/u]"
974            )),
975            concat!(
976                "\x1b[7mi\x1b[0m",
977                "\x1b[53mo\x1b[0m",
978                "\x1b[5ms\x1b[0m",
979                "\x1b[6mr\x1b[0m",
980                "\x1b[4m1\x1b[0m",
981                "\x1b[4:2m2\x1b[0m",
982                "\x1b[4:3m3\x1b[0m",
983                "\x1b[4:4m4\x1b[0m",
984                "\x1b[4:5m5\x1b[0m"
985            )
986        );
987    }
988
989    #[test]
990    fn underline_colors_use_58_and_extract_only_theme_underline_color() {
991        let mut theme = Theme::new();
992        theme
993            .insert(
994                "accent",
995                TextStyle::new()
996                    .bold()
997                    .foreground(Color::Basic(BasicColor::Red))
998                    .underline_color(Color::Rgb(1, 2, 3)),
999            )
1000            .unwrap();
1001        theme
1002            .insert(
1003                "no-underline",
1004                TextStyle::new().foreground(Color::Basic(BasicColor::Green)),
1005            )
1006            .unwrap();
1007
1008        assert_eq!(
1009            render("[underline-color=blue]x[/underline-color]", true, &theme),
1010            "\x1b[58;5;4mx\x1b[0m"
1011        );
1012        assert_eq!(
1013            render("[underline-color=accent]x[/underline-color]", true, &theme),
1014            "\x1b[58;2;1;2;3mx\x1b[0m"
1015        );
1016        assert_eq!(
1017            render(
1018                "[underline-color=no-underline]x[/underline-color]",
1019                true,
1020                &theme
1021            ),
1022            "[underline-color=no-underline]x[/underline-color]"
1023        );
1024    }
1025
1026    #[test]
1027    fn link_targets_are_unrestricted_and_preserve_spelling() {
1028        for (target, label) in [
1029            ("HTTPS://Example.COM/A?Q=One#Two", "absolute"),
1030            ("custom+Thing:Value", "custom"),
1031            ("../Relative/Path", "relative"),
1032        ] {
1033            assert_eq!(
1034                render_ansi(&format!("[LiNk={target}]{label}[/lInK]")),
1035                format!("\x1b]8;;{target}\x1b\\{label}{}", ansi::OSC8_CLOSE)
1036            );
1037        }
1038    }
1039
1040    #[test]
1041    fn quoted_link_targets_allow_brackets_quotes_and_backslashes() {
1042        assert_eq!(
1043            render_ansi(r#"[link="A]B\"C\\D"]label[/link]"#),
1044            format!("\x1b]8;;A]B\"C\\D\x1b\\label{}", ansi::OSC8_CLOSE)
1045        );
1046        assert_eq!(
1047            find_tag_end(r#"[link="A]B"]x"#, 1),
1048            Some(r#"[link="A]B"]"#.len() - 1)
1049        );
1050    }
1051
1052    #[test]
1053    fn malformed_and_empty_links_have_defined_behavior() {
1054        assert_eq!(render_ansi("[link]x[/link]"), "[link]x[/link]");
1055        assert_eq!(
1056            render_ansi("[link=\"unterminated]x[/link]"),
1057            "[link=\"unterminated]x[/link]"
1058        );
1059        assert_eq!(render_ansi("[link=]x[/link]"), "x");
1060        assert_eq!(render_ansi("[link=\"\"]x[/link]"), "x");
1061        assert_eq!(strip_bbcode("[link=../Path]label[/link]"), "label");
1062    }
1063
1064    #[test]
1065    fn osc8_percent_encodes_only_framing_controls_as_utf8_bytes() {
1066        let target = "A\0\x1b\x7f\u{80}\u{9f} Z%[]";
1067        assert_eq!(
1068            render_ansi(&format!("[link=\"{target}\"]x[/link]")),
1069            format!(
1070                "\x1b]8;;A%00%1B%7F%C2%80%C2%9F Z%[]\x1b\\x{}",
1071                ansi::OSC8_CLOSE
1072            )
1073        );
1074    }
1075
1076    #[test]
1077    fn nested_links_suspend_and_restore_the_outer_target() {
1078        let close = ansi::OSC8_CLOSE;
1079        assert_eq!(
1080            render_ansi("[link=outer]a[link=inner]b[/link]c[/link]"),
1081            format!(
1082                "\x1b]8;;outer\x1b\\a{close}\x1b]8;;inner\x1b\\b{close}\x1b]8;;outer\x1b\\c{close}"
1083            )
1084        );
1085        assert_eq!(
1086            render_ansi("[link=outer]a[link=]b[/]c[/]"),
1087            format!("\x1b]8;;outer\x1b\\a{close}b\x1b]8;;outer\x1b\\c{close}")
1088        );
1089    }
1090
1091    #[test]
1092    fn links_and_styles_close_and_reopen_at_boundaries() {
1093        let close = ansi::OSC8_CLOSE;
1094        assert_eq!(
1095            render_ansi("[b][link=T]a\nb[br]c[/link][/b]"),
1096            format!(
1097                "\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"
1098            )
1099        );
1100        assert_eq!(
1101            render_ansi("[b][link=T]x[reset]y"),
1102            format!("\x1b[1m\x1b]8;;T\x1b\\x{close}\x1b[0my")
1103        );
1104        assert_eq!(
1105            render_ansi("[red][link=T]x[/link]y[/red]"),
1106            format!("\x1b[31m\x1b]8;;T\x1b\\x{close}y\x1b[0m")
1107        );
1108        assert_eq!(
1109            render_ansi("[link=T]unterminated"),
1110            format!("\x1b]8;;T\x1b\\unterminated{close}")
1111        );
1112    }
1113
1114    #[test]
1115    fn closing_sgr_rebuilds_remaining_styles_without_disturbing_link() {
1116        assert_eq!(
1117            render_ansi("[red][link=T][b]x[/b]y[/link]z[/red]"),
1118            format!(
1119                "\x1b[31m\x1b]8;;T\x1b\\\x1b[1mx\x1b[0m\x1b[31my{}z\x1b[0m",
1120                ansi::OSC8_CLOSE
1121            )
1122        );
1123    }
1124
1125    #[test]
1126    fn incremental_typed_links_ignore_markup_closes_and_restore_outer_links() {
1127        let close = ansi::OSC8_CLOSE;
1128        let theme = Theme::new();
1129        let mut formatter = FormatSession::new(true, &theme);
1130        formatter.push_markup("[link=outer]a");
1131        formatter.link_start(7, "typed[/link][reset]\u{e000}");
1132        formatter.push_markup("b[/link][reset]c");
1133        formatter.link_end(7);
1134        formatter.push_markup("d[/link]");
1135        assert_eq!(
1136            formatter.finish(),
1137            format!(
1138                "\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}"
1139            )
1140        );
1141    }
1142
1143    #[test]
1144    fn typed_link_end_discards_unclosed_formats_and_restores_outer_state() {
1145        let close = ansi::OSC8_CLOSE;
1146        let theme = Theme::new();
1147        let mut formatter = FormatSession::new(true, &theme);
1148        formatter.push_markup("[red][bg=blue][blink][link=outer]a");
1149        formatter.link_start(7, "typed");
1150        formatter.push_markup("b[green][bg=yellow][blink=rapid][link=source]c");
1151        formatter.link_end(7);
1152        formatter.push_markup("d[/link][/blink][/bg][/red]");
1153        assert_eq!(
1154            formatter.finish(),
1155            format!(
1156                concat!(
1157                    "\x1b[31m\x1b[44m\x1b[5m\x1b]8;;outer\x1b\\a",
1158                    "{close}\x1b]8;;typed\x1b\\b\x1b[32m\x1b[43m\x1b[6m",
1159                    "{close}\x1b]8;;source\x1b\\c{close}",
1160                    "\x1b[0m\x1b[31m\x1b[44m\x1b[5m\x1b]8;;outer\x1b\\d{close}",
1161                    "\x1b[0m\x1b[31m\x1b[44m\x1b[0m\x1b[31m\x1b[0m"
1162                ),
1163                close = close
1164            )
1165        );
1166    }
1167
1168    #[test]
1169    fn ansi_false_keeps_only_link_labels_and_strips_supported_tags() {
1170        assert_eq!(
1171            render(
1172                "[inverse]a[/inverse][link=Target]b[blink=rapid]c[/blink][/link][br]d",
1173                false,
1174                &Theme::new()
1175            ),
1176            "abc\nd"
1177        );
1178        assert_eq!(
1179            strip_bbcode("[underline=dotted]u[/underline][overline]o[/overline]"),
1180            "uo"
1181        );
1182    }
1183
1184    #[test]
1185    fn semantic_backgrounds_extract_only_the_theme_background() {
1186        let mut theme = Theme::new();
1187        theme
1188            .insert(
1189                "panel",
1190                TextStyle::new()
1191                    .bold()
1192                    .foreground(Color::Basic(BasicColor::Red))
1193                    .background(Color::Rgb(1, 2, 3)),
1194            )
1195            .unwrap();
1196        theme
1197            .insert(
1198                "foreground-only",
1199                TextStyle::new().foreground(Color::Basic(BasicColor::Green)),
1200            )
1201            .unwrap();
1202
1203        assert_eq!(
1204            render("[bg=panel]内容[/bg]", true, &theme),
1205            "\x1b[48;2;1;2;3m内容\x1b[0m"
1206        );
1207        assert_eq!(
1208            render("[bg=foreground-only]内容[/bg]", true, &theme),
1209            "[bg=foreground-only]内容[/bg]"
1210        );
1211    }
1212
1213    #[test]
1214    fn escaped_unknown_and_hostile_controls_are_literal_or_removed() {
1215        assert_eq!(
1216            render(
1217                r"\[red]原样[/red] [unknown]x[/unknown]",
1218                false,
1219                &Theme::new()
1220            ),
1221            "[red]原样[/red] [unknown]x[/unknown]"
1222        );
1223        assert_eq!(
1224            render("安全\x1b[31m伪造\x1b[0m\x07", true, &Theme::new()),
1225            "安全伪造"
1226        );
1227    }
1228}