ansi-style 1.2.1

ANSI escape codes for styling strings in the terminal
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! # ansi-style
//!
//! ## Usage
//!
//! ```rust
//! use ansi_style::{Color, Style};
//!
//! // You can either color the text directly with the Color enumeration
//! println!(
//!     "{}Cyan colored \"Hello World!\"{}",
//!     Color::Cyan.open(),
//!     Color::Cyan.close()
//! );
//!
//! // or you can use the builder function from within the Style stuct
//! // to create a style that can be used for more than one instance of
//! // a string and you wouldn't need to have an open and close function
//! // prepended and appended to every text you type like the above example
//!
//! let style = Style::builder().red().strikethrough().build();
//!
//! println!(
//!     "{}",
//!     style.stylize("Hello World in red with strikethrough")
//! )
//! ```

#![no_std]

extern crate alloc;

use core::fmt::Display;

use alloc::{format, string::String};

/// A helper struct for creating the [`Style`] object
pub struct StyleBuilder {
    bold: bool,
    dim: bool,
    italic: bool,
    underline: bool,
    blink: bool,
    inverse: bool,
    hidden: bool,
    strikethrough: bool,
    overline: bool,
    color: Option<Color>,
    bg_color: Option<BGColor>,
}

impl StyleBuilder {
    /// Creates a new [`StyleBuilder`] struct for creating styles
    #[must_use]
    pub fn new() -> Self {
        Self {
            bold: false,
            dim: false,
            italic: false,
            underline: false,
            blink: false,
            inverse: false,
            hidden: false,
            strikethrough: false,
            overline: false,
            color: None,
            bg_color: None,
        }
    }

    /// Sets the `bold` property to true
    #[must_use]
    pub fn bold(mut self) -> Self {
        self.bold = true;
        self
    }

    /// Sets the `dim` property to true
    #[must_use]
    pub fn dim(mut self) -> Self {
        self.dim = true;
        self
    }

    /// Sets the `italic` property to true
    #[must_use]
    pub fn italic(mut self) -> Self {
        self.italic = true;
        self
    }

    /// Sets the `underline` property to true
    #[must_use]
    pub fn underline(mut self) -> Self {
        self.underline = true;
        self
    }

    /// Sets the `blink` property to true
    #[must_use]
    pub fn blink(mut self) -> Self {
        self.blink = true;
        self
    }

    /// Sets the `inverse` property to true
    #[must_use]
    pub fn inverse(mut self) -> Self {
        self.inverse = true;
        self
    }

    /// Sets the `hidden` property to true
    #[must_use]
    pub fn hidden(mut self) -> Self {
        self.hidden = true;
        self
    }

    /// Sets the `strikethrough` property to true
    #[must_use]
    pub fn strikethrough(mut self) -> Self {
        self.strikethrough = true;
        self
    }

    /// Sets the `overline` property to true
    #[must_use]
    pub fn overline(mut self) -> Self {
        self.overline = true;
        self
    }

    /// Sets the text color to black
    #[must_use]
    pub fn black(mut self) -> Self {
        self.color = Some(Color::Black);
        self
    }

    /// Sets the text color to red
    #[must_use]
    pub fn red(mut self) -> Self {
        self.color = Some(Color::Red);
        self
    }

    /// Sets the text color to green
    #[must_use]
    pub fn green(mut self) -> Self {
        self.color = Some(Color::Green);
        self
    }

    /// Sets the text color to yellow
    #[must_use]
    pub fn yellow(mut self) -> Self {
        self.color = Some(Color::Yellow);
        self
    }

    /// Sets the text color to blue
    #[must_use]
    pub fn blue(mut self) -> Self {
        self.color = Some(Color::Blue);
        self
    }

    /// Sets the text color to magenta
    #[must_use]
    pub fn magenta(mut self) -> Self {
        self.color = Some(Color::Magenta);
        self
    }

