blazer 0.1.2

A blazing fast, feature-rich library for styling and enhancing CLI output in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! Text styling functionality including colors, bold, italic, underline, and more.
//!
//! This is the core module of Blazer, providing the [`Stylize`] trait that
//! extends string types with chainable styling methods, and the
//! [`StyledString`] type that holds the resulting style information.

use crate::color::Color;
use std::fmt;

/// The reset sequence, used to reset all styling.
pub const RESET: &str = "\x1b[0m";

/// Internal set of boolean text attributes (bold, italic, etc.).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct Attributes {
    bold: bool,
    dim: bool,
    italic: bool,
    underline: bool,
    blink: bool,
    reverse: bool,
    hidden: bool,
    strikethrough: bool,
}

/// A string value paired with styling information (color, boldness, etc.).
///
/// `StyledString` is produced by calling methods from the [`Stylize`] trait
/// on any `&str` or `String`, or by constructing one directly with
/// [`StyledString::new`]. It implements [`Display`](fmt::Display), so it can
/// be printed directly or formatted into other strings.
///
/// # Examples
///
/// ```
/// use blazer::Stylize;
///
/// let s = "Hello".red().bold();
/// println!("{}", s);
/// assert_eq!(s.to_string(), "\u{1b}[1;31mHello\u{1b}[0m");
/// ```
#[derive(Debug, Clone)]
pub struct StyledString {
    text: String,
    fg: Option<Color>,
    bg: Option<Color>,
    attrs: Attributes,
}

// Generates a chainable foreground color method on `StyledString`.
macro_rules! inherent_color_method {
    ($name:ident, $doc:expr, $color:expr) => {
        #[doc = $doc]
        pub fn $name(self) -> StyledString {
            self.color($color)
        }
    };
}

// Generates a chainable background color method on `StyledString`.
macro_rules! inherent_bg_method {
    ($name:ident, $doc:expr, $color:expr) => {
        #[doc = $doc]
        pub fn $name(self) -> StyledString {
            self.on_color($color)
        }
    };
}

impl StyledString {
    /// Creates a new, unstyled `StyledString` from any value convertible
    /// into a `String`.
    pub fn new(text: impl Into<String>) -> Self {
        StyledString {
            text: text.into(),
            fg: None,
            bg: None,
            attrs: Attributes::default(),
        }
    }

    /// Sets the foreground color.
    pub fn color(mut self, color: Color) -> Self {
        self.fg = Some(color);
        self
    }

    /// Sets the background color.
    pub fn on_color(mut self, color: Color) -> Self {
        self.bg = Some(color);
        self
    }

    /// Makes the text bold.
    pub fn bold(mut self) -> Self {
        self.attrs.bold = true;
        self
    }

    /// Makes the text dim/faint.
    pub fn dim(mut self) -> Self {
        self.attrs.dim = true;
        self
    }

    /// Makes the text italic.
    pub fn italic(mut self) -> Self {
        self.attrs.italic = true;
        self
    }

    /// Underlines the text.
    pub fn underline(mut self) -> Self {
        self.attrs.underline = true;
        self
    }

    /// Makes the text blink (not supported by all terminals).
    pub fn blink(mut self) -> Self {
        self.attrs.blink = true;
        self
    }

    /// Reverses the foreground and background colors.
    pub fn reverse(mut self) -> Self {
        self.attrs.reverse = true;
        self
    }

    /// Hides the text (useful for secrets); matches foreground to background.
    pub fn hidden(mut self) -> Self {
        self.attrs.hidden = true;
        self
    }

    /// Adds a strikethrough to the text.
    pub fn strikethrough(mut self) -> Self {
        self.attrs.strikethrough = true;
        self
    }

    /// Sets a 256-color palette foreground color.
    pub fn fixed(self, n: u8) -> Self {
        self.color(Color::Fixed(n))
    }

    /// Sets an RGB truecolor foreground color.
    pub fn rgb(self, r: u8, g: u8, b: u8) -> Self {
        self.color(Color::Rgb(r, g, b))
    }

    /// Sets an RGB truecolor background color.
    pub fn on_rgb(self, r: u8, g: u8, b: u8) -> Self {
        self.on_color(Color::Rgb(r, g, b))
    }

