Skip to main content

uncurses/ansi/
sgr.rs

1//! Select Graphic Rendition (SGR) writer.
2//!
3//! ## Category
4//!
5//! SGR is the CSI `m` family used for rendition attributes such as reset,
6//! intensity, underline, foreground color, and background color. Higher-level
7//! style construction lives in [`Style`]; this module stores and writes the
8//! raw parameter grammar.
9//!
10//! ## Parameter conventions
11//!
12//! The outer slice in [`write_sgr`] becomes semicolon-separated primary
13//! parameters. Each inner slice becomes colon-separated subparameters, allowing
14//! both classic SGR and colon-form color parameters.
15//!
16//! ## Mode interaction
17//!
18//! SGR attributes are not enabled by a separate mode. They change the terminal's
19//! active rendition state until another SGR sequence resets or modifies it.
20
21use std::io::{self, Write};
22
23use super::params::Params;
24use crate::style::{Style, read_style_groups};
25
26/// Owned SGR parameters, with semicolon groups and colon subparameters.
27///
28/// A DECRPSS SGR reply carries this value in
29/// [`SettingReport::Sgr`](crate::event::SettingReport::Sgr).
30/// Call [`style`](Self::style) to interpret the parameters as a [`Style`].
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
32pub struct Sgr {
33    /// Semicolon-separated groups of colon-separated numeric values.
34    ///
35    /// Decoded omitted slots become zero. An empty list means SGR reset.
36    /// [`write_sgr`] accepts borrowed slices of these groups.
37    pub params: Vec<Vec<u16>>,
38}
39
40impl Sgr {
41    /// Interpret these parameters from the default [`Style`].
42    ///
43    /// Parameters apply in order. Unknown attributes stay in [`params`](Self::params)
44    /// and do not change the style. Empty groups are skipped, as in [`write_sgr`].
45    pub fn style(&self) -> Style {
46        let mut style = Style::default();
47        read_style_groups(
48            self.params
49                .iter()
50                .filter(|group| !group.is_empty())
51                .map(|group| group.iter().copied().map(u32::from)),
52            &mut style,
53        );
54        style
55    }
56
57    pub(crate) fn from_params(params: Params<'_>) -> Option<Self> {
58        let params = params
59            .iter()
60            .map(|group| {
61                group
62                    .raw()
63                    .split(|&byte| byte == b':')
64                    .map(|slot| {
65                        if slot.is_empty() {
66                            Some(0)
67                        } else {
68                            std::str::from_utf8(slot).ok()?.parse::<u16>().ok()
69                        }
70                    })
71                    .collect::<Option<Vec<_>>>()
72            })
73            .collect::<Option<Vec<_>>>()?;
74        Some(Self { params })
75    }
76}
77
78/// Write an SGR sequence using semicolon-separated groups and colon-separated subparameters.
79///
80/// The emitted format is `ESC [ <params> m`. The outer slice separates primary parameters with `;`; each non-empty inner slice is joined with `:`. An empty outer slice emits `ESC [ m` (SGR reset), and empty inner slices are skipped.
81///
82/// # Examples
83///
84/// ```rust,ignore
85/// // ESC [ 1 ; 31 ; 4 m — bold, red, underline
86/// write_sgr(w, &[&[1], &[31], &[4]])?;
87///
88/// // ESC [ 38 : 2 : 0 : 10 : 20 : 30 m — colon-form truecolor foreground
89/// write_sgr(w, &[&[38, 2, 0, 10, 20, 30]])?;
90///
91/// // ESC [ 0 ; 38 : 2 : 10 : 20 : 30 ; 1 m — mixed groups
92/// write_sgr(w, &[&[0], &[38, 2, 10, 20, 30], &[1]])?;
93/// ```
94pub fn write_sgr<W: Write>(w: &mut W, params: &[&[u16]]) -> io::Result<()> {
95    w.write_all(b"\x1b[")?;
96    let mut first = true;
97    for group in params {
98        if group.is_empty() {
99            continue;
100        }
101        if !first {
102            w.write_all(b";")?;
103        }
104        first = false;
105        for (i, p) in group.iter().enumerate() {
106            if i > 0 {
107                w.write_all(b":")?;
108            }
109            write!(w, "{p}")?;
110        }
111    }
112    w.write_all(b"m")
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use crate::color::Color;
119    use crate::style::UnderlineStyle;
120
121    #[test]
122    fn sgr_style_uses_parameter_order_and_color_groups() {
123        let sgr = Sgr {
124            params: vec![
125                vec![1],
126                vec![31],
127                vec![0],
128                vec![],
129                vec![3],
130                vec![4, 3],
131                vec![38, 2, 0, 10, 20, 30],
132                vec![48],
133                vec![5],
134                vec![200],
135                vec![58, 5, 201],
136                vec![65535],
137            ],
138        };
139        assert_eq!(
140            sgr.style(),
141            Style::new()
142                .italic()
143                .underline_style(UnderlineStyle::Curly)
144                .fg(Color::Rgb(10, 20, 30))
145                .bg(Color::Indexed(200))
146                .underline_color(Color::Indexed(201)),
147        );
148        let groups: Vec<&[u16]> = sgr.params.iter().map(Vec::as_slice).collect();
149        let mut bytes = Vec::new();
150        write_sgr(&mut bytes, &groups).unwrap();
151        assert_eq!(
152            bytes,
153            b"\x1b[1;31;0;3;4:3;38:2:0:10:20:30;48;5;200;58:5:201;65535m",
154        );
155        let mut parsed = Style::default();
156        crate::style::read_style(Params::from_raw(&bytes[2..bytes.len() - 1]), &mut parsed);
157        assert_eq!(parsed, sgr.style());
158    }
159
160    #[test]
161    fn test_empty_is_reset() {
162        let mut buf = Vec::new();
163        write_sgr(&mut buf, &[]).unwrap();
164        assert_eq!(buf, b"\x1b[m");
165    }
166
167    #[test]
168    fn test_semicolon_only() {
169        let mut buf = Vec::new();
170        write_sgr(&mut buf, &[&[1], &[31], &[4]]).unwrap();
171        assert_eq!(buf, b"\x1b[1;31;4m");
172    }
173
174    #[test]
175    fn test_colon_subparams() {
176        let mut buf = Vec::new();
177        write_sgr(&mut buf, &[&[38, 2, 0, 10, 20, 30]]).unwrap();
178        assert_eq!(buf, b"\x1b[38:2:0:10:20:30m");
179    }
180
181    #[test]
182    fn test_mixed() {
183        let mut buf = Vec::new();
184        write_sgr(&mut buf, &[&[0], &[38, 2, 10, 20, 30], &[1]]).unwrap();
185        assert_eq!(buf, b"\x1b[0;38:2:10:20:30;1m");
186    }
187
188    #[test]
189    fn test_skip_empty_groups() {
190        let mut buf = Vec::new();
191        write_sgr(&mut buf, &[&[1], &[], &[4]]).unwrap();
192        assert_eq!(buf, b"\x1b[1;4m");
193    }
194}