    /// Sets the text color to cyan
    #[must_use]
    pub fn cyan(mut self) -> Self {
        self.color = Some(Color::Cyan);
        self
    }

    /// Sets the text color to white
    #[must_use]
    pub fn white(mut self) -> Self {
        self.color = Some(Color::White);
        self
    }

    /// Sets the text color to a bright black (gray)
    #[must_use]
    pub fn black_bright(mut self) -> Self {
        self.color = Some(Color::BlackBright);
        self
    }

    /// Sets the text color to a bright red
    #[must_use]
    pub fn red_bright(mut self) -> Self {
        self.color = Some(Color::RedBright);
        self
    }

    /// Sets the text color to a bright green
    #[must_use]
    pub fn green_bright(mut self) -> Self {
        self.color = Some(Color::GreenBright);
        self
    }

    /// Sets the text color to a bright yellow
    #[must_use]
    pub fn yellow_bright(mut self) -> Self {
        self.color = Some(Color::YellowBright);
        self
    }

    /// Sets the text color to a bright blue
    #[must_use]
    pub fn blue_bright(mut self) -> Self {
        self.color = Some(Color::BlueBright);
        self
    }

    /// Sets the text color to a bright magenta
    #[must_use]
    pub fn magenta_bright(mut self) -> Self {
        self.color = Some(Color::MagentaBright);
        self
    }

    /// Sets the text color to a bright cyan
    #[must_use]
    pub fn cyan_bright(mut self) -> Self {
        self.color = Some(Color::CyanBright);
        self
    }

    /// Sets the text color to a bright white
    #[must_use]
    pub fn white_bright(mut self) -> Self {
        self.color = Some(Color::WhiteBright);
        self
    }

    /// Sets the text's bckground color to black
    #[must_use]
    pub fn bg_black(mut self) -> Self {
        self.bg_color = Some(BGColor::Black);
        self
    }

    /// Sets the text's bckground color to red
    #[must_use]
    pub fn bg_red(mut self) -> Self {
        self.bg_color = Some(BGColor::Red);
        self
    }

    /// Sets the text's bckground color to green
    #[must_use]
    pub fn bg_green(mut self) -> Self {
        self.bg_color = Some(BGColor::Green);
        self
    }

    /// Sets the text's bckground color to yellow
    #[must_use]
    pub fn bg_yellow(mut self) -> Self {
        self.bg_color = Some(BGColor::Yellow);
        self
    }

    /// Sets the text's bckground color to blue
    #[must_use]
    pub fn bg_blue(mut self) -> Self {
        self.bg_color = Some(BGColor::Blue);
        self
    }

    /// Sets the text's bckground color to magenta
    #[must_use]
    pub fn bg_magenta(mut self) -> Self {
        self.bg_color = Some(BGColor::Magenta);
        self
    }

    /// Sets the text's bckground color to cyan
    #[must_use]
    pub fn bg_cyan(mut self) -> Self {
        self.bg_color = Some(BGColor::Cyan);
        self
    }

    /// Sets the text's bckground color to white
    #[must_use]
    pub fn bg_white(mut self) -> Self {
        self.bg_color = Some(BGColor::White);
        self
    }

    /// Sets the text's bckground color to a bright black (gray)
    #[must_use]
    pub fn bg_black_bright(mut self) -> Self {
        self.bg_color = Some(BGColor::BlackBright);
        self
    }

    /// Sets the text's bckground color to a bright red
    #[must_use]
    pub fn bg_red_bright(mut self) -> Self {
        self.bg_color = Some(BGColor::RedBright);
        self
    }

    /// Sets the text's bckground color to a bright green
    #[must_use]
    pub fn bg_green_bright(mut self) -> Self {
        self.bg_color = Some(BGColor::GreenBright);
        self
    }

    /// Sets the text's bckground color to a bright yellow
    #[must_use]
    pub fn bg_yellow_bright(mut self) -> Self {
        self.bg_color = Some(BGColor::YellowBright);
        self
    }