    inherent_color_method!(black, "Sets foreground to black.", Color::Black);
    inherent_color_method!(red, "Sets foreground to red.", Color::Red);
    inherent_color_method!(green, "Sets foreground to green.", Color::Green);
    inherent_color_method!(yellow, "Sets foreground to yellow.", Color::Yellow);
    inherent_color_method!(blue, "Sets foreground to blue.", Color::Blue);
    inherent_color_method!(magenta, "Sets foreground to magenta.", Color::Magenta);
    inherent_color_method!(cyan, "Sets foreground to cyan.", Color::Cyan);
    inherent_color_method!(white, "Sets foreground to white.", Color::White);
    inherent_color_method!(bright_black, "Sets foreground to bright black.", Color::BrightBlack);
    inherent_color_method!(bright_red, "Sets foreground to bright red.", Color::BrightRed);
    inherent_color_method!(bright_green, "Sets foreground to bright green.", Color::BrightGreen);
    inherent_color_method!(bright_yellow, "Sets foreground to bright yellow.", Color::BrightYellow);
    inherent_color_method!(bright_blue, "Sets foreground to bright blue.", Color::BrightBlue);
    inherent_color_method!(bright_magenta, "Sets foreground to bright magenta.", Color::BrightMagenta);
    inherent_color_method!(bright_cyan, "Sets foreground to bright cyan.", Color::BrightCyan);
    inherent_color_method!(bright_white, "Sets foreground to bright white.", Color::BrightWhite);

    inherent_bg_method!(on_black, "Sets background to black.", Color::Black);
    inherent_bg_method!(on_red, "Sets background to red.", Color::Red);
    inherent_bg_method!(on_green, "Sets background to green.", Color::Green);
    inherent_bg_method!(on_yellow, "Sets background to yellow.", Color::Yellow);
    inherent_bg_method!(on_blue, "Sets background to blue.", Color::Blue);
    inherent_bg_method!(on_magenta, "Sets background to magenta.", Color::Magenta);
    inherent_bg_method!(on_cyan, "Sets background to cyan.", Color::Cyan);
    inherent_bg_method!(on_white, "Sets background to white.", Color::White);
    inherent_bg_method!(on_bright_black, "Sets background to bright black.", Color::BrightBlack);
    inherent_bg_method!(on_bright_red, "Sets background to bright red.", Color::BrightRed);
    inherent_bg_method!(on_bright_green, "Sets background to bright green.", Color::BrightGreen);
    inherent_bg_method!(on_bright_yellow, "Sets background to bright yellow.", Color::BrightYellow);
    inherent_bg_method!(on_bright_blue, "Sets background to bright blue.", Color::BrightBlue);
    inherent_bg_method!(on_bright_magenta, "Sets background to bright magenta.", Color::BrightMagenta);
    inherent_bg_method!(on_bright_cyan, "Sets background to bright cyan.", Color::BrightCyan);
    inherent_bg_method!(on_bright_white, "Sets background to bright white.", Color::BrightWhite);

    /// Builds the ANSI escape prefix representing all currently-set styles.
    fn build_prefix(&self) -> String {
        let mut codes: Vec<String> = Vec::new();

        if self.attrs.bold {
            codes.push("1".into());
        }
        if self.attrs.dim {
            codes.push("2".into());
        }
        if self.attrs.italic {
            codes.push("3".into());
        }
        if self.attrs.underline {
            codes.push("4".into());
        }
        if self.attrs.blink {
            codes.push("5".into());
        }
        if self.attrs.reverse {
            codes.push("7".into());
        }
        if self.attrs.hidden {
            codes.push("8".into());
        }
        if self.attrs.strikethrough {
            codes.push("9".into());
        }
        if let Some(fg) = self.fg {
            codes.push(fg.fg_code());
        }
        if let Some(bg) = self.bg {
            codes.push(bg.bg_code());
        }

        if codes.is_empty() {
            String::new()
        } else {
            format!("\x1b[{}m", codes.join(";"))
        }
    }
}

