cli_prompts/style/
formatting.rs

1use crate::engine::CommandBuffer;
2
3use super::color::Color;
4
5/// Set of text formatting options
6#[derive(Clone, Copy)]
7pub enum FormattingOption {
8    /// Reset the formatting
9    Reset,
10
11    /// Make the text bold
12    Bold,
13
14    /// Make the text italic
15    Italic,
16
17    /// Underline the text
18    Underline,
19
20    /// Cross the text out
21    CrossedOut,
22}
23
24/// Represent the text formatting which includes
25/// - Color of the text
26/// - Color of the background
27/// - Text formatting options
28#[derive(Clone)]
29pub struct Formatting {
30    /// Text color
31    pub foreground_color: Option<Color>,
32
33    /// Background color
34    pub background_color: Option<Color>,
35
36    /// List of formatting options
37    pub text_formatting: Vec<FormattingOption>,
38}
39
40impl Default for Formatting {
41    fn default() -> Self {
42        Formatting {
43            foreground_color: None,
44            background_color: None,
45            text_formatting: vec![],
46        }
47    }
48}
49
50impl Formatting {
51
52    /// Set the text color
53    pub fn foreground_color(mut self, color: Color) -> Self {
54        self.foreground_color = Some(color);
55        self
56    }
57
58    /// Set the background color
59    pub fn background_color(mut self, color: Color) -> Self {
60        self.background_color = Some(color);
61        self
62    }
63
64    /// Make the text bold
65    pub fn bold(mut self) -> Self {
66        self.text_formatting.push(FormattingOption::Bold);
67        self
68    }
69
70    /// Make the text italic
71    pub fn italic(mut self) -> Self {
72        self.text_formatting.push(FormattingOption::Italic);
73        self
74    }
75
76    /// Underline the text
77    pub fn underline(mut self) -> Self {
78        self.text_formatting.push(FormattingOption::Underline);
79        self
80    }
81
82    /// Cross the text out
83    pub fn crossed_out(mut self) -> Self {
84        self.text_formatting.push(FormattingOption::CrossedOut);
85        self
86    }
87
88    /// Reset text formatting (colors and options)
89    pub fn reset() -> Self {
90        let mut f = Self::default();
91        f.text_formatting.push(FormattingOption::Reset);
92        f
93    }
94
95    /// Print the given text using the current formatting to the provided command buffer
96    pub fn print(&self, text: impl Into<String>, cmd_buffer: &mut impl CommandBuffer) {
97        cmd_buffer.set_formatting(self);
98        cmd_buffer.print(&text.into());
99        cmd_buffer.reset_formatting();
100    }
101}