    /// Sets the text's bckground color to a bright blue
    #[must_use]
    pub fn bg_blue_bright(mut self) -> Self {
        self.bg_color = Some(BGColor::BlueBright);
        self
    }

    /// Sets the text's bckground color to a bright magenta
    #[must_use]
    pub fn bg_magenta_bright(mut self) -> Self {
        self.bg_color = Some(BGColor::MagentaBright);
        self
    }

    /// Sets the text's bckground color to a bright cyan
    #[must_use]
    pub fn bg_cyan_bright(mut self) -> Self {
        self.bg_color = Some(BGColor::CyanBright);
        self
    }

    /// Sets the text's bckground color to a bright white
    #[must_use]
    pub fn bg_white_bright(mut self) -> Self {
        self.bg_color = Some(BGColor::WhiteBright);
        self
    }

    /// Builds a [`Style`] struct from a the current instance of
    /// the [`StyleBuilder`] struct
    #[must_use]
    pub fn build(self) -> Style {
        let StyleBuilder {
            bold,
            dim,
            italic,
            underline,
            blink,
            inverse,
            hidden,
            strikethrough,
            overline,
            color,
            bg_color,
        } = self;

        Style {
            bold,
            dim,
            italic,
            underline,
            blink,
            inverse,
            hidden,
            strikethrough,
            overline,
            color,
            bg_color,
        }
    }
}

impl Default for StyleBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// A  collection of properties that can be used to format a string using ANSI escape codes.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct Style {
    bold: bool,
    dim: bool,
    italic: bool,
    underline: bool,
    blink: bool,
    inverse: bool,
    hidden: bool,
    strikethrough: bool,
    overline: bool,
    color: Option<Color>,
    bg_color: Option<BGColor>,
}

impl Style {
    /// Creates a new [`Style`] struct
    #[must_use]
    pub fn new() -> Self {
        Self {
            bold: false,
            dim: false,
            italic: false,
            underline: false,
            blink: false,
            inverse: false,
            hidden: false,
            strikethrough: false,
            overline: false,
            color: None,
            bg_color: None,
        }
    }

    /// Creates a new [`StyleBuilder`] struct
    #[must_use]
    pub fn builder() -> StyleBuilder {
        StyleBuilder::new()
    }

    /// Checks whether or not the text's style is bold
    #[must_use]
    pub fn bold(&self) -> bool {
        self.bold
    }

    /// Checks whether or not the text's style is dim
    #[must_use]
    pub fn dim(&self) -> bool {
        self.dim
    }

    /// Checks whether or not the text's style is italic
    #[must_use]
    pub fn italic(&self) -> bool {
        self.italic
    }

    /// Checks whether or not the text's style is underline
    #[must_use]
    pub fn underline(&self) -> bool {
        self.underline
    }

    /// Checks whether or not the text's style is blink
    #[must_use]
    pub fn blink(&self) -> bool {
        self.blink
    }

    /// Checks whether or not the text's style is inverse
    #[must_use]
    pub fn inverse(&self) -> bool {
        self.inverse
    }

    /// Checks whether or not the text's style is hidden
    #[must_use]
    pub fn hidden(&self) -> bool {
        self.hidden
    }

    /// Checks whether or not the text's style is strikethrough
    #[must_use]
    pub fn strikethrough(&self) -> bool {
        self.strikethrough
    }

    /// Checks whether or not the text's style is overline
    #[must_use]
    pub fn overline(&self) -> bool {
        self.overline
    }

    /// Checks whether oor not the current style has a text color if no color is
    /// provided a default color [`Color::Any`] will be provided
    #[must_use]
    pub fn color(&self) -> Color {
        match self.color {
            Some(color) => color,
            None => Color::Any,
        }
    }

    /// Checks whether oor not the current style has a text background color if no color is
    /// provided a default color [`BGColor::Any`] will be provided
    #[must_use]
    pub fn bg_color(&self) -> BGColor {
        match self.bg_color {
            Some(color) => color,
            None => BGColor::Any,
        }
    }