impl fmt::Display for StyledString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let prefix = self.build_prefix();
        if prefix.is_empty() {
            write!(f, "{}", self.text)
        } else {
            write!(f, "{}{}{}", prefix, self.text, RESET)
        }
    }
}

// Generates a chainable foreground color default-method on the `Stylize` trait.
macro_rules! trait_color_method {
    ($name:ident, $doc:expr, $color:expr) => {
        #[doc = $doc]
        fn $name(self) -> StyledString {
            self.stylize().color($color)
        }
    };
}

// Generates a chainable background color default-method on the `Stylize` trait.
macro_rules! trait_bg_method {
    ($name:ident, $doc:expr, $color:expr) => {
        #[doc = $doc]
        fn $name(self) -> StyledString {
            self.stylize().on_color($color)
        }
    };
}

/// Extension trait providing chainable styling methods for string-like types.
///
/// Implemented for `&str` and `String`, allowing you to write expressive,
/// chainable color and style declarations without manually constructing
/// ANSI escape codes.
///
/// # Examples
///
/// ```
/// use blazer::Stylize;
///
/// println!("{}", "Error!".red().bold());
/// println!("{}", "Success".green().underline());
/// println!("{}", "Custom".rgb(255, 100, 0));
/// println!("{}", "Highlighted".black().on_yellow());
/// ```
pub trait Stylize: Sized {
    /// Converts `self` into a [`StyledString`] with no styling applied yet.
    fn stylize(self) -> StyledString;

    /// Sets an arbitrary foreground [`Color`].
    fn color(self, color: Color) -> StyledString {
        self.stylize().color(color)
    }

    /// Sets an arbitrary background [`Color`].
    fn on_color(self, color: Color) -> StyledString {
        self.stylize().on_color(color)
    }

    /// Makes the text bold.
    fn bold(self) -> StyledString {
        self.stylize().bold()
    }

    /// Makes the text dim/faint.
    fn dim(self) -> StyledString {
        self.stylize().dim()
    }

    /// Makes the text italic.
    fn italic(self) -> StyledString {
        self.stylize().italic()
    }

    /// Underlines the text.
    fn underline(self) -> StyledString {
        self.stylize().underline()
    }

    /// Makes the text blink (not supported by all terminals).
    fn blink(self) -> StyledString {
        self.stylize().blink()
    }

    /// Reverses the foreground and background colors.
    fn reverse(self) -> StyledString {
        self.stylize().reverse()
    }

    /// Hides the text (useful for secrets).
    fn hidden(self) -> StyledString {
        self.stylize().hidden()
    }

    /// Adds a strikethrough to the text.
    fn strikethrough(self) -> StyledString {
        self.stylize().strikethrough()
    }

    /// Sets a 256-color palette foreground color.
    fn fixed(self, n: u8) -> StyledString {
        self.stylize().color(Color::Fixed(n))
    }

    /// Sets an RGB truecolor foreground color.
    fn rgb(self, r: u8, g: u8, b: u8) -> StyledString {
        self.stylize().color(Color::Rgb(r, g, b))
    }

    /// Sets an RGB truecolor background color.
    fn on_rgb(self, r: u8, g: u8, b: u8) -> StyledString {
        self.stylize().on_color(Color::Rgb(r, g, b))
    }

    trait_color_method!(black, "Sets foreground to black.", Color::Black);
    trait_color_method!(red, "Sets foreground to red.", Color::Red);
    trait_color_method!(green, "Sets foreground to green.", Color::Green);
    trait_color_method!(yellow, "Sets foreground to yellow.", Color::Yellow);
    trait_color_method!(blue, "Sets foreground to blue.", Color::Blue);
    trait_color_method!(magenta, "Sets foreground to magenta.", Color::Magenta);
    trait_color_method!(cyan, "Sets foreground to cyan.", Color::Cyan);
    trait_color_method!(white, "Sets foreground to white.", Color::White);
    trait_color_method!(bright_black, "Sets foreground to bright black.", Color::BrightBlack);
    trait_color_method!(bright_red, "Sets foreground to bright red.", Color::BrightRed);
    trait_color_method!(bright_green, "Sets foreground to bright green.", Color::BrightGreen);
    trait_color_method!(bright_yellow, "Sets foreground to bright yellow.", Color::BrightYellow);
    trait_color_method!(bright_blue, "Sets foreground to bright blue.", Color::BrightBlue);
    trait_color_method!(bright_magenta, "Sets foreground to bright magenta.", Color::BrightMagenta);
    trait_color_method!(bright_cyan, "Sets foreground to bright cyan.", Color::BrightCyan);
    trait_color_method!(bright_white, "Sets foreground to bright white.", Color::BrightWhite);

