Debian Codegraph @

Xtermina/src/style.rs

raw symbols SCIP
1 //! Types for styling terminal cells.
2 //!
3 //! Terminal styling is controlled by [`Sgr`] commands, the `CSI ... m` escape sequences that set
4 //! foreground color, background color, intensity, underline, and related text attributes. This
5 //! module provides those low-level SGR attribute types and a small [`StyleExt`] convenience trait
6 //! for formatting styled text.
7 //!
8 //! # Examples
9 //!
10 //! ```
11 //! use termina::style::StyleExt as _;
12 //!
13 //! # termina::style::Stylized::force_ansi_color(true);
14 //! let warning = "warning".red().bold();
15 //! assert_eq!(warning.to_string(), "\x1b[0;31;1mwarning\x1b[m");
16 //! ```
17 //!
18 //! # Implementation Notes
19 //!
20 //! Styling support is shared almost fairly between crossterm and TermWiz: SGR property types like
21 //! [`Underline`], [`CursorStyle`], and [`Intensity`] are adapted from [termwiz styling], while
22 //! [`StyleExt`] follows the shape of [crossterm styling] helpers.
23 //!
24 //! [termwiz styling]: https://docs.rs/termwiz/latest/termwiz/
25 //! [crossterm styling]: https://docs.rs/crossterm/latest/crossterm/style/index.html
26
27 use std::{
28 borrow::Cow,
29 fmt::{self, Display},
30 str::FromStr,
31 sync::atomic::{AtomicBool, Ordering},
32 };
33
34 use crate::escape::{
35 self,
36 csi::{Csi, Sgr},
37 };
38
39 /// Styling of a cell's underline according to the [Kitty underline extension].
40 ///
41 /// Single and double underlines are widely understood SGR attributes. Curly, dotted, dashed, and
42 /// colored underlines are extensions and depend on terminal support.
43 ///
44 /// ```
45 /// use termina::{
46 /// escape::csi::{Csi, Sgr},
47 /// style::Underline,
48 /// };
49 ///
50 /// assert_eq!(Csi::Sgr(Sgr::Underline(Underline::Curly)).to_string(), "\x1b[4:3m");
51 /// ```
52 ///
53 /// [kitty underline extension]: https://sw.kovidgoyal.net/kitty/underlines/
54 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
55 pub enum Underline {
56 /// No underline
57 #[default]
58 None = 0,
59
60 /// Straight underline
61 Single = 1,
62
63 /// Two underlines stacked on top of one another
64 Double = 2,
65
66 /// Curly / "squiggly" / "wavy" underline
67 Curly = 3,
68
69 /// Dotted underline
70 Dotted = 4,
71
72 /// Dashed underline
73 Dashed = 5,
74 }
75
76 /// Cursor shape values for [DECSCUSR].
77 ///
78 /// DECSCUSR is the DEC-style cursor shape setting used by many modern terminals. The numeric
79 /// values select the terminal default, block, underline, or vertical-bar cursor, with blinking and
80 /// steady variants where the protocol defines both.
81 ///
82 /// ```
83 /// use termina::{
84 /// escape::csi::{Csi, Cursor},
85 /// style::CursorStyle,
86 /// };
87 ///
88 /// let cursor = Csi::Cursor(Cursor::CursorStyle(CursorStyle::SteadyBar));
89 /// assert_eq!(cursor.to_string(), "\x1b[6 q");
90 /// ```
91 ///
92 /// [DECSCUSR]: https://vt100.net/docs/vt510-rm/DECSCUSR.html
93 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
94 pub enum CursorStyle {
95 /// DECSCUSR value 0: use the terminal's configured cursor style.
96 #[default]
97 Default = 0,
98 /// DECSCUSR value 1: a blinking block cursor.
99 BlinkingBlock = 1,
100 /// DECSCUSR value 2: a steady block cursor.
101 SteadyBlock = 2,
102 /// DECSCUSR value 3: a blinking underline cursor.
103 BlinkingUnderline = 3,
104 /// DECSCUSR value 4: a steady underline cursor.
105 SteadyUnderline = 4,
106 /// DECSCUSR value 5: a blinking vertical bar cursor.
107 BlinkingBar = 5,
108 /// DECSCUSR value 6: a steady vertical bar cursor.
109 SteadyBar = 6,
110 }
111
112 impl Display for CursorStyle {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 write!(f, "{}", *self as u8)
115 }
116 }
117
118 /// An 8-bit "256-color".
119 ///
120 /// Colors 0-15 are the same as [`AnsiColor`] values (0-7 being normal colors and 8-15 being
121 /// "bright").
122 /// Colors 16-231 make up a 6x6x6 "color cube"; 232-255 define a dark-to-light grayscale.
123 ///
124 /// These are also known as "web-safe colors" or "X11 colors" historically, although the actual
125 /// colors varied somewhat between historical usages; see the [ANSI 8-bit color] table.
126 ///
127 /// Convert a `WebColor` into [`ColorSpec`] when building SGR colors:
128 ///
129 /// ```
130 /// use termina::style::{ColorSpec, WebColor};
131 ///
132 /// let orange: ColorSpec = WebColor(208).into();
133 /// assert_eq!(orange, ColorSpec::PaletteIndex(208));
134 /// ```
135 ///
136 /// [ANSI 8-bit color]: https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit
137 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
138 pub struct WebColor(pub u8);
139
140 /// Red, green, and blue color with 8-bit channels.
141 ///
142 /// Use [`Self::new`] for byte channels, [`Self::new_f32`] for normalized floating-point channels,
143 /// or [`str::parse`] for xterm-style color strings:
144 ///
145 /// ```
146 /// use termina::style::{ColorSpec, RgbColor};
147 ///
148 /// let from_bytes = RgbColor::new(40, 80, 120);
149 /// let from_floats = RgbColor::new_f32(0.5, 0.0, 1.0);
150 /// let from_hex: RgbColor = "#285078".parse().unwrap();
151 ///
152 /// assert_eq!(from_bytes, from_hex);
153 /// assert_eq!(from_floats, RgbColor::new(127, 0, 255));
154 ///
155 /// let color_spec: ColorSpec = from_bytes.into();
156 /// assert!(matches!(color_spec, ColorSpec::TrueColor(_)));
157 /// ```
158 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
159 pub struct RgbColor {
160 /// Red channel.
161 pub red: u8,
162 /// Green channel.
163 pub green: u8,
164 /// Blue channel.
165 pub blue: u8,
166 }
167
168 impl RgbColor {
169 /// Creates a new RGB color from 8-bit channel values.
170 pub const fn new(red: u8, green: u8, blue: u8) -> Self {
171 Self { red, green, blue }
172 }
173
174 /// Creates a new RGB color from floating-point channel values.
175 ///
176 /// Values are multiplied by 255 and cast to `u8`. Rust float-to-integer casts round toward
177 /// zero, so fractional values lose their fractional part after scaling. `NaN` and values below
178 /// `0.0` become `0`; values above `1.0` and positive infinity become `255`.
179 pub fn new_f32(red: f32, green: f32, blue: f32) -> Self {
180 let red = (red * 255.) as u8;
181 let green = (green * 255.) as u8;
182 let blue = (blue * 255.) as u8;
183 Self { red, green, blue }
184 }
185
186 fn channel_from_hex(s: &str) -> Result<u8, InvalidFormatError> {
187 if s.is_empty() || s.len() > 4 {
188 return Err(InvalidFormatError);
189 }
190 let color: u16 = u16::from_str_radix(s, 16).map_err(|_| InvalidFormatError)?;
191 let divisor: usize = match s.len() {
192 1 => 0xf,
193 2 => 0xff,
194 3 => 0xfff,
195 4 => 0xffff,
196 _ => return Err(InvalidFormatError),
197 };
198 Ok(((color as usize) * 0xff / divisor) as u8)
199 }
200 }
201
202 /// Error returned when parsing a red, green, and blue color string fails.
203 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
204 pub struct InvalidFormatError;
205
206 impl FromStr for RgbColor {
207 type Err = InvalidFormatError;
208
209 // See `man xparsecolor`. This parses colors according to some of the formats accepted by
210 // xterm's `XParseColor` function.
211 //
212 // 1. rgb:<red>/<green>/<blue>
213 // <red>, <green>, <blue> := h | hh | hhh | hhhh
214 // h := single hexadecimal digits (case insignificant)
215 // 2. #RGB, #RRGGBB, #RRRGGGBBB, #RRRRGGGGBBBB
216 fn from_str(s: &str) -> Result<Self, Self::Err> {
217 if let Some(rgb) = s.strip_prefix("rgb:") {
218 let mut parts = rgb.split('/').map(Self::channel_from_hex);
219 let Some(r) = parts.next().transpose()? else {
220 return Err(InvalidFormatError);
221 };
222 let Some(g) = parts.next().transpose()? else {
223 return Err(InvalidFormatError);
224 };
225 let Some(b) = parts.next().transpose()? else {
226 return Err(InvalidFormatError);
227 };
228 Ok(Self::new(r, g, b))
229 } else if let Some(hex) = s.strip_prefix('#') {
230 let (r, g, b) = match hex.len() {
231 3 => (
232 Self::channel_from_hex(&hex[0..1])?,
233 Self::channel_from_hex(&hex[1..2])?,
234 Self::channel_from_hex(&hex[2..3])?,
235 ),
236 6 => (
237 Self::channel_from_hex(&hex[0..2])?,
238 Self::channel_from_hex(&hex[2..4])?,
239 Self::channel_from_hex(&hex[4..6])?,
240 ),
241 9 => (
242 Self::channel_from_hex(&hex[0..3])?,
243 Self::channel_from_hex(&hex[3..6])?,
244 Self::channel_from_hex(&hex[6..9])?,
245 ),
246 12 => (
247 Self::channel_from_hex(&hex[0..4])?,
248 Self::channel_from_hex(&hex[4..8])?,
249 Self::channel_from_hex(&hex[8..12])?,
250 ),
251 _ => return Err(InvalidFormatError),
252 };
253 Ok(Self::new(r, g, b))
254 } else {
255 Err(InvalidFormatError)
256 }
257 }
258 }
259
260 /// Red, green, blue, and alpha color with 8-bit channels.
261 ///
262 /// Alpha defaults to fully opaque when converting from [`RgbColor`]. Converting back to
263 /// [`RgbColor`] drops the alpha channel because standard terminal foreground/background colors are
264 /// RGB values.
265 ///
266 /// ```
267 /// use termina::style::{RgbColor, RgbaColor};
268 ///
269 /// let rgb = RgbColor::new(10, 20, 30);
270 /// let rgba = RgbaColor::from(rgb);
271 /// assert_eq!(rgba.alpha, 255);
272 /// assert_eq!(RgbColor::from(rgba), rgb);
273 /// ```
274 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
275 pub struct RgbaColor {
276 /// Red channel.
277 pub red: u8,
278 /// Green channel.
279 pub green: u8,
280 /// Blue channel.
281 pub blue: u8,
282 /// Also known as "opacity"
283 pub alpha: u8,
284 }
285
286 impl From<RgbaColor> for RgbColor {
287 fn from(color: RgbaColor) -> Self {
288 Self {
289 red: color.red,
290 green: color.green,
291 blue: color.blue,
292 }
293 }
294 }
295
296 impl From<RgbColor> for RgbaColor {
297 fn from(color: RgbColor) -> Self {
298 Self {
299 red: color.red,
300 green: color.green,
301 blue: color.blue,
302 alpha: 255,
303 }
304 }
305 }
306
307 /// Named ANSI colors used by standard 16-color palettes.
308 ///
309 /// The numeric SGR assignments are stable, but names are not fully consistent across terminal
310 /// libraries. In particular, SGR 37 may be called white, gray, or silver, while SGR 97 may be
311 /// called bright white, light white, or white. Termina names the base 37 color [`Self::White`] and
312 /// the bright 97 color [`Self::BrightWhite`]. Ratatui documents the same naming ambiguity in its
313 /// [ANSI color table].
314 ///
315 /// `AnsiColor` converts to [`ColorSpec`] through the indexed palette path:
316 ///
317 /// ```
318 /// use termina::style::{AnsiColor, ColorSpec};
319 ///
320 /// let red: ColorSpec = AnsiColor::Red.into();
321 /// assert_eq!(red, ColorSpec::RED);
322 /// ```
323 ///
324 /// [ANSI color table]: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
325 /// [Ratatui color docs]: https://docs.rs/ratatui/latest/ratatui/style/enum.Color.html
326 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
327 pub enum AnsiColor {
328 /// The standard black palette entry.
329 Black = 0,
330 /// The standard red palette entry.
331 Red,
332 /// The standard green palette entry.
333 Green,
334 /// The standard yellow palette entry.
335 Yellow,
336 /// The standard blue palette entry.
337 Blue,
338 /// The standard magenta palette entry.
339 Magenta,
340 /// The standard cyan palette entry.
341 Cyan,
342 /// The standard white palette entry.
343 ///
344 /// This is SGR 37. Some terminal libraries call this gray or silver and reserve white for the
345 /// bright SGR 97 color.
346 White,
347 /// Bright black.
348 ///
349 /// This is SGR 90. Some terminal libraries call this dark gray, gray, light black, or bright
350 /// black.
351 BrightBlack,
352 /// The bright red palette entry.
353 BrightRed,
354 /// The bright green palette entry.
355 BrightGreen,
356 /// The bright yellow palette entry.
357 BrightYellow,
358 /// The bright blue palette entry.
359 BrightBlue,
360 /// The bright magenta palette entry.
361 BrightMagenta,
362 /// The bright cyan palette entry.
363 BrightCyan,
364 /// The bright white palette entry.
365 ///
366 /// This is SGR 97. Some terminal libraries call this white, bright white, or light white.
367 BrightWhite,
368 }
369
370 /// Index into the terminal's 256-color palette.
371 pub type PaletteIndex = u8;
372
373 /// Terminal color specification for [`Sgr`] color commands.
374 ///
375 /// This is the common color input type for foreground, background, and underline colors. Named
376 /// ANSI colors and 256-color palette values use [`Self::PaletteIndex`]; true-color values use
377 /// [`Self::TrueColor`]; [`Self::Reset`] returns the terminal color to its default.
378 ///
379 /// ```
380 /// use termina::{
381 /// escape::csi::{Csi, Sgr},
382 /// style::{ColorSpec, RgbColor},
383 /// };
384 ///
385 /// assert_eq!(Csi::Sgr(Sgr::Foreground(ColorSpec::RED)).to_string(), "\x1b[31m");
386 ///
387 /// let blue = ColorSpec::from(RgbColor::new(0, 0, 255));
388 /// assert_eq!(Csi::Sgr(Sgr::Foreground(blue)).to_string(), "\x1b[38;2;0;0;255m");
389 /// ```
390 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
391 pub enum ColorSpec {
392 /// Reset the color back to the terminal default.
393 ///
394 /// For SGR foreground and background colors this formats as the standard reset color codes
395 /// rather than as an indexed palette color.
396 Reset,
397
398 /// Use an indexed palette color.
399 ///
400 /// Values 0-15 address the standard ANSI palette. Values 16-255 address the 256-color
401 /// extension palette described by [`WebColor`].
402 PaletteIndex(PaletteIndex),
403
404 /// Use a true-color red, green, blue, and alpha value.
405 ///
406 /// Red, green, and blue values format using SGR true-color parameters. Non-opaque alpha uses
407 /// the colon form from ITU T.416-style color notation.
408 TrueColor(RgbaColor),
409 }
410
411 impl ColorSpec {
412 /// Standard black palette color.
413 pub const BLACK: Self = Self::PaletteIndex(AnsiColor::Black as PaletteIndex);
414 /// Standard red palette color.
415 pub const RED: Self = Self::PaletteIndex(AnsiColor::Red as PaletteIndex);
416 /// Standard green palette color.
417 pub const GREEN: Self = Self::PaletteIndex(AnsiColor::Green as PaletteIndex);
418 /// Standard yellow palette color.
419 pub const YELLOW: Self = Self::PaletteIndex(AnsiColor::Yellow as PaletteIndex);
420 /// Standard blue palette color.
421 pub const BLUE: Self = Self::PaletteIndex(AnsiColor::Blue as PaletteIndex);
422 /// Standard magenta palette color.
423 pub const MAGENTA: Self = Self::PaletteIndex(AnsiColor::Magenta as PaletteIndex);
424 /// Standard cyan palette color.
425 pub const CYAN: Self = Self::PaletteIndex(AnsiColor::Cyan as PaletteIndex);
426 /// Standard white palette color.
427 pub const WHITE: Self = Self::PaletteIndex(AnsiColor::White as PaletteIndex);
428 /// Bright black palette color.
429 pub const BRIGHT_BLACK: Self = Self::PaletteIndex(AnsiColor::BrightBlack as PaletteIndex);
430 /// Bright red palette color.
431 pub const BRIGHT_RED: Self = Self::PaletteIndex(AnsiColor::BrightRed as PaletteIndex);
432 /// Bright green palette color.
433 pub const BRIGHT_GREEN: Self = Self::PaletteIndex(AnsiColor::BrightGreen as PaletteIndex);
434 /// Bright yellow palette color.
435 pub const BRIGHT_YELLOW: Self = Self::PaletteIndex(AnsiColor::BrightYellow as PaletteIndex);
436 /// Bright blue palette color.
437 pub const BRIGHT_BLUE: Self = Self::PaletteIndex(AnsiColor::BrightBlue as PaletteIndex);
438 /// Bright magenta palette color.
439 pub const BRIGHT_MAGENTA: Self = Self::PaletteIndex(AnsiColor::BrightMagenta as PaletteIndex);
440 /// Bright cyan palette color.
441 pub const BRIGHT_CYAN: Self = Self::PaletteIndex(AnsiColor::BrightCyan as PaletteIndex);
442 /// Bright white palette color.
443 pub const BRIGHT_WHITE: Self = Self::PaletteIndex(AnsiColor::BrightWhite as PaletteIndex);
444 }
445
446 impl From<AnsiColor> for ColorSpec {
447 fn from(color: AnsiColor) -> Self {
448 Self::PaletteIndex(color as u8)
449 }
450 }
451
452 impl From<WebColor> for ColorSpec {
453 fn from(color: WebColor) -> Self {
454 Self::PaletteIndex(color.0)
455 }
456 }
457
458 impl From<RgbColor> for ColorSpec {
459 fn from(color: RgbColor) -> Self {
460 Self::TrueColor(color.into())
461 }
462 }
463
464 impl From<RgbaColor> for ColorSpec {
465 fn from(color: RgbaColor) -> Self {
466 Self::TrueColor(color)
467 }
468 }
469
470 /// Text intensity for [`Sgr`].
471 ///
472 /// Use this directly with [`Sgr::Intensity`] when building escape sequences, or through
473 /// [`StyleExt::bold`] for simple styled strings.
474 ///
475 /// ```
476 /// use termina::{
477 /// escape::csi::{Csi, Sgr},
478 /// style::{Intensity, StyleExt as _},
479 /// };
480 ///
481 /// assert_eq!(Csi::Sgr(Sgr::Intensity(Intensity::Bold)).to_string(), "\x1b[1m");
482 ///
483 /// # termina::style::Stylized::force_ansi_color(true);
484 /// assert_eq!("warn".bold().to_string(), "\x1b[0;1mwarn\x1b[m");
485 /// ```
486 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
487 pub enum Intensity {
488 /// SGR 22: normal text intensity.
489 #[default]
490 Normal,
491 /// SGR 1: bold text intensity.
492 Bold,
493 /// SGR 2: dim text intensity.
494 Dim,
495 }
496
497 /// Text blink mode for [`Sgr`].
498 ///
499 /// Blink support is terminal-dependent. Some terminals ignore blink entirely or let users disable
500 /// it in their settings.
501 ///
502 /// ```
503 /// use termina::{
504 /// escape::csi::{Csi, Sgr},
505 /// style::Blink,
506 /// };
507 ///
508 /// assert_eq!(Csi::Sgr(Sgr::Blink(Blink::Slow)).to_string(), "\x1b[5m");
509 /// ```
510 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
511 pub enum Blink {
512 /// SGR 25: disable blinking text.
513 #[default]
514 None,
515 /// SGR 5: slow blinking text.
516 Slow,
517 /// SGR 6: rapid blinking text.
518 Rapid,
519 }
520
521 /// Font selection for SGR parameters 10-19.
522 ///
523 /// Alternate fonts are terminal-dependent and uncommon in modern terminal applications. The
524 /// variant value maps to SGR 11 through SGR 19; `Font::Alternate(1)` emits SGR 11.
525 ///
526 /// ```
527 /// use termina::{
528 /// escape::csi::{Csi, Sgr},
529 /// style::Font,
530 /// };
531 ///
532 /// assert_eq!(Csi::Sgr(Sgr::Font(Font::Alternate(1))).to_string(), "\x1b[11m");
533 /// ```
534 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
535 pub enum Font {
536 /// SGR 10: use the default font.
537 #[default]
538 Default,
539
540 /// SGR 11-19: select an alternate font.
541 ///
542 /// Valid values are 1-9, corresponding to SGR 11 through SGR 19.
543 Alternate(u8),
544 }
545
546 /// Vertical alignment for [`Sgr`].
547 ///
548 /// Superscript and subscript support is terminal-dependent.
549 ///
550 /// ```
551 /// use termina::{
552 /// escape::csi::{Csi, Sgr},
553 /// style::VerticalAlign,
554 /// };
555 ///
556 /// let superscript = Csi::Sgr(Sgr::VerticalAlign(VerticalAlign::SuperScript));
557 /// assert_eq!(superscript.to_string(), "\x1b[73m");
558 /// ```
559 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
560 pub enum VerticalAlign {
561 /// SGR 75: baseline text alignment.
562 #[default]
563 BaseLine = 0,
564 /// SGR 73: superscript text alignment.
565 SuperScript = 1,
566 /// SGR 74: subscript text alignment.
567 SubScript = 2,
568 }
569
570 /// Styled text that renders by surrounding content with SGR escape sequences.
571 ///
572 /// Use this for simple styled strings, for example a CLI help string. Code that already writes
573 /// structured terminal output can use [`crate::escape::csi::Sgr`] directly instead.
574 ///
575 /// Instead of using this type directly, `use` the [`StyleExt`] trait and the helper functions
576 /// attached to strings:
577 ///
578 /// ```
579 /// use termina::style::StyleExt as _;
580 ///
581 /// # termina::style::Stylized::force_ansi_color(true);
582 /// assert_eq!(
583 /// "warning".red().bold().underlined().to_string(),
584 /// "\x1b[0;31;1;4mwarning\x1b[m",
585 /// );
586 /// ```
587 ///
588 /// [`PlatformTerminal`]: crate::PlatformTerminal
589 #[derive(Debug, Clone, PartialEq, Eq)]
590 pub struct Stylized<'a> {
591 /// The text rendered between the opening SGR sequence and reset sequence.
592 pub content: Cow<'a, str>,
593 styles: Vec<Sgr>,
594 }
595
596 static INITIALIZER: parking_lot::Once = parking_lot::Once::new();
597 static NO_COLOR: AtomicBool = AtomicBool::new(false);
598
599 impl Stylized<'_> {
600 /// Checks whether ANSI color sequences were turned off in the environment.
601 ///
602 /// This follows the guidance on [no-color.org][no-color]: if the `NO_COLOR` environment
603 /// variable is present and non-empty, color escape sequences will be omitted when rendering
604 /// this struct. This behavior can be overridden with [Self::force_ansi_color].
605 ///
606 /// [no-color]: https://no-color.org/
607 pub fn is_ansi_color_disabled() -> bool {
608 // Guidance on disabling colors comes from the no-color.org recommendations.
609 INITIALIZER.call_once(|| {
610 NO_COLOR.store(
611 std::env::var("NO_COLOR").is_ok_and(|e| !e.is_empty()),
612 Ordering::SeqCst,
613 );
614 });
615 NO_COLOR.load(Ordering::SeqCst)
616 }
617
618 /// Overrides detection of the `NO_COLOR` environment variable.
619 ///
620 /// Pass `true` to ensure that ANSI color codes are always included when displaying this type
621 /// or `false` to ensure ANSI color codes are never included.
622 pub fn force_ansi_color(enable_color: bool) {
623 // Run the `Once` first so this override is not later overwritten by the `Once` fn.
624 let _ = Self::is_ansi_color_disabled();
625 NO_COLOR.store(!enable_color, Ordering::SeqCst);
626 }
627 }
628
629 impl Display for Stylized<'_> {
630 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
631 let no_color = Self::is_ansi_color_disabled();
632 let mut styles = self
633 .styles
634 .iter()
635 .filter(|sgr| {
636 !(no_color
637 && matches!(
638 sgr,
639 Sgr::Foreground(_) | Sgr::Background(_) | Sgr::UnderlineColor(_)
640 ))
641 })
642 .peekable();
643
644 if styles.peek().is_none() {
645 write!(f, "{}", self.content)?;
646 } else {
647 write!(f, "{}0", escape::CSI)?;
648 for sgr in styles {
649 write!(f, ";{sgr}")?;
650 }
651 write!(f, "m{}{}", self.content, Csi::Sgr(Sgr::Reset))?;
652 }
653 Ok(())
654 }
655 }
656
657 /// Convenience methods for building [`Stylized`] text.
658 ///
659 /// Methods that accept `impl Into<ColorSpec>` work with named ANSI colors, 256-color palette
660 /// values, and true-color RGB values:
661 ///
662 /// ```
663 /// use termina::style::{AnsiColor, RgbColor, StyleExt as _, Stylized, WebColor};
664 ///
665 /// Stylized::force_ansi_color(true);
666 ///
667 /// assert_eq!("red".foreground(AnsiColor::Red).to_string(), "\x1b[0;31mred\x1b[m");
668 /// assert_eq!("orange".foreground(WebColor(208)).to_string(), "\x1b[0;38;5;208morange\x1b[m");
669 /// assert_eq!(
670 /// "blue".foreground(RgbColor::new(0, 0, 255)).bold().to_string(),
671 /// "\x1b[0;38;2;0;0;255;1mblue\x1b[m",
672 /// );
673 /// ```
674 pub trait StyleExt<'a>: Sized {
675 /// Wraps this value in [`Stylized`] without adding styles.
676 fn stylized(self) -> Stylized<'a>;
677
678 /// Adds a foreground color.
679 fn foreground(self, color: impl Into<ColorSpec>) -> Stylized<'a> {
680 let mut this = self.stylized();
681 this.styles.push(Sgr::Foreground(color.into()));
682 this
683 }
684 /// Adds the standard red foreground color.
685 fn red(self) -> Stylized<'a> {
686 self.foreground(ColorSpec::RED)
687 }
688 /// Adds the standard yellow foreground color.
689 fn yellow(self) -> Stylized<'a> {
690 self.foreground(ColorSpec::YELLOW)
691 }
692 /// Adds the standard green foreground color.
693 fn green(self) -> Stylized<'a> {
694 self.foreground(ColorSpec::GREEN)
695 }
696 /// Adds a single underline.
697 fn underlined(self) -> Stylized<'a> {
698 let mut this = self.stylized();
699 this.styles.push(Sgr::Underline(Underline::Single));
700 this
701 }
702 /// Adds bold intensity.
703 fn bold(self) -> Stylized<'a> {
704 let mut this = self.stylized();
705 this.styles.push(Sgr::Intensity(Intensity::Bold));
706 this
707 }
708 }
709
710 impl<'a> StyleExt<'a> for Cow<'a, str> {
711 fn stylized(self) -> Stylized<'a> {
712 Stylized {
713 content: self,
714 styles: Vec::with_capacity(2),
715 }
716 }
717 }
718
719 impl<'a> StyleExt<'a> for &'a str {
720 fn stylized(self) -> Stylized<'a> {
721 Cow::Borrowed(self).stylized()
722 }
723 }
724
725 impl StyleExt<'static> for String {
726 fn stylized(self) -> Stylized<'static> {
727 Cow::<str>::Owned(self).stylized()
728 }
729 }
730
731 // NOTE: this allows chaining like `"hello".green().bold()`.
732 impl<'a> StyleExt<'a> for Stylized<'a> {
733 fn stylized(self) -> Stylized<'a> {
734 self
735 }
736 }
737
738 #[cfg(test)]
739 mod test {
740 use super::*;
741
742 #[test]
743 fn parse_color() {
744 assert_eq!("#282828".parse(), Ok(RgbColor::new(40, 40, 40)));
745 assert_eq!("rgb:28/28/28".parse(), Ok(RgbColor::new(40, 40, 40)));
746 assert_eq!("rgb:2828/2828/2828".parse(), Ok(RgbColor::new(40, 40, 40)));
747 }
748 }