Debian Codegraph @

src/lib.rs

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 //!Coloring terminal so simple, you already know how to do it !
2 //!
3 //! use colored::Colorize;
4 //!
5 //! "this is blue".blue();
6 //! "this is red".red();
7 //! "this is red on blue".red().on_blue();
8 //! "this is also red on blue".on_blue().red();
9 //! "you can use truecolor values too!".truecolor(0, 255, 136);
10 //! "background truecolor also works :)".on_truecolor(135, 28, 167);
11 //! "you can also make bold text".bold();
12 //! println!("{} {} {}", "or use".cyan(), "any".italic().yellow(), "string type".cyan());
13 //! "or change advice. This is red".yellow().blue().red();
14 //! "or clear things up. This is default color and style".red().bold().clear();
15 //! "purple and magenta are the same".purple().magenta();
16 //! "bright colors are also allowed".bright_blue().on_bright_white();
17 //! "you can specify color by string".color("blue").on_color("red");
18 //! "and so are normal and clear".normal().clear();
19 //! String::from("this also works!").green().bold();
20 //! format!("{:30}", "format works as expected. This will be padded".blue());
21 //! format!("{:.3}", "and this will be green but truncated to 3 chars".green());
22 //!
23 //!
24 //! See [the `Colorize` trait](./trait.Colorize.html) for all the methods.
25 //!
26 //! Note: The methods of [`Colorize`], when used on [`str`]'s, return
27 //! [`ColoredString`]'s. See [`ColoredString`] to learn more about them and
28 //! what you can do with them beyond continuing to use [`Colorize`] to further
29 //! modify them.
30 #![warn(missing_docs)]
31
32
33 mod color;
34 pub mod control;
35 mod error;
36 mod style;
37
38 pub use self::customcolors::CustomColor;
39
40 /// Custom colors support.
41 pub mod customcolors;
42
43 pub use color::*;
44
45 use std::{
46 borrow::Cow,
47 error::Error,
48 fmt,
49 ops::{Deref, DerefMut},
50 };
51
52 pub use style::{Style, Styles};
53
54 /// A string that may have color and/or style applied to it.
55 ///
56 /// Commonly created via calling the methods of [`Colorize`] on a &str.
57 /// All methods of [`Colorize`] either create a new `ColoredString` from
58 /// the type called on or modify a callee `ColoredString`. See
59 /// [`Colorize`] for more.
60 ///
61 /// The primary usage of `ColoredString`'s is as a way to take text,
62 /// apply colors and miscellaneous styling to it (such as bold or
63 /// underline), and then use it to create formatted strings that print
64 /// to the console with the special styling applied.
65 ///
66 /// ## Usage
67 ///
68 /// As stated, `ColoredString`'s, once created, can be printed to the
69 /// console with their colors and style or turned into a string
70 /// containing special console codes that has the same effect.
71 /// This is made easy via `ColoredString`'s implementations of
72 /// [`Display`](std::fmt::Display) and [`ToString`] for those purposes
73 /// respectively.
74 ///
75 /// Printing a `ColoredString` with its style is as easy as:
76 ///
77 /// ```
78 /// # use colored::*;
79 /// let cstring: ColoredString = "Bold and Red!".bold().red();
80 /// println!("{}", cstring);
81 /// ```
82 ///
83 /// ## Manipulating the coloring/style of a `ColoredString`
84 ///
85 /// Getting or changing the foreground color, background color, and or
86 /// style of a `ColoredString` is as easy as manually reading / modifying
87 /// the fields of `ColoredString`.
88 ///
89 /// ```
90 /// # use colored::*;
91 /// let mut red_text = "Red".red();
92 /// // Changing color using re-assignment and [`Colorize`]:
93 /// red_text = red_text.blue();
94 /// // Manipulating fields of `ColoredString` in-place:
95 /// red_text.fgcolor = Some(Color::Blue);
96 ///
97 /// let styled_text1 = "Bold".bold();
98 /// let styled_text2 = "Italic".italic();
99 /// let mut styled_text3 = ColoredString::from("Bold and Italic");
100 /// styled_text3.style = styled_text1.style | styled_text2.style;
101 /// ```
102 ///
103 /// ## Modifying the text of a `ColoredString`
104 ///
105 /// Modifying the text is as easy as modifying the `input` field of
106 /// `ColoredString`...
107 ///
108 /// ```
109 /// # use colored::*;
110 /// let mut colored_text = "Magenta".magenta();
111 /// colored_text = colored_text.blue();
112 /// colored_text.input = "Blue".to_string();
113 /// // Note: The above is inefficient and `colored_text.input.replace_range(.., "Blue")` would
114 /// // be more proper. This is just for example.
115 ///
116 /// assert_eq!(&*colored_text, "Blue");
117 /// ```
118 ///
119 /// Notice how this process preserves the coloring and style.
120 #[derive(Clone, Debug, Default, PartialEq, Eq)]
121 #[non_exhaustive]
122 pub struct ColoredString {
123 /// The plain text that will have color and style applied to it.
124 pub input: String,
125
126 /// The color of the text as it will be printed.
127 pub fgcolor: Option<Color>,
128
129 /// The background color (if any). None means that the text will be printed
130 /// without a special background.
131 pub bgcolor: Option<Color>,
132
133 /// Any special styling to be applied to the text (see Styles for a list of
134 /// available options).
135 pub style: style::Style,
136 }
137
138 /// The trait that enables something to be given color.
139 ///
140 /// You can use `colored` effectively simply by importing this trait
141 /// and then using its methods on `String` and `&str`.
142 #[allow(missing_docs)]
143 pub trait Colorize: Sized {
144 // Font Colors
145 fn black(self) -> ColoredString {
146 self.color(Color::Black)
147 }
148 fn red(self) -> ColoredString {
149 self.color(Color::Red)
150 }
151 fn green(self) -> ColoredString {
152 self.color(Color::Green)
153 }
154 fn yellow(self) -> ColoredString {
155 self.color(Color::Yellow)
156 }
157 fn blue(self) -> ColoredString {
158 self.color(Color::Blue)
159 }
160 fn magenta(self) -> ColoredString {
161 self.color(Color::Magenta)
162 }
163 fn purple(self) -> ColoredString {
164 self.color(Color::Magenta)
165 }
166 fn cyan(self) -> ColoredString {
167 self.color(Color::Cyan)
168 }
169 fn white(self) -> ColoredString {
170 self.color(Color::White)
171 }
172 fn bright_black(self) -> ColoredString {
173 self.color(Color::BrightBlack)
174 }
175 fn bright_red(self) -> ColoredString {
176 self.color(Color::BrightRed)
177 }
178 fn bright_green(self) -> ColoredString {
179 self.color(Color::BrightGreen)
180 }
181 fn bright_yellow(self) -> ColoredString {
182 self.color(Color::BrightYellow)
183 }
184 fn bright_blue(self) -> ColoredString {
185 self.color(Color::BrightBlue)
186 }
187 fn bright_magenta(self) -> ColoredString {
188 self.color(Color::BrightMagenta)
189 }
190 fn bright_purple(self) -> ColoredString {
191 self.color(Color::BrightMagenta)
192 }
193 fn bright_cyan(self) -> ColoredString {
194 self.color(Color::BrightCyan)
195 }
196 fn bright_white(self) -> ColoredString {
197 self.color(Color::BrightWhite)
198 }
199 fn truecolor(self, r: u8, g: u8, b: u8) -> ColoredString {
200 self.color(Color::TrueColor { r, g, b })
201 }
202 fn custom_color<C: Into<CustomColor>>(self, color: C) -> ColoredString {
203 let color = color.into();
204
205 self.color(Color::TrueColor {
206 r: color.r,
207 g: color.g,
208 b: color.b,
209 })
210 }
211 fn ansi_color<T: Into<u8>>(self, color: T) -> ColoredString {
212 self.color(Color::AnsiColor(color.into()))
213 }
214 fn color<C: Into<Color>>(self, color: C) -> ColoredString;
215
216 // Background Colors
217 fn on_black(self) -> ColoredString {
218 self.on_color(Color::Black)
219 }
220 fn on_red(self) -> ColoredString {
221 self.on_color(Color::Red)
222 }
223 fn on_green(self) -> ColoredString {
224 self.on_color(Color::Green)
225 }
226 fn on_yellow(self) -> ColoredString {
227 self.on_color(Color::Yellow)
228 }
229 fn on_blue(self) -> ColoredString {
230 self.on_color(Color::Blue)
231 }
232 fn on_magenta(self) -> ColoredString {
233 self.on_color(Color::Magenta)
234 }
235 fn on_purple(self) -> ColoredString {
236 self.on_color(Color::Magenta)
237 }
238 fn on_cyan(self) -> ColoredString {
239 self.on_color(Color::Cyan)
240 }
241 fn on_white(self) -> ColoredString {
242 self.on_color(Color::White)
243 }
244 fn on_bright_black(self) -> ColoredString {
245 self.on_color(Color::BrightBlack)
246 }
247 fn on_bright_red(self) -> ColoredString {
248 self.on_color(Color::BrightRed)
249 }
250 fn on_bright_green(self) -> ColoredString {
251 self.on_color(Color::BrightGreen)
252 }
253 fn on_bright_yellow(self) -> ColoredString {
254 self.on_color(Color::BrightYellow)
255 }
256 fn on_bright_blue(self) -> ColoredString {
257 self.on_color(Color::BrightBlue)
258 }
259 fn on_bright_magenta(self) -> ColoredString {
260 self.on_color(Color::BrightMagenta)
261 }
262 fn on_bright_purple(self) -> ColoredString {
263 self.on_color(Color::BrightMagenta)
264 }
265 fn on_bright_cyan(self) -> ColoredString {
266 self.on_color(Color::BrightCyan)
267 }
268 fn on_bright_white(self) -> ColoredString {
269 self.on_color(Color::BrightWhite)
270 }
271 fn on_truecolor(self, r: u8, g: u8, b: u8) -> ColoredString {
272 self.on_color(Color::TrueColor { r, g, b })
273 }
274 fn on_custom_color<C: Into<CustomColor>>(self, color: C) -> ColoredString {
275 let color = color.into();
276
277 self.on_color(Color::TrueColor {
278 r: color.r,
279 g: color.g,
280 b: color.b,
281 })
282 }
283 fn on_ansi_color<T: Into<u8>>(self, color: T) -> ColoredString {
284 self.on_color(Color::AnsiColor(color.into()))
285 }
286 fn on_color<C: Into<Color>>(self, color: C) -> ColoredString;
287
288 // Styles
289 fn clear(self) -> ColoredString;
290 fn normal(self) -> ColoredString;
291 fn bold(self) -> ColoredString;
292 fn dimmed(self) -> ColoredString;
293 fn italic(self) -> ColoredString;
294 fn underline(self) -> ColoredString;
295 fn blink(self) -> ColoredString;
296 #[deprecated(since = "1.5.2", note = "Users should use reversed instead")]
297 fn reverse(self) -> ColoredString;
298 fn reversed(self) -> ColoredString;
299 fn hidden(self) -> ColoredString;
300 fn strikethrough(self) -> ColoredString;
301 }
302
303 impl ColoredString {
304 /// Get the current background color applied.
305 ///
306 /// ```rust
307 /// # use colored::*;
308 /// let cstr = "".blue();
309 /// assert_eq!(cstr.fgcolor(), Some(Color::Blue));
310 /// let cstr = cstr.clear();
311 /// assert_eq!(cstr.fgcolor(), None);
312 /// ```
313 #[deprecated(note = "Deprecated due to the exposing of the fgcolor struct field.")]
314 #[must_use]
315 pub fn fgcolor(&self) -> Option<Color> {
316 self.fgcolor.as_ref().copied()
317 }
318
319 /// Get the current background color applied.
320 ///
321 /// ```rust
322 /// # use colored::*;
323 /// let cstr = "".on_blue();
324 /// assert_eq!(cstr.bgcolor(), Some(Color::Blue));
325 /// let cstr = cstr.clear();
326 /// assert_eq!(cstr.bgcolor(), None);
327 /// ```
328 #[deprecated(note = "Deprecated due to the exposing of the bgcolor struct field.")]
329 #[must_use]
330 pub fn bgcolor(&self) -> Option<Color> {
331 self.bgcolor.as_ref().copied()
332 }
333
334 /// Get the current [`Style`] which can be check if it contains a [`Styles`].
335 ///
336 /// ```rust
337 /// # use colored::*;
338 /// let colored = "".bold().italic();
339 /// assert_eq!(colored.style().contains(Styles::Bold), true);
340 /// assert_eq!(colored.style().contains(Styles::Italic), true);
341 /// assert_eq!(colored.style().contains(Styles::Dimmed), false);
342 /// ```
343 #[deprecated(note = "Deprecated due to the exposing of the style struct field.")]
344 #[must_use]
345 pub fn style(&self) -> style::Style {
346 self.style
347 }
348
349 /// Clears foreground coloring on this `ColoredString`, meaning that it
350 /// will be printed with the default terminal text color.
351 pub fn clear_fgcolor(&mut self) {
352 self.fgcolor = None;
353 }
354
355 /// Gets rid of this `ColoredString`'s background.
356 pub fn clear_bgcolor(&mut self) {
357 self.bgcolor = None;
358 }
359
360 /// Clears any special styling and sets it back to the default (plain,
361 /// maybe colored, text).
362 pub fn clear_style(&mut self) {
363 self.style = Style::default();
364 }
365
366 /// Checks if the colored string has no color or styling.
367 ///
368 /// ```rust
369 /// # use colored::*;
370 /// let cstr = "".red();
371 /// assert_eq!(cstr.is_plain(), false);
372 /// let cstr = cstr.clear();
373 /// assert_eq!(cstr.is_plain(), true);
374 /// ```
375 #[must_use]
376 pub fn is_plain(&self) -> bool {
377 self.bgcolor.is_none() && self.fgcolor.is_none() && self.style == style::CLEAR
378 }
379
380 #[cfg(not(feature = "no-color"))]
381 fn has_colors() -> bool {
382 control::SHOULD_COLORIZE.should_colorize()
383 }
384
385 #[cfg(feature = "no-color")]
386 const fn has_colors() -> bool {
387 false
388 }
389
390 fn compute_style(&self) -> String {
391 if !Self::has_colors() || self.is_plain() {
392 return String::new();
393 }
394
395 let mut res = String::from("\x1B[");
396 let mut has_written = if self.style == style::CLEAR {
397 false
398 } else {
399 res.push_str(&self.style.to_str());
400 true
401 };
402
403 if let Some(bgcolor) = &self.bgcolor {
404 if has_written {
405 res.push(';');
406 }
407
408 res.push_str(&bgcolor.to_bg_str());
409 has_written = true;
410 }
411
412 if let Some(fgcolor) = &self.fgcolor {
413 if has_written {
414 res.push(';');
415 }
416
417 res.push_str(&fgcolor.to_fg_str());
418 }
419
420 res.push('m');
421 res
422 }
423
424 fn escape_inner_reset_sequences(&self) -> Cow<'_, str> {
425 if !Self::has_colors() || self.is_plain() {
426 return self.input.as_str().into();
427 }
428
429 // TODO: BoyScoutRule
430 let reset = "\x1B[0m";
431 let style = self.compute_style();
432 let matches: Vec<usize> = self
433 .input
434 .match_indices(reset)
435 .map(|(idx, _)| idx)
436 .collect();
437 if matches.is_empty() {
438 return self.input.as_str().into();
439 }
440
441 let mut input = self.input.clone();
442 input.reserve(matches.len() * style.len());
443
444 for (idx_in_matches, offset) in matches.into_iter().enumerate() {
445 // shift the offset to the end of the reset sequence and take in account
446 // the number of matches we have escaped (which shift the index to insert)
447 let mut offset = offset + reset.len() + idx_in_matches * style.len();
448
449 for cchar in style.chars() {
450 input.insert(offset, cchar);
451 offset += 1;
452 }
453 }
454
455 input.into()
456 }
457 }
458
459 impl Deref for ColoredString {
460 type Target = str;
461 fn deref(&self) -> &Self::Target {
462 &self.input
463 }
464 }
465
466 impl DerefMut for ColoredString {
467 fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
468 &mut self.input
469 }
470 }
471
472 impl From<String> for ColoredString {
473 fn from(s: String) -> Self {
474 Self {
475 input: s,
476 ..Self::default()
477 }
478 }
479 }
480
481 impl<'a> From<&'a str> for ColoredString {
482 fn from(s: &'a str) -> Self {
483 Self {
484 input: String::from(s),
485 ..Self::default()
486 }
487 }
488 }
489
490 impl Colorize for ColoredString {
491 fn color<S: Into<Color>>(mut self, color: S) -> ColoredString {
492 self.fgcolor = Some(color.into());
493 self
494 }
495 fn on_color<S: Into<Color>>(mut self, color: S) -> ColoredString {
496 self.bgcolor = Some(color.into());
497 self
498 }
499
500 fn clear(self) -> ColoredString {
501 Self {
502 input: self.input,
503 ..Self::default()
504 }
505 }
506 fn normal(self) -> ColoredString {
507 self.clear()
508 }
509 fn bold(mut self) -> ColoredString {
510 self.style.add(style::Styles::Bold);
511 self
512 }
513 fn dimmed(mut self) -> ColoredString {
514 self.style.add(style::Styles::Dimmed);
515 self
516 }
517 fn italic(mut self) -> ColoredString {
518 self.style.add(style::Styles::Italic);
519 self
520 }
521 fn underline(mut self) -> ColoredString {
522 self.style.add(style::Styles::Underline);
523 self
524 }
525 fn blink(mut self) -> ColoredString {
526 self.style.add(style::Styles::Blink);
527 self
528 }
529 fn reverse(self) -> ColoredString {
530 self.reversed()
531 }
532 fn reversed(mut self) -> ColoredString {
533 self.style.add(style::Styles::Reversed);
534 self
535 }
536 fn hidden(mut self) -> ColoredString {
537 self.style.add(style::Styles::Hidden);
538 self
539 }
540 fn strikethrough(mut self) -> ColoredString {
541 self.style.add(style::Styles::Strikethrough);
542 self
543 }
544 }
545
546 impl Colorize for &str {
547 fn color<S: Into<Color>>(self, color: S) -> ColoredString {
548 ColoredString {
549 fgcolor: Some(color.into()),
550 input: String::from(self),
551 ..ColoredString::default()
552 }
553 }
554
555 fn on_color<S: Into<Color>>(self, color: S) -> ColoredString {
556 ColoredString {
557 bgcolor: Some(color.into()),
558 input: String::from(self),
559 ..ColoredString::default()
560 }
561 }
562
563 fn clear(self) -> ColoredString {
564 ColoredString {
565 input: String::from(self),
566 style: style::CLEAR,
567 ..ColoredString::default()
568 }
569 }
570 fn normal(self) -> ColoredString {
571 self.clear()
572 }
573 fn bold(self) -> ColoredString {
574 ColoredString::from(self).bold()
575 }
576 fn dimmed(self) -> ColoredString {
577 ColoredString::from(self).dimmed()
578 }
579 fn italic(self) -> ColoredString {
580 ColoredString::from(self).italic()
581 }
582 fn underline(self) -> ColoredString {
583 ColoredString::from(self).underline()
584 }
585 fn blink(self) -> ColoredString {
586 ColoredString::from(self).blink()
587 }
588 fn reverse(self) -> ColoredString {
589 self.reversed()
590 }
591 fn reversed(self) -> ColoredString {
592 ColoredString::from(self).reversed()
593 }
594 fn hidden(self) -> ColoredString {
595 ColoredString::from(self).hidden()
596 }
597 fn strikethrough(self) -> ColoredString {
598 ColoredString::from(self).strikethrough()
599 }
600 }
601
602 impl fmt::Display for ColoredString {
603 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
604 if !Self::has_colors() || self.is_plain() {
605 return <String as fmt::Display>::fmt(&self.input, f);
606 }
607
608 // XXX: see tests. Useful when nesting colored strings
609 let escaped_input = self.escape_inner_reset_sequences();
610
611 f.write_str(&self.compute_style())?;
612 escaped_input.fmt(f)?;
613 f.write_str("\x1B[0m")?;
614 Ok(())
615 }
616 }
617
618 impl From<ColoredString> for Box<dyn Error> {
619 fn from(cs: ColoredString) -> Self {
620 Box::from(error::ColoredStringError(cs))
621 }
622 }
623
624 #[cfg(test)]
625 mod tests {
626 use super::*;
627 use std::{error::Error, fmt::Write};
•628 use crate::control::set_override;
629
630 #[test]
631 fn formatting() {
632 // respect the formatting. Escape sequence add some padding so >= 40
633 assert!(format!("{:40}", "".blue()).len() >= 40);
634 // both should be truncated to 1 char before coloring
635 assert_eq!(
636 format!("{:1.1}", "toto".blue()).len(),
637 format!("{:1.1}", "1".blue()).len()
638 );
639 }
640
641 #[test]
•642 #[ignore]
643 fn it_works() -> Result<(), Box<dyn Error>> {
644 let mut buf = String::new();
645 let toto = "toto";
646 writeln!(&mut buf, "{}", toto.red())?;
647 writeln!(&mut buf, "{}", String::from(toto).red())?;
648 writeln!(&mut buf, "{}", toto.blue())?;
649
650 writeln!(&mut buf, "blue style ****")?;
651 writeln!(&mut buf, "{}", toto.bold())?;
652 writeln!(&mut buf, "{}", "yeah ! Red bold !".red().bold())?;
653 writeln!(&mut buf, "{}", "yeah ! Yellow bold !".bold().yellow())?;
654 writeln!(&mut buf, "{}", toto.bold().blue())?;
655 writeln!(&mut buf, "{}", toto.blue().bold())?;
656 writeln!(&mut buf, "{}", toto.blue().bold().underline())?;
657 writeln!(&mut buf, "{}", toto.blue().italic())?;
658 writeln!(&mut buf, "******")?;
659 writeln!(&mut buf, "test clearing")?;
660 writeln!(&mut buf, "{}", "red cleared".red().clear())?;
661 writeln!(&mut buf, "{}", "bold cyan cleared".bold().cyan().clear())?;
662 writeln!(&mut buf, "******")?;
663 writeln!(&mut buf, "Bg tests")?;
664 writeln!(&mut buf, "{}", toto.green().on_blue())?;
665 writeln!(&mut buf, "{}", toto.on_magenta().yellow())?;
666 writeln!(&mut buf, "{}", toto.purple().on_yellow())?;
667 writeln!(&mut buf, "{}", toto.magenta().on_white())?;
668 writeln!(&mut buf, "{}", toto.cyan().on_green())?;
669 writeln!(&mut buf, "{}", toto.black().on_white())?;
670 writeln!(&mut buf, "******")?;
671 writeln!(&mut buf, "{}", toto.green())?;
672 writeln!(&mut buf, "{}", toto.yellow())?;
673 writeln!(&mut buf, "{}", toto.purple())?;
674 writeln!(&mut buf, "{}", toto.magenta())?;
675 writeln!(&mut buf, "{}", toto.cyan())?;
676 writeln!(&mut buf, "{}", toto.white())?;
677 writeln!(&mut buf, "{}", toto.white().red().blue().green())?;
678 writeln!(&mut buf, "{}", toto.truecolor(255, 0, 0))?;
679 writeln!(&mut buf, "{}", toto.truecolor(255, 255, 0))?;
680 writeln!(&mut buf, "{}", toto.on_truecolor(0, 80, 80))?;
681 writeln!(&mut buf, "{}", toto.custom_color((255, 255, 0)))?;
682 writeln!(&mut buf, "{}", toto.on_custom_color((0, 80, 80)))?;
683 #[cfg(feature = "no-color")]
684 insta::assert_snapshot!("it_works_no_color", buf);
685 #[cfg(not(feature = "no-color"))]
686 insta::assert_snapshot!("it_works", buf);
687 Ok(())
688 }
689
690 #[test]
691 fn compute_style_empty_string() {
692 assert_eq!("", "".clear().compute_style());
693 }
694
695 #[cfg_attr(feature = "no-color", ignore)]
696 #[test]
697 fn compute_style_simple_fg_blue() {
698 let blue = "\x1B[34m";
699
•700 set_override(true);
701 assert_eq!(blue, "".blue().compute_style());
702 }
703
704 #[cfg_attr(feature = "no-color", ignore)]
705 #[test]
706 fn compute_style_simple_bg_blue() {
707 let on_blue = "\x1B[44m";
708
•709 set_override(true);
710 assert_eq!(on_blue, "".on_blue().compute_style());
711 }
712
713 #[cfg_attr(feature = "no-color", ignore)]
714 #[test]
715 fn compute_style_blue_on_blue() {
716 let blue_on_blue = "\x1B[44;34m";
•717 set_override(true);
718 assert_eq!(blue_on_blue, "".blue().on_blue().compute_style());
719 }
720
721 #[cfg_attr(feature = "no-color", ignore)]
722 #[test]
723 fn compute_style_simple_fg_bright_blue() {
724 let blue = "\x1B[94m";
725
•726 set_override(true);
727 assert_eq!(blue, "".bright_blue().compute_style());
728 }
729
730 #[cfg_attr(feature = "no-color", ignore)]
731 #[test]
732 fn compute_style_simple_bg_bright_blue() {
733 let on_blue = "\x1B[104m";
734
•735 set_override(true);
736 assert_eq!(on_blue, "".on_bright_blue().compute_style());
737 }
738
739 #[cfg_attr(feature = "no-color", ignore)]
740 #[test]
741 fn compute_style_bright_blue_on_bright_blue() {
742 let blue_on_blue = "\x1B[104;94m";
743
•744 set_override(true);
745 assert_eq!(
746 blue_on_blue,
747 "".bright_blue().on_bright_blue().compute_style()
748 );
749 }
750
751 #[cfg_attr(feature = "no-color", ignore)]
752 #[test]
753 fn compute_style_simple_bold() {
754 let bold = "\x1B[1m";
755
•756 set_override(true);
757 assert_eq!(bold, "".bold().compute_style());
758 }
759
760 #[cfg_attr(feature = "no-color", ignore)]
761 #[test]
762 fn compute_style_blue_bold() {
763 let blue_bold = "\x1B[1;34m";
•764 set_override(true);
765 assert_eq!(blue_bold, "".blue().bold().compute_style());
766 }
767
768 #[cfg_attr(feature = "no-color", ignore)]
769 #[test]
770 fn compute_style_blue_bold_on_blue() {
771 let blue_bold_on_blue = "\x1B[1;44;34m";
772
•773 set_override(true);
774 assert_eq!(
775 blue_bold_on_blue,
776 "".blue().bold().on_blue().compute_style()
777 );
778 }
779
780 #[test]
781 fn escape_reset_sequence_spec_should_do_nothing_on_empty_strings() {
782 let style = ColoredString::default();
783 let expected = String::new();
784
785 let output = style.escape_inner_reset_sequences();
786
787 assert_eq!(expected, output);
788 }
789
790 #[test]
791 fn escape_reset_sequence_spec_should_do_nothing_on_string_with_no_reset() {
792 let style = ColoredString {
793 input: String::from("hello world !"),
794 ..ColoredString::default()
795 };
796
797 let expected = String::from("hello world !");
798 let output = style.escape_inner_reset_sequences();
799
800 assert_eq!(expected, output);
801 }
802
803 #[cfg_attr(feature = "no-color", ignore)]
804 #[test]
805 fn escape_reset_sequence_spec_should_replace_inner_reset_sequence_with_current_style() {
806 let input = format!("start {} end", String::from("hello world !").red());
807 let style = input.blue();
808
•809 set_override(true);
810 let output = style.escape_inner_reset_sequences();
811 let blue = "\x1B[34m";
812 let red = "\x1B[31m";
813 let reset = "\x1B[0m";
814 let expected = format!("start {red}hello world !{reset}{blue} end");
815 assert_eq!(expected, output);
816 }
817
818 #[cfg_attr(feature = "no-color", ignore)]
819 #[test]
820 fn escape_reset_sequence_spec_should_replace_multiple_inner_reset_sequences_with_current_style()
821 {
822 let italic_str = String::from("yo").italic();
823 let input = format!("start 1:{italic_str} 2:{italic_str} 3:{italic_str} end");
824 let style = input.blue();
825
•826 set_override(true);
827 let output = style.escape_inner_reset_sequences();
828 let blue = "\x1B[34m";
829 let italic = "\x1B[3m";
830 let reset = "\x1B[0m";
831 let expected = format!(
832 "start 1:{italic}yo{reset}{blue} 2:{italic}yo{reset}{blue} 3:{italic}yo{reset}{blue} end"
833 );
834
835 println!("first: {expected}\nsecond: {output}");
836
837 assert_eq!(expected, output);
838 }
839
840 #[test]
841 fn color_fn() {
842 assert_eq!("blue".blue(), "blue".color("blue"));
843 }
844
845 #[test]
846 fn on_color_fn() {
847 assert_eq!("blue".on_blue(), "blue".on_color("blue"));
848 }
849
850 #[test]
851 fn bright_color_fn() {
852 assert_eq!("blue".bright_blue(), "blue".color("bright blue"));
853 }
854
855 #[test]
856 fn on_bright_color_fn() {
857 assert_eq!("blue".on_bright_blue(), "blue".on_color("bright blue"));
858 }
859
860 #[test]
861 fn exposing_tests() {
862 #![allow(deprecated)]
863
864 let cstring = "".red();
865 assert_eq!(cstring.fgcolor(), Some(Color::Red));
866 assert_eq!(cstring.bgcolor(), None);
867
868 let cstring = cstring.clear();
869 assert_eq!(cstring.fgcolor(), None);
870 assert_eq!(cstring.bgcolor(), None);
871
872 let cstring = cstring.blue().on_bright_yellow();
873 assert_eq!(cstring.fgcolor(), Some(Color::Blue));
874 assert_eq!(cstring.bgcolor(), Some(Color::BrightYellow));
875
876 let cstring = cstring.bold().italic();
877 assert_eq!(cstring.fgcolor(), Some(Color::Blue));
878 assert_eq!(cstring.bgcolor(), Some(Color::BrightYellow));
879 assert!(cstring.style().contains(Styles::Bold));
880 assert!(cstring.style().contains(Styles::Italic));
881 assert!(!cstring.style().contains(Styles::Dimmed));
882 }
883 }