    trait_bg_method!(on_black, "Sets background to black.", Color::Black);
    trait_bg_method!(on_red, "Sets background to red.", Color::Red);
    trait_bg_method!(on_green, "Sets background to green.", Color::Green);
    trait_bg_method!(on_yellow, "Sets background to yellow.", Color::Yellow);
    trait_bg_method!(on_blue, "Sets background to blue.", Color::Blue);
    trait_bg_method!(on_magenta, "Sets background to magenta.", Color::Magenta);
    trait_bg_method!(on_cyan, "Sets background to cyan.", Color::Cyan);
    trait_bg_method!(on_white, "Sets background to white.", Color::White);
    trait_bg_method!(on_bright_black, "Sets background to bright black.", Color::BrightBlack);
    trait_bg_method!(on_bright_red, "Sets background to bright red.", Color::BrightRed);
    trait_bg_method!(on_bright_green, "Sets background to bright green.", Color::BrightGreen);
    trait_bg_method!(on_bright_yellow, "Sets background to bright yellow.", Color::BrightYellow);
    trait_bg_method!(on_bright_blue, "Sets background to bright blue.", Color::BrightBlue);
    trait_bg_method!(on_bright_magenta, "Sets background to bright magenta.", Color::BrightMagenta);
    trait_bg_method!(on_bright_cyan, "Sets background to bright cyan.", Color::BrightCyan);
    trait_bg_method!(on_bright_white, "Sets background to bright white.", Color::BrightWhite);
}

impl Stylize for &str {
    fn stylize(self) -> StyledString {
        StyledString::new(self)
    }
}

impl Stylize for String {
    fn stylize(self) -> StyledString {
        StyledString::new(self)
    }
}

/// Removes ANSI escape sequences from a string, returning the plain text.
///
/// This is useful when you need to calculate the visible width of a string
/// that may contain color or style codes (e.g. for aligning columns).
///
/// # Examples
///
/// ```
/// use blazer::style::strip_ansi;
/// use blazer::Stylize;
///
/// let styled = "Hello".red().to_string();
/// assert_eq!(strip_ansi(&styled), "Hello");
/// ```
pub fn strip_ansi(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\x1b' {
            if let Some('[') = chars.peek() {
                chars.next();
                for next in chars.by_ref() {
                    if next.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
        } else {
            result.push(c);
        }
    }

    result
}