    /// Converts three values (red, green, blue) to an ansi 256-color lookup (8-bit)
    ///
    /// # Arguments
    ///
    /// * `red` - a number representation for red
    /// * `green` - a number representation for green
    /// * `blue` - a number representation for blue
    #[must_use]
    pub fn rgb_to_ansi256(red: u8, green: u8, blue: u8) -> u8 {
        if red == green && green == blue {
            if red < 8 {
                return 16;
            }

            if red > 248 {
                return 231;
            }

            return ((((red as f32 - 8.) / 247.) * 24.) + 232.) as u8;
        }

        (16. + (36. * (red as f32 / 255. * 5.))
            + (6. * (green as f32 / 255. * 5.))
            + (blue as f32 / 255. * 5.)) as u8
    }

    /// Adds style to a given text
    ///
    /// * `text` - the string of characters to add style to  
    #[must_use]
    pub fn stylize(&self, text: &str) -> String {
        format!("{self}{text}{}", Self::reset())
    }

    fn is_default(&self) -> bool {
        *self == Self::default()
    }

    fn reset() -> &'static str {
        "\x1B[0m"
    }
}

impl Display for Style {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        if self.is_default() {
            return Ok(());
        }

        write!(f, "\x1B[")?;

        let mut written = false;

        {
            let mut write_char = |c| {
                if written {
                    write!(f, ";")?;
                }
                written = true;
                write!(f, "{}", c)?;
                Ok(())
            };

            if self.bold {
                write_char('1')?;
            }

            if self.dim {
                write_char('2')?;
            }

            if self.italic {
                write_char('3')?;
            }

            if self.underline {
                write_char('4')?;
            }

            if self.blink {
                write_char('5')?;
            }

            if self.inverse {
                write_char('7')?;
            }

            if self.hidden {
                write_char('8')?;
            }

            if self.strikethrough {
                write_char('9')?;
            }

            if self.overline {
                write!(f, "53")?;
            }
        }

        if let Some(color) = self.bg_color {
            if written {
                write!(f, ";{color}")?;
            } else {
                write!(f, "{color}")?;
                written = true;
            }
        }

        if let Some(color) = self.color {
            if written {
                write!(f, ";{color}")?;
            } else {
                write!(f, "{color}")?;
            }
        }

        write!(f, "m")
    }
}

impl Default for Style {
    fn default() -> Self {
        Self::new()
    }
}

/// The [`Color`] enumeration can be used to directly add color in ANSI
/// compatible environments without the use of the [`Style`] struct.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub enum Color {
    /// A generic color
    Any,
    /// A black text color
    Black,
    /// A red text color
    Red,
    /// A green text color
    Green,
    /// A yellow text color
    Yellow,
    /// A blue text color
    Blue,
    /// A magenta text color
    Magenta,
    /// A cyan text color
    Cyan,
    /// A white text color
    White,

    /// A bright black (gray) text color
    BlackBright,
    /// A bright red text color
    RedBright,
    /// A bright green text color
    GreenBright,
    /// A bright yellow text color
    YellowBright,
    /// A bright blue text color
    BlueBright,
    /// A bright magenta text color
    MagentaBright,
    /// A bright cyan text color
    CyanBright,
    /// A bright white text color
    WhiteBright,

    /// An 8-bit color from  0 to 255
    Ansi256(u8),
    /// A 24-bit RGB color, as specified by ISO-8613-3.
    RGB(u8, u8, u8),
}

impl Color {
    /// Closes the terminal from adding selected color to text
    #[must_use]
    pub fn close(&self) -> &'static str {
        "\x1B[39m"
    }

    /// Opens the terminal for adding selected color to text
    #[must_use]
    pub fn open(&self) -> String {
        format!("\x1B[{self}m")
    }

    /// Adds color to a given text
    ///
    /// * `text` - the string of characters to add background color to  
    #[must_use]
    pub fn paint(&self, text: &str) -> String {
        format!("{}{text}{}", self.open(), self.close())
    }
}

