uncurses/style/mod.rs
1//! Visual text styles and terminal SGR output.
2//!
3//! ## Style as a value
4//!
5//! [`Style`] is a small, copyable visual value. It contains optional colors,
6//! an [`UnderlineStyle`], and [`AttrFlags`]. Cells store their shared OSC 8
7//! [`Link`] separately. Use [`crate::cell::Cell::set_link`] to attach a link.
8//!
9//! ## Open/close versus wrapped rendering
10//!
11//! The [`std::fmt::Display`] implementation for [`Style`] emits the opener: the
12//! SGR sequence (`CSI ... m`). Following output remains in that style until another style
13//! or reset is written.
14//!
15//! The alternate form (`{style:#}`) emits the matching SGR reset (`CSI m`).
16//! Used together, `{style}` and `{style:#}` wrap a complete
17//! span with a single style value. The SGR reset clears to defaults rather than
18//! restoring a previously active style, so wrap each span independently:
19//!
20//! [`Link`] uses the same format syntax for OSC 8 hyperlinks:
21//! `{link}` opens the link and `{link:#}` closes it. Hyperlink controls
22//! preserve the visual style.
23//!
24//! ## Attributes and underline
25//!
26//! Boolean SGR attributes such as bold, italic, blinking, reverse video,
27//! conceal, and strikethrough live in [`AttrFlags`]. Underlining is modeled
28//! separately with [`UnderlineStyle`] because SGR supports multiple underline
29//! shapes (`4`, `4:2`, `4:3`, `4:4`, `4:5`) and an independent underline
30//! color.
31//!
32//! ## SGR encoding
33//!
34//! Style emission uses a single `CSI … m` sequence for all SGR state. Standard
35//! foreground/background colors use `30`–`37`/`40`–`47`, bright colors use
36//! `90`–`97`/`100`–`107`, indexed colors use `38;5;n`/`48;5;n`, true color
37//! uses `38;2;r;g;b`/`48;2;r;g;b`, and underline color uses the colon
38//! subparameter form (`58:5:n` or `58:2::r:g:b`).
39//!
40//! ```text
41//! ESC [ 1 ; 4:3 ; 38;2;255;128;0 ; 58:2::0:255:255 m
42//! └─┬─┘ └─────────────── SGR parameters ─────────────────────┘ └┬┘
43//! CSI attrs underline fg truecolor ul color final
44//! ```
45//!
46//! ```rust
47//! use uncurses::color::Color;
48//! use uncurses::style::Style;
49//!
50//! // `{style}` writes the opener; `{style:#}` writes the matching closer.
51//! let heading = Style::default().bold().fg(Color::Green);
52//! println!("{heading}Hello{heading:#}");
53//!
54//! let emphasis = Style::default().underline();
55//! println!("{emphasis}docs{emphasis:#}");
56//! ```
57
58pub(crate) mod diff;
59mod parse;
60mod sgr;
61
62pub(crate) use parse::{read_style, read_style_groups};
63#[cfg(test)]
64pub(crate) use sgr::RESET;
65
66use std::borrow::Borrow;
67use std::io::{self, Write};
68
69use bitflags::bitflags;
70
71use crate::color::Color;
72
73#[cfg(test)]
74pub(crate) fn test_link(url: &str, params: &str) -> std::sync::Arc<Link> {
75 std::sync::Arc::new(Link {
76 url: url.into(),
77 params: params.into(),
78 })
79}
80
81/// A shared OSC 8 hyperlink target for a [`Cell`](crate::cell::Cell).
82///
83/// A link is used when styled text should also open a terminal hyperlink.
84/// Cells store links behind an [`Arc`](std::sync::Arc) so many cells in
85/// the same hyperlink span can share one allocation. The URL and parameter
86/// string are emitted verbatim as `OSC 8 ; params ; url ST`; callers are
87/// responsible for passing values that are appropriate for the target
88/// terminal.
89#[derive(Debug, Clone, PartialEq, Eq, Hash)]
90pub struct Link {
91 /// Target URI written into the OSC 8 sequence.
92 ///
93 /// An empty URL clears the link through [`Cell::set_link`](crate::cell::Cell::set_link).
94 pub url: String,
95 /// OSC 8 parameter string written between the two semicolons.
96 ///
97 /// Use an empty string for no parameters, or terminal-supported
98 /// `key=value` pairs such as `id=section`.
99 pub params: String,
100}
101
102/// Render this link as OSC 8 escape sequences.
103///
104/// The default form (`{link}`) writes the parameters and URL verbatim.
105/// An empty URL closes the current hyperlink.
106/// The alternate form (`{link:#}`) closes the current hyperlink with empty
107/// parameters and URL. It preserves the visual style and clears the link
108/// rather than restoring a previous one.
109///
110/// ```
111/// use uncurses::style::Link;
112///
113/// let link = Link {
114/// url: "https://example.com".into(),
115/// params: String::new(),
116/// };
117/// println!("{link}Example{link:#}");
118/// ```
119impl std::fmt::Display for Link {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 if f.alternate() {
122 f.write_str("\x1b]8;;\x1b\\")
123 } else {
124 write!(f, "\x1b]8;{};{}\x1b\\", self.params, self.url)
125 }
126 }
127}
128
129bitflags! {
130 /// Bitflags for SGR text attributes.
131 ///
132 /// These are the boolean attributes that can be combined freely on a
133 /// [`Style`]. Underline shape is tracked separately by
134 /// [`UnderlineStyle`], and colors are stored as [`Color`](crate::color::Color).
135 /// Use [`Style::attrs`] when replacing the whole set, or the convenience
136 /// builders such as [`Style::bold`] and [`Style::italic`] when adding one
137 /// flag at a time.
138 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
139 pub struct AttrFlags: u16 {
140 /// Bold/intense text (`SGR 1`).
141 ///
142 /// Cleared together with [`FAINT`](Self::FAINT) by `SGR 22`.
143 const BOLD = 0b0000_0000_0001;
144 /// Faint/decreased-intensity text (`SGR 2`).
145 ///
146 /// Cleared together with [`BOLD`](Self::BOLD) by `SGR 22`.
147 const FAINT = 0b0000_0000_0010;
148 /// Italic text (`SGR 3`, cleared by `SGR 23`).
149 const ITALIC = 0b0000_0000_0100;
150 /// Slow blinking text (`SGR 5`).
151 ///
152 /// Cleared together with [`RAPID_BLINK`](Self::RAPID_BLINK) by
153 /// `SGR 25`.
154 const SLOW_BLINK = 0b0000_0000_1000;
155 /// Rapid blinking text (`SGR 6`).
156 ///
157 /// Cleared together with [`SLOW_BLINK`](Self::SLOW_BLINK) by
158 /// `SGR 25`.
159 const RAPID_BLINK = 0b0000_0001_0000;
160 /// Reverse foreground and background (`SGR 7`, cleared by `SGR 27`).
161 const REVERSE = 0b0000_0010_0000;
162 /// Concealed text (`SGR 8`, cleared by `SGR 28`).
163 const CONCEAL = 0b0000_0100_0000;
164 /// Struck-through text (`SGR 9`, cleared by `SGR 29`).
165 const STRIKETHROUGH = 0b0000_1000_0000;
166 }
167}
168
169/// Underline shape encoded in SGR underline parameters.
170///
171/// Use [`Style::underline`] for the common single underline or
172/// [`Style::underline_style`] to select an explicit shape. [`None`](Self::None)
173/// means no underline; it emits no parameter when writing a full [`Style`] and
174/// emits `SGR 24` when a diff needs to clear an existing underline.
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
176#[repr(u8)]
177pub enum UnderlineStyle {
178 #[default]
179 /// No underline.
180 None = 0,
181 /// Single underline (`SGR 4` or `4:1` when parsed).
182 Single = 1,
183 /// Double underline (`SGR 4:2`; `SGR 21` is parsed as this variant).
184 Double = 2,
185 /// Curly underline (`SGR 4:3`).
186 Curly = 3,
187 /// Dotted underline (`SGR 4:4`).
188 Dotted = 4,
189 /// Dashed underline (`SGR 4:5`).
190 Dashed = 5,
191}
192
193/// A copyable visual terminal text style.
194///
195/// `Style` is the central value used by cells, text painters, and renderers.
196/// It stores SGR state (foreground/background/underline colors, underline
197/// shape, and attributes). Build styles with
198/// the provided value-taking builders, then render with the
199/// [`std::fmt::Display`] implementation: `{style}` writes the opener and
200/// `{style:#}` writes the matching closer.
201///
202/// Cells store OSC 8 hyperlinks separately from their visual styles.
203#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
204pub struct Style {
205 /// Foreground/text color.
206 ///
207 /// `None` leaves the terminal's current/default foreground unchanged when
208 /// writing a full style; diffs use `SGR 39` to clear a previous foreground.
209 pub fg: Option<Color>,
210 /// Background color.
211 ///
212 /// `None` leaves the terminal's current/default background unchanged when
213 /// writing a full style; diffs use `SGR 49` to clear a previous background.
214 pub bg: Option<Color>,
215 /// Underline color.
216 ///
217 /// Encoded with SGR `58` when present. `None` means use the terminal's
218 /// default underline color; diffs use `SGR 59` to clear a previous value.
219 pub underline_color: Option<Color>,
220 /// Underline shape.
221 pub underline: UnderlineStyle,
222 /// Boolean SGR text attributes.
223 pub attrs: AttrFlags,
224}
225
226impl From<&Style> for Style {
227 /// Copy a borrowed style into an owned one.
228 ///
229 /// This lets APIs that accept `impl Into<Style>` take a `&Style` without
230 /// the caller writing `.clone()`. Owned styles convert for free via the
231 /// blanket `From<Style> for Style`.
232 fn from(style: &Style) -> Self {
233 *style
234 }
235}
236
237impl From<Option<Style>> for Style {
238 /// Convert an optional style, mapping `None` to [`Style::EMPTY`].
239 ///
240 /// This lets APIs that accept `impl Into<Style>` take a bare `None` to mean
241 /// "no styling", e.g. `surface.set_str(pos, text, None)`. `Some(style)`
242 /// unwraps to the contained style.
243 fn from(style: Option<Style>) -> Self {
244 style.unwrap_or(Style::EMPTY)
245 }
246}
247
248impl Style {
249 /// Create an empty style.
250 ///
251 /// Equivalent to [`Style::default`] and [`Style::EMPTY`]: no colors,
252 /// attributes, or underline. Chain the builder methods such as
253 /// [`bold`](Self::bold) or [`fg`](Self::fg) to add settings.
254 pub const fn new() -> Self {
255 Self::EMPTY
256 }
257
258 /// Style with no colors, attributes, or underline.
259 ///
260 /// This is equivalent to [`Style::default()`]. Writing it as a style opener
261 /// emits nothing, since the opener is additive; format any style with the
262 /// alternate flag (`{style:#}`) to emit an explicit return to the terminal
263 /// default.
264 pub const EMPTY: Style = Style {
265 fg: None,
266 bg: None,
267 underline_color: None,
268 underline: UnderlineStyle::None,
269 attrs: AttrFlags::empty(),
270 };
271
272 /// Return whether this style is entirely empty.
273 ///
274 /// Empty means no visual attributes or colors. This is
275 /// equivalent to `*self == Style::EMPTY`.
276 pub fn is_empty(&self) -> bool {
277 self.is_sgr_empty()
278 }
279
280 /// Return whether this style has no SGR-relevant settings.
281 ///
282 /// Colors, attributes, underline shape, and underline color are checked.
283 pub(crate) fn is_sgr_empty(&self) -> bool {
284 self.fg.is_none()
285 && self.bg.is_none()
286 && self.underline_color.is_none()
287 && self.underline == UnderlineStyle::None
288 && self.attrs.is_empty()
289 }
290
291 /// Inherit from `base`, returning `self` with its unset fields filled in.
292 ///
293 /// `self` takes precedence, like a child overriding inherited values: its
294 /// foreground, background, underline color, and underline shape
295 /// win wherever `self` sets them, and `base` only supplies a fallback for
296 /// each field `self` leaves at its default. Attributes from both are
297 /// combined. Inheriting from any `base` therefore never clears a field
298 /// `self` already set, and inheriting from an empty `base` returns `self`
299 /// unchanged.
300 ///
301 /// `base` is borrowed, so either an owned [`Style`] or a `&Style` may be
302 /// passed without cloning.
303 pub fn inherit(&self, base: impl Borrow<Style>) -> Style {
304 let base = base.borrow();
305 Style {
306 fg: self.fg.or(base.fg),
307 bg: self.bg.or(base.bg),
308 underline_color: self.underline_color.or(base.underline_color),
309 underline: if self.underline == UnderlineStyle::None {
310 base.underline
311 } else {
312 self.underline
313 },
314 attrs: self.attrs | base.attrs,
315 }
316 }
317
318 /// Add bold intensity and return the updated style.
319 ///
320 /// This sets [`AttrFlags::BOLD`] and leaves all other fields unchanged.
321 pub fn bold(mut self) -> Self {
322 self.attrs |= AttrFlags::BOLD;
323 self
324 }
325
326 /// Add faint intensity and return the updated style.
327 ///
328 /// This sets [`AttrFlags::FAINT`] and leaves all other fields unchanged.
329 pub fn faint(mut self) -> Self {
330 self.attrs |= AttrFlags::FAINT;
331 self
332 }
333
334 /// Add italic text and return the updated style.
335 ///
336 /// This sets [`AttrFlags::ITALIC`] and leaves all other fields unchanged.
337 pub fn italic(mut self) -> Self {
338 self.attrs |= AttrFlags::ITALIC;
339 self
340 }
341
342 /// Use a single underline and return the updated style.
343 ///
344 /// Equivalent to [`Style::underline_style`] with
345 /// [`UnderlineStyle::Single`].
346 pub fn underline(mut self) -> Self {
347 self.underline = UnderlineStyle::Single;
348 self
349 }
350
351 /// Add strikethrough text and return the updated style.
352 ///
353 /// This sets [`AttrFlags::STRIKETHROUGH`] and leaves all other fields
354 /// unchanged.
355 pub fn strikethrough(mut self) -> Self {
356 self.attrs |= AttrFlags::STRIKETHROUGH;
357 self
358 }
359
360 /// Add slow blinking text and return the updated style.
361 ///
362 /// This sets [`AttrFlags::SLOW_BLINK`] and leaves all other fields
363 /// unchanged.
364 pub fn blink(mut self) -> Self {
365 self.attrs |= AttrFlags::SLOW_BLINK;
366 self
367 }
368
369 /// Add rapid blinking text and return the updated style.
370 ///
371 /// This sets [`AttrFlags::RAPID_BLINK`] and leaves all other fields
372 /// unchanged.
373 pub fn rapid_blink(mut self) -> Self {
374 self.attrs |= AttrFlags::RAPID_BLINK;
375 self
376 }
377
378 /// Reverse foreground and background and return the updated style.
379 ///
380 /// This sets [`AttrFlags::REVERSE`]; it does not swap the stored `fg` and
381 /// `bg` values.
382 pub fn reverse(mut self) -> Self {
383 self.attrs |= AttrFlags::REVERSE;
384 self
385 }
386
387 /// Add concealed text and return the updated style.
388 ///
389 /// This sets [`AttrFlags::CONCEAL`] and leaves all other fields unchanged.
390 pub fn conceal(mut self) -> Self {
391 self.attrs |= AttrFlags::CONCEAL;
392 self
393 }
394
395 /// Set or clear the foreground color and return the updated style.
396 ///
397 /// Accepts any value convertible into `Option<Color>`, including a
398 /// [`Color`] or `None`.
399 /// Passing `None` clears any foreground color carried by the base style.
400 pub fn fg(mut self, color: impl Into<Option<Color>>) -> Self {
401 self.fg = color.into();
402 self
403 }
404
405 /// Set or clear the background color and return the updated style.
406 ///
407 /// Accepts any value convertible into `Option<Color>`, including a
408 /// [`Color`] or `None`.
409 /// Passing `None` clears any background color carried by the base style.
410 pub fn bg(mut self, color: impl Into<Option<Color>>) -> Self {
411 self.bg = color.into();
412 self
413 }
414
415 /// Set or clear the underline color and return the updated style.
416 ///
417 /// Accepts any value convertible into `Option<Color>`, including a
418 /// [`Color`] or `None`.
419 /// Passing `None` clears any underline color carried by the base style.
420 pub fn underline_color(mut self, color: impl Into<Option<Color>>) -> Self {
421 self.underline_color = color.into();
422 self
423 }
424
425 /// Set the underline shape and return the updated style.
426 ///
427 /// Use [`UnderlineStyle::None`] to clear underlining.
428 pub fn underline_style(mut self, style: UnderlineStyle) -> Self {
429 self.underline = style;
430 self
431 }
432
433 /// Replace the entire attribute flag set and return the updated style.
434 ///
435 /// This is useful when applying a previously computed [`AttrFlags`] value.
436 /// Use the convenience builders when adding a single flag.
437 pub fn attrs(mut self, attrs: AttrFlags) -> Self {
438 self.attrs = attrs;
439 self
440 }
441
442 /// Write this style's SGR opener bytes.
443 ///
444 /// Additive: an [empty](Self::is_empty) style writes nothing.
445 fn write_opener<W: Write>(&self, w: &mut W) -> io::Result<()> {
446 sgr::write_style(w, self)
447 }
448
449 /// Write the SGR reset (`CSI m`) when this style carries SGR state.
450 ///
451 /// The SGR reset clears all attributes to their defaults, so the closer
452 /// returns the terminal to a clean state rather than restoring whatever
453 /// style was active before the opener. An [empty](Self::is_empty) style
454 /// writes nothing.
455 fn write_closer<W: Write>(&self, w: &mut W) -> io::Result<()> {
456 if !self.is_sgr_empty() {
457 w.write_all(sgr::RESET)?;
458 }
459 Ok(())
460 }
461}
462
463/// Render this style as ANSI escape sequences.
464///
465/// The default form (`{style}`) renders the **opener**: the SGR sequence
466/// (`CSI ... m`). The opener is additive, so an empty style renders
467/// nothing.
468///
469/// The alternate form (`{style:#}`) renders the **closer**: the SGR
470/// reset (`CSI m`, when it carries SGR state). The SGR reset clears all
471/// attributes to their defaults rather than restoring a previously active
472/// style.
473///
474/// Use the two together to wrap a span with a single style value:
475///
476/// ```
477/// use uncurses::color::Color;
478/// use uncurses::style::Style;
479///
480/// let style = Style::default().bold().fg(Color::Green);
481/// assert_eq!(format!("{style}hi{style:#}"), "\x1b[1;32mhi\x1b[m");
482/// ```
483impl std::fmt::Display for Style {
484 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
485 // SGR sequences and OSC 8 framing are pure ASCII, so the bytes are
486 // valid UTF-8.
487 let mut buf = Vec::new();
488 if f.alternate() {
489 self.write_closer(&mut buf).map_err(|_| std::fmt::Error)?;
490 } else {
491 self.write_opener(&mut buf).map_err(|_| std::fmt::Error)?;
492 }
493 let s = std::str::from_utf8(&buf).map_err(|_| std::fmt::Error)?;
494 f.write_str(s)
495 }
496}
497
498#[cfg(test)]
499mod tests {
500 use super::*;
501 use crate::color::Color;
502
503 #[test]
504 fn link_display_wraps_text_with_verbatim_parameters() {
505 let link = Link {
506 url: "https://example.test/?a=1;b=2".into(),
507 params: "id=docs:foo=bar".into(),
508 };
509 assert_eq!(
510 format!("{link}docs{link:#}"),
511 "\x1b]8;id=docs:foo=bar;https://example.test/?a=1;b=2\x1b\\docs\x1b]8;;\x1b\\"
512 );
513 }
514
515 #[test]
516 fn link_display_with_empty_url_closes_the_link() {
517 let link = Link {
518 url: String::new(),
519 params: String::new(),
520 };
521 assert_eq!(format!("{link}"), "\x1b]8;;\x1b\\");
522 assert_eq!(format!("{link:#}"), "\x1b]8;;\x1b\\");
523 }
524
525 #[test]
526 fn test_style_empty() {
527 assert!(Style::EMPTY.is_empty());
528 assert!(Style::default().is_empty());
529 }
530
531 #[test]
532 fn test_style_builder() {
533 let s = Style::EMPTY.bold().italic().fg(Color::Red);
534 assert!(s.attrs.contains(AttrFlags::BOLD));
535 assert!(s.attrs.contains(AttrFlags::ITALIC));
536 assert_eq!(s.fg, Some(Color::Red));
537 assert!(!s.is_empty());
538 }
539
540 #[test]
541 fn display_emits_sgr_opener_without_reset() {
542 let s = Style::EMPTY.bold().fg(Color::Red);
543 assert_eq!(format!("{s}"), "\x1b[1;31m");
544 }
545
546 #[test]
547 fn display_empty_style_emits_nothing() {
548 assert_eq!(format!("{}", Style::EMPTY), "");
549 }
550
551 #[test]
552 fn span_wraps_text_in_style_and_reset() {
553 let s = Style::EMPTY.bold();
554 // SGR-only style: opener, text, then just the SGR reset (no link close).
555 assert_eq!(format!("{s}hi{s:#}"), "\x1b[1mhi\x1b[m");
556 }
557
558 #[test]
559 fn alternate_display_closes_only_what_is_set() {
560 let s = Style::EMPTY.bold();
561 assert_eq!(format!("{s:#}"), "\x1b[m");
562
563 // An empty style resets nothing.
564 assert_eq!(format!("{:#}", Style::EMPTY), "");
565 }
566
567 #[test]
568 fn inherit_self_wins_and_fills_unset_from_base() {
569 let style = Style::EMPTY.italic().fg(Color::Blue);
570 let base = Style::EMPTY.bold().fg(Color::Red).bg(Color::Black);
571 let merged = style.inherit(base);
572 // self's fg wins; bg is inherited from base; attributes combine.
573 assert_eq!(merged.fg, Some(crate::color::Color::Blue));
574 assert_eq!(merged.bg, Some(crate::color::Color::Black));
575 assert!(merged.attrs.contains(AttrFlags::BOLD));
576 assert!(merged.attrs.contains(AttrFlags::ITALIC));
577 }
578
579 #[test]
580 fn inherit_empty_self_returns_base() {
581 let base = Style::EMPTY.bold().fg(Color::Red);
582 // An empty child inherits everything from the base.
583 assert_eq!(Style::EMPTY.inherit(base), base);
584 }
585
586 #[test]
587 fn inherit_empty_base_keeps_self() {
588 let style = Style::EMPTY.bold().fg(Color::Red);
589 let merged = style.inherit(Style::EMPTY);
590 assert_eq!(merged, style);
591 }
592}