/// Parses a string containing nested markup and returns a vector of [`StyledString`] objects.
pub fn parse_styled_components(input: &str) -> Vec<StyledString> {
    use crate::Stylize;

    let mut segments = Vec::new();
    let mut chars = input.chars().peekable();
    let mut style_stack: Vec<String> = Vec::new();

    while let Some(c) = chars.next() {
        if c == '[' {
            let mut tag = String::new();
            while let Some(&next_c) = chars.peek() {
                chars.next();
                if next_c == ']' {
                    break;
                }
                tag.push(next_c);
            }
            if tag == "/" || tag == format!("/{}", style_stack.last().unwrap_or(&" ".to_string()))  {
                style_stack.pop();
            } else {
                style_stack.push(tag);
            }
        } else {
            let mut text = String::new();
            text.push(c);
            while let Some(&next_c) = chars.peek() {
                if next_c == '[' {
                    break;
                }
                text.push(chars.next().unwrap());
            }

            let mut styled = text.stylize();

            for style_tag in &style_stack {
                styled = match style_tag.as_str() {
                    "black" => styled.black(),
                    "red" => styled.red(),
                    "green" => styled.green(),
                    "yellow" => styled.yellow(),
                    "blue" => styled.blue(),
                    "magenta" => styled.magenta(),
                    "cyan" => styled.cyan(),
                    "white" => styled.white(),
                    "bright_black" => styled.bright_black(),
                    "bright_red" => styled.bright_red(),
                    "bright_green" => styled.bright_green(),
                    "bright_yellow" => styled.bright_yellow(),
                    "bright_blue" => styled.bright_blue(),
                    "bright_magenta" => styled.bright_magenta(),
                    "bright_cyan" => styled.bright_cyan(),
                    "bright_white" => styled.bright_white(),

                    "on_black" => styled.on_black(),
                    "on_red" => styled.on_red(),
                    "on_green" => styled.on_green(),
                    "on_yellow" => styled.on_yellow(),
                    "on_blue" => styled.on_blue(),
                    "on_magenta" => styled.on_magenta(),
                    "on_cyan" => styled.on_cyan(),
                    "on_white" => styled.on_white(),
                    "on_bright_black" => styled.on_bright_black(),
                    "on_bright_red" => styled.on_bright_red(),
                    "on_bright_green" => styled.on_bright_green(),
                    "on_bright_yellow" => styled.on_bright_yellow(),
                    "on_bright_blue" => styled.on_bright_blue(),
                    "on_bright_magenta" => styled.on_bright_magenta(),
                    "on_bright_cyan" => styled.on_bright_cyan(),
                    "on_bright_white" => styled.on_bright_white(),

                    "bold" => styled.bold(),
                    "dim" => styled.dim(),
                    "italic" => styled.italic(),
                    "underline" => styled.underline(),
                    "blink" => styled.blink(),
                    "reverse" => styled.reverse(),
                    "hidden" => styled.hidden(),
                    "strikethrough" => styled.strikethrough(),
                    _ => styled,
                };
            }

            segments.push(styled);
        }
    }

    segments
}

/// Renders a vector of [`StyledString`] objects into a single string.
pub fn render_styled_components(styled: Vec<StyledString>) -> String {
    styled.iter().render()
}

/// Parses a string containing inline markup and returns a rendered string.
pub fn parse_styled(input: &str) -> String {
    render_styled_components(parse_styled_components(input))
}

/// Extension trait for iterators yielding [`StyledString`] references,
/// allowing them to be concatenated into a single rendered string.
pub trait Renderable {
    /// Renders and concatenates all styled strings in the iterator into one.
    fn render(self) -> String;
}

impl<'a, I> Renderable for I
where
    I: Iterator<Item = &'a StyledString>,
{
    fn render(self) -> String {
        self.map(ToString::to_string).collect()
    }
}

/// A macro for styling strings using inline markup tags.
///
/// Supports format string interpolation just like `format!`.
///
/// # Examples
///
/// ```
/// use blazer::style;
///
/// let name = "Alice";
/// let msg = style!("[red]Hello [underline]in style to [/][/][blue]{}[/]", name);
/// ```
#[macro_export]
macro_rules! style {
    ($($arg:tt)*) => {
        $crate::style::parse_styled(&format!($($arg)*))
    };
}

/// A macro for styling strings using inline markup tags and printing them to standard output.
/// Paint prints the styled string and then resets the style without adding a new line.
///
/// Supports format string interpolation just like `format!`.
/// Uses the same inline markup tags as `style!`.
///
///
/// # Examples
///
/// ```
/// use blazer::paint;
///
/// let name = "Alice";
/// let msg = paint!("[red]Hello, [bold]{}[/][/]", name);
/// ```
#[macro_export]
macro_rules! paint {
    ($($arg:tt)*) => {
        print!("\x1b[0m{}", $crate::style!($($arg)*))
    };
}

/// A macro for styling strings using a shorthand idiomatic syntax and printing them to standard output.
/// Paintln prints the styled string and then resets the style, adding a new line.
///
/// Supports format string interpolation just like `format!`.
/// Uses the same inline markup tags as `style!`.
///
/// # Examples
///
/// ```
/// use blazer::paintln;
///
/// let name = "Alice";
/// let msg = paintln!("[red]Hello, [bold]{}[/][/]", name);
/// ```
#[macro_export]
macro_rules! paintln {
    ($($arg:tt)*) => {
        {
            $crate::paint!($($arg)*);
            std::println!("")
        }
    };
}