impl Display for Color {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Color::Any => write!(f, ""),
            Color::Black => write!(f, "30"),
            Color::Red => write!(f, "31"),
            Color::Green => write!(f, "32"),
            Color::Yellow => write!(f, "33"),
            Color::Blue => write!(f, "34"),
            Color::Magenta => write!(f, "35"),
            Color::Cyan => write!(f, "36"),
            Color::White => write!(f, "37"),
            Color::BlackBright => write!(f, "90"),
            Color::RedBright => write!(f, "91"),
            Color::GreenBright => write!(f, "92"),
            Color::YellowBright => write!(f, "93"),
            Color::BlueBright => write!(f, "94"),
            Color::MagentaBright => write!(f, "95"),
            Color::CyanBright => write!(f, "96"),
            Color::WhiteBright => write!(f, "97"),
            Color::Ansi256(num) => write!(f, "38;5;{}", &num),
            Color::RGB(r, g, b) => write!(f, "38;2;{};{};{}", &r, &g, &b),
        }
    }
}

/// The [`BGColor`] enumeration can be used to directly add color in ANSI
/// compatible environments without the use of the [`Style`] struct.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub enum BGColor {
    /// A generic color
    Any,
    /// A black background color
    Black,
    /// A red background color
    Red,
    /// A green background color
    Green,
    /// A yellow background color
    Yellow,
    /// A blue background color
    Blue,
    /// A magenta background color
    Magenta,
    /// A cyan background color
    Cyan,
    /// A white background color
    White,

    /// A bright black (gray) background color
    BlackBright,
    /// A bright red background color
    RedBright,
    /// A bright green background color
    GreenBright,
    /// A bright yellow background color
    YellowBright,
    /// A bright blue background color
    BlueBright,
    /// A bright magenta background color
    MagentaBright,
    /// A bright cyan background color
    CyanBright,
    /// A bright white background color
    WhiteBright,

    /// An 8-bit color from  0 to 255
    Ansi256(u8),
    /// A 24-bit RGB color, as specified by ISO-8613-3.
    RGB(u8, u8, u8),
}

impl BGColor {
    /// Closes the terminal from adding selected color to text's background
    #[must_use]
    pub fn close(&self) -> &'static str {
        "\x1B[49m"
    }

    /// Opens the terminal to adding selected color to text's background
    #[must_use]
    pub fn open(&self) -> String {
        format!("\x1B[{self}m")
    }

    /// Adds background color to a given text
    ///
    /// * `text` - the string of characters to add color to  
    #[must_use]
    pub fn paint(&self, text: &str) -> String {
        format!("{}{text}{}", self.open(), self.close())
    }
}

impl Display for BGColor {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            BGColor::Any => write!(f, ""),
            BGColor::Black => write!(f, "40"),
            BGColor::Red => write!(f, "41"),
            BGColor::Green => write!(f, "42"),
            BGColor::Yellow => write!(f, "43"),
            BGColor::Blue => write!(f, "44"),
            BGColor::Magenta => write!(f, "45"),
            BGColor::Cyan => write!(f, "46"),
            BGColor::White => write!(f, "47"),
            BGColor::BlackBright => write!(f, "100"),
            BGColor::RedBright => write!(f, "101"),
            BGColor::GreenBright => write!(f, "102"),
            BGColor::YellowBright => write!(f, "103"),
            BGColor::BlueBright => write!(f, "104"),
            BGColor::MagentaBright => write!(f, "105"),
            BGColor::CyanBright => write!(f, "106"),
            BGColor::WhiteBright => write!(f, "107"),
            BGColor::Ansi256(num) => write!(f, "48;5;{}", &num),
            BGColor::RGB(r, g, b) => write!(f, "48;2;{};{};{}", &r, &g, &b),
        }
    }
}