[go: up one dir, main page]

Struct Style

Source
pub struct Style {
    pub fg: Option<Color>,
    pub bg: Option<Color>,
    pub underline_color: Option<Color>,
    pub add_modifier: Modifier,
    pub sub_modifier: Modifier,
}
Expand description

Style lets you control the main characteristics of the displayed elements.

use ratatui::style::{Color, Modifier, Style};

Style::default()
    .fg(Color::Black)
    .bg(Color::Green)
    .add_modifier(Modifier::ITALIC | Modifier::BOLD);

Styles can also be created with a shorthand notation.

use ratatui::style::{Style, Stylize};

Style::new().black().on_green().italic().bold();

For more information about the style shorthands, see the Stylize trait.

We implement conversions from Color and Modifier to Style so you can use them anywhere that accepts Into<Style>.

use ratatui::{
    style::{Color, Modifier, Style},
    text::Line,
};

Line::styled("hello", Style::new().fg(Color::Red));
// simplifies to
Line::styled("hello", Color::Red);

Line::styled("hello", Style::new().add_modifier(Modifier::BOLD));
// simplifies to
Line::styled("hello", Modifier::BOLD);

Styles represents an incremental change. If you apply the styles S1, S2, S3 to a cell of the terminal buffer, the style of this cell will be the result of the merge of S1, S2 and S3, not just S3.

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
};

let styles = [
    Style::default()
        .fg(Color::Blue)
        .add_modifier(Modifier::BOLD | Modifier::ITALIC),
    Style::default()
        .bg(Color::Red)
        .add_modifier(Modifier::UNDERLINED),
    #[cfg(feature = "underline-color")]
    Style::default().underline_color(Color::Green),
    Style::default()
        .fg(Color::Yellow)
        .remove_modifier(Modifier::ITALIC),
];
let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
for style in &styles {
    buffer[(0, 0)].set_style(*style);
}
assert_eq!(
    Style {
        fg: Some(Color::Yellow),
        bg: Some(Color::Red),
        #[cfg(feature = "underline-color")]
        underline_color: Some(Color::Green),
        add_modifier: Modifier::BOLD | Modifier::UNDERLINED,
        sub_modifier: Modifier::empty(),
    },
    buffer[(0, 0)].style(),
);

The default implementation returns a Style that does not modify anything. If you wish to reset all properties until that point use Style::reset.

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
};

let styles = [
    Style::default()
        .fg(Color::Blue)
        .add_modifier(Modifier::BOLD | Modifier::ITALIC),
    Style::reset().fg(Color::Yellow),
];
let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
for style in &styles {
    buffer[(0, 0)].set_style(*style);
}
assert_eq!(
    Style {
        fg: Some(Color::Yellow),
        bg: Some(Color::Reset),
        #[cfg(feature = "underline-color")]
        underline_color: Some(Color::Reset),
        add_modifier: Modifier::empty(),
        sub_modifier: Modifier::empty(),
    },
    buffer[(0, 0)].style(),
);

Fields§

§fg: Option<Color>§bg: Option<Color>§underline_color: Option<Color>
Available on crate feature underline-color only.
§add_modifier: Modifier§sub_modifier: Modifier

Implementations§

Source§

impl Style

Source

pub const fn new() -> Self

Examples found in repository?
examples/list.rs (line 34)
34const TODO_HEADER_STYLE: Style = Style::new().fg(SLATE.c100).bg(BLUE.c800);
35const NORMAL_ROW_BG: Color = SLATE.c950;
36const ALT_ROW_BG_COLOR: Color = SLATE.c900;
37const SELECTED_STYLE: Style = Style::new().bg(SLATE.c800).add_modifier(Modifier::BOLD);
More examples
Hide additional examples
examples/barchart.rs (line 135)
132fn temperature_style(value: u8) -> Style {
133    let green = (255.0 * (1.0 - f64::from(value - 50) / 40.0)) as u8;
134    let color = Color::Rgb(255, green, 0);
135    Style::new().fg(color)
136}
examples/block.rs (line 127)
125fn render_styled_borders(paragraph: &Paragraph, frame: &mut Frame, area: Rect) {
126    let block = Block::bordered()
127        .border_style(Style::new().blue().on_white().bold().italic())
128        .title("Styled borders");
129    frame.render_widget(paragraph.clone().block(block), area);
130}
131
132fn render_styled_block(paragraph: &Paragraph, frame: &mut Frame, area: Rect) {
133    let block = Block::bordered()
134        .style(Style::new().blue().on_white().bold().italic())
135        .title("Styled block");
136    frame.render_widget(paragraph.clone().block(block), area);
137}
138
139fn render_styled_title(paragraph: &Paragraph, frame: &mut Frame, area: Rect) {
140    let block = Block::bordered()
141        .title("Styled title")
142        .title_style(Style::new().blue().on_white().bold().italic());
143    frame.render_widget(paragraph.clone().block(block), area);
144}
examples/demo2/tabs/weather.rs (line 68)
66fn render_calendar(area: Rect, buf: &mut Buffer) {
67    let date = OffsetDateTime::now_utc().date();
68    Monthly::new(date, CalendarEventStore::today(Style::new().red().bold()))
69        .block(Block::new().padding(Padding::new(0, 0, 2, 0)))
70        .show_month_header(Style::new().bold())
71        .show_weekdays_header(Style::new().italic())
72        .render(area, buf);
73}
74
75fn render_simple_barchart(area: Rect, buf: &mut Buffer) {
76    let data = [
77        ("Sat", 76),
78        ("Sun", 69),
79        ("Mon", 65),
80        ("Tue", 67),
81        ("Wed", 65),
82        ("Thu", 69),
83        ("Fri", 73),
84    ];
85    let data = data
86        .into_iter()
87        .map(|(label, value)| {
88            Bar::default()
89                .value(value)
90                // This doesn't actually render correctly as the text is too wide for the bar
91                // See https://github.com/ratatui/ratatui/issues/513 for more info
92                // (the demo GIFs hack around this by hacking the calculation in bars.rs)
93                .text_value(format!("{value}°"))
94                .style(if value > 70 {
95                    Style::new().fg(Color::Red)
96                } else {
97                    Style::new().fg(Color::Yellow)
98                })
99                .value_style(if value > 70 {
100                    Style::new().fg(Color::Gray).bg(Color::Red).bold()
101                } else {
102                    Style::new().fg(Color::DarkGray).bg(Color::Yellow).bold()
103                })
104                .label(label.into())
105        })
106        .collect_vec();
107    let group = BarGroup::default().bars(&data);
108    BarChart::default()
109        .data(group)
110        .bar_width(3)
111        .bar_gap(1)
112        .render(area, buf);
113}
114
115fn render_horizontal_barchart(area: Rect, buf: &mut Buffer) {
116    let bg = Color::Rgb(32, 48, 96);
117    let data = [
118        Bar::default().text_value("Winter 37-51".into()).value(51),
119        Bar::default().text_value("Spring 40-65".into()).value(65),
120        Bar::default().text_value("Summer 54-77".into()).value(77),
121        Bar::default()
122            .text_value("Fall 41-71".into())
123            .value(71)
124            .value_style(Style::new().bold()), // current season
125    ];
126    let group = BarGroup::default().label("GPU".into()).bars(&data);
127    BarChart::default()
128        .block(Block::new().padding(Padding::new(0, 0, 2, 0)))
129        .direction(Direction::Horizontal)
130        .data(group)
131        .bar_gap(1)
132        .bar_style(Style::new().fg(bg))
133        .value_style(Style::new().bg(bg).fg(Color::Gray))
134        .render(area, buf);
135}
136
137#[allow(clippy::cast_precision_loss)]
138pub fn render_gauge(progress: usize, area: Rect, buf: &mut Buffer) {
139    let percent = (progress * 3).min(100) as f64;
140
141    render_line_gauge(percent, area, buf);
142}
143
144#[allow(clippy::cast_possible_truncation)]
145fn render_line_gauge(percent: f64, area: Rect, buf: &mut Buffer) {
146    // cycle color hue based on the percent for a neat effect yellow -> red
147    let hue = 90.0 - (percent as f32 * 0.6);
148    let value = Okhsv::max_value();
149    let filled_color = color_from_oklab(hue, Okhsv::max_saturation(), value);
150    let unfilled_color = color_from_oklab(hue, Okhsv::max_saturation(), value * 0.5);
151    let label = if percent < 100.0 {
152        format!("Downloading: {percent}%")
153    } else {
154        "Download Complete!".into()
155    };
156    LineGauge::default()
157        .ratio(percent / 100.0)
158        .label(label)
159        .style(Style::new().light_blue())
160        .filled_style(Style::new().fg(filled_color))
161        .unfilled_style(Style::new().fg(unfilled_color))
162        .line_set(symbols::line::THICK)
163        .render(area, buf);
164}
examples/barchart-grouped.rs (line 196)
189    fn vertical_revenue_bar(&self, revenue: u32) -> Bar {
190        let text_value = format!("{:.1}M", f64::from(revenue) / 1000.);
191        Bar::default()
192            .label(self.short_name.into())
193            .value(u64::from(revenue))
194            .text_value(text_value)
195            .style(self.color)
196            .value_style(Style::new().fg(Color::Black).bg(self.color))
197    }
198
199    /// Create a horizontal revenue bar for the company
200    ///
201    /// The label is the long name of the company combined with the revenue and will be displayed
202    /// on the bar
203    fn horizontal_revenue_bar(&self, revenue: u32) -> Bar {
204        let text_value = format!("{} ({:.1} M)", self.name, f64::from(revenue) / 1000.);
205        Bar::default()
206            .value(u64::from(revenue))
207            .text_value(text_value)
208            .style(self.color)
209            .value_style(Style::new().fg(Color::Black).bg(self.color))
210    }
examples/gauge.rs (line 164)
160    fn render_gauge2(&self, area: Rect, buf: &mut Buffer) {
161        let title = title_block("Gauge with ratio and custom label");
162        let label = Span::styled(
163            format!("{:.1}/100", self.progress2),
164            Style::new().italic().bold().fg(CUSTOM_LABEL_COLOR),
165        );
166        Gauge::default()
167            .block(title)
168            .gauge_style(GAUGE2_COLOR)
169            .ratio(self.progress2 / 100.0)
170            .label(label)
171            .render(area, buf);
172    }
Source

pub const fn reset() -> Self

Returns a Style resetting all properties.

Examples found in repository?
examples/constraint-explorer.rs (line 444)
434    fn render_2px(&self, area: Rect, buf: &mut Buffer) {
435        let lighter_color = ConstraintName::from(self.constraint).lighter_color();
436        let main_color = ConstraintName::from(self.constraint).color();
437        let selected_color = if self.selected {
438            lighter_color
439        } else {
440            main_color
441        };
442        Block::bordered()
443            .border_set(symbols::border::QUADRANT_OUTSIDE)
444            .border_style(Style::reset().fg(selected_color).reversed())
445            .render(area, buf);
446    }
447
448    fn render_4px(&self, area: Rect, buf: &mut Buffer) {
449        let lighter_color = ConstraintName::from(self.constraint).lighter_color();
450        let main_color = ConstraintName::from(self.constraint).color();
451        let selected_color = if self.selected {
452            lighter_color
453        } else {
454            main_color
455        };
456        let color = if self.legend {
457            selected_color
458        } else {
459            main_color
460        };
461        let label = self.label(area.width);
462        let block = Block::bordered()
463            .border_set(symbols::border::QUADRANT_OUTSIDE)
464            .border_style(Style::reset().fg(color).reversed())
465            .fg(Self::TEXT_COLOR)
466            .bg(color);
467        Paragraph::new(label)
468            .centered()
469            .fg(Self::TEXT_COLOR)
470            .bg(color)
471            .block(block)
472            .render(area, buf);
473
474        if !self.legend {
475            let border_color = if self.selected {
476                lighter_color
477            } else {
478                main_color
479            };
480            if let Some(last_row) = area.rows().last() {
481                buf.set_style(last_row, border_color);
482            }
483        }
484    }
More examples
Hide additional examples
examples/layout.rs (line 154)
146fn render_example_combination(
147    frame: &mut Frame,
148    area: Rect,
149    title: &str,
150    constraints: impl ExactSizeIterator<Item = (Constraint, Constraint)>,
151) {
152    let block = Block::bordered()
153        .title(title.gray())
154        .style(Style::reset())
155        .border_style(Style::default().fg(Color::DarkGray));
156    let inner = block.inner(area);
157    frame.render_widget(block, area);
158    let layout = Layout::vertical(vec![Length(1); constraints.len() + 1]).split(inner);
159    for ((a, b), &area) in constraints.into_iter().zip(layout.iter()) {
160        render_single_example(frame, area, vec![a, b, Min(0)]);
161    }
162    // This is to make it easy to visually see the alignment of the examples
163    // with the constraints.
164    frame.render_widget(Paragraph::new("123456789012"), layout[6]);
165}
examples/flex.rs (line 466)
452    fn render_spacer(spacer: Rect, buf: &mut Buffer) {
453        if spacer.width > 1 {
454            let corners_only = symbols::border::Set {
455                top_left: line::NORMAL.top_left,
456                top_right: line::NORMAL.top_right,
457                bottom_left: line::NORMAL.bottom_left,
458                bottom_right: line::NORMAL.bottom_right,
459                vertical_left: " ",
460                vertical_right: " ",
461                horizontal_top: " ",
462                horizontal_bottom: " ",
463            };
464            Block::bordered()
465                .border_set(corners_only)
466                .border_style(Style::reset().dark_gray())
467                .render(spacer, buf);
468        } else {
469            Paragraph::new(Text::from(vec![
470                Line::from(""),
471                Line::from("│"),
472                Line::from("│"),
473                Line::from(""),
474            ]))
475            .style(Style::reset().dark_gray())
476            .render(spacer, buf);
477        }
478        let width = spacer.width;
479        let label = if width > 4 {
480            format!("{width} px")
481        } else if width > 2 {
482            format!("{width}")
483        } else {
484            String::new()
485        };
486        let text = Text::from(vec![
487            Line::raw(""),
488            Line::raw(""),
489            Line::styled(label, Style::reset().dark_gray()),
490        ]);
491        Paragraph::new(text)
492            .style(Style::reset().dark_gray())
493            .alignment(Alignment::Center)
494            .render(spacer, buf);
495    }
496
497    fn illustration(constraint: Constraint, width: u16) -> impl Widget {
498        let main_color = color_for_constraint(constraint);
499        let fg_color = Color::White;
500        let title = format!("{constraint}");
501        let content = format!("{width} px");
502        let text = format!("{title}\n{content}");
503        let block = Block::bordered()
504            .border_set(symbols::border::QUADRANT_OUTSIDE)
505            .border_style(Style::reset().fg(main_color).reversed())
506            .style(Style::default().fg(fg_color).bg(main_color));
507        Paragraph::new(text).centered().block(block)
508    }
Source

pub const fn fg(self, color: Color) -> Self

Changes the foreground color.

§Examples
use ratatui::style::{Color, Style};

let style = Style::default().fg(Color::Blue);
let diff = Style::default().fg(Color::Red);
assert_eq!(style.patch(diff), Style::default().fg(Color::Red));
Examples found in repository?
examples/list.rs (line 34)
34const TODO_HEADER_STYLE: Style = Style::new().fg(SLATE.c100).bg(BLUE.c800);
More examples
Hide additional examples
examples/barchart.rs (line 135)
132fn temperature_style(value: u8) -> Style {
133    let green = (255.0 * (1.0 - f64::from(value - 50) / 40.0)) as u8;
134    let color = Color::Rgb(255, green, 0);
135    Style::new().fg(color)
136}
examples/barchart-grouped.rs (line 196)
189    fn vertical_revenue_bar(&self, revenue: u32) -> Bar {
190        let text_value = format!("{:.1}M", f64::from(revenue) / 1000.);
191        Bar::default()
192            .label(self.short_name.into())
193            .value(u64::from(revenue))
194            .text_value(text_value)
195            .style(self.color)
196            .value_style(Style::new().fg(Color::Black).bg(self.color))
197    }
198
199    /// Create a horizontal revenue bar for the company
200    ///
201    /// The label is the long name of the company combined with the revenue and will be displayed
202    /// on the bar
203    fn horizontal_revenue_bar(&self, revenue: u32) -> Bar {
204        let text_value = format!("{} ({:.1} M)", self.name, f64::from(revenue) / 1000.);
205        Bar::default()
206            .value(u64::from(revenue))
207            .text_value(text_value)
208            .style(self.color)
209            .value_style(Style::new().fg(Color::Black).bg(self.color))
210    }
examples/line_gauge.rs (line 135)
131    fn render_gauge1(&self, area: Rect, buf: &mut Buffer) {
132        let title = title_block("Blue / red only foreground");
133        LineGauge::default()
134            .block(title)
135            .filled_style(Style::default().fg(Color::Blue))
136            .unfilled_style(Style::default().fg(Color::Red))
137            .label("Foreground:")
138            .ratio(self.progress)
139            .render(area, buf);
140    }
141
142    fn render_gauge2(&self, area: Rect, buf: &mut Buffer) {
143        let title = title_block("Blue / red only background");
144        LineGauge::default()
145            .block(title)
146            .filled_style(Style::default().fg(Color::Blue).bg(Color::Blue))
147            .unfilled_style(Style::default().fg(Color::Red).bg(Color::Red))
148            .label("Background:")
149            .ratio(self.progress)
150            .render(area, buf);
151    }
152
153    fn render_gauge3(&self, area: Rect, buf: &mut Buffer) {
154        let title = title_block("Fully styled with background");
155        LineGauge::default()
156            .block(title)
157            .filled_style(
158                Style::default()
159                    .fg(tailwind::BLUE.c400)
160                    .bg(tailwind::BLUE.c600),
161            )
162            .unfilled_style(
163                Style::default()
164                    .fg(tailwind::RED.c400)
165                    .bg(tailwind::RED.c800),
166            )
167            .label("Both:")
168            .ratio(self.progress)
169            .render(area, buf);
170    }
examples/gauge.rs (line 164)
160    fn render_gauge2(&self, area: Rect, buf: &mut Buffer) {
161        let title = title_block("Gauge with ratio and custom label");
162        let label = Span::styled(
163            format!("{:.1}/100", self.progress2),
164            Style::new().italic().bold().fg(CUSTOM_LABEL_COLOR),
165        );
166        Gauge::default()
167            .block(title)
168            .gauge_style(GAUGE2_COLOR)
169            .ratio(self.progress2 / 100.0)
170            .label(label)
171            .render(area, buf);
172    }
examples/constraint-explorer.rs (line 444)
434    fn render_2px(&self, area: Rect, buf: &mut Buffer) {
435        let lighter_color = ConstraintName::from(self.constraint).lighter_color();
436        let main_color = ConstraintName::from(self.constraint).color();
437        let selected_color = if self.selected {
438            lighter_color
439        } else {
440            main_color
441        };
442        Block::bordered()
443            .border_set(symbols::border::QUADRANT_OUTSIDE)
444            .border_style(Style::reset().fg(selected_color).reversed())
445            .render(area, buf);
446    }
447
448    fn render_4px(&self, area: Rect, buf: &mut Buffer) {
449        let lighter_color = ConstraintName::from(self.constraint).lighter_color();
450        let main_color = ConstraintName::from(self.constraint).color();
451        let selected_color = if self.selected {
452            lighter_color
453        } else {
454            main_color
455        };
456        let color = if self.legend {
457            selected_color
458        } else {
459            main_color
460        };
461        let label = self.label(area.width);
462        let block = Block::bordered()
463            .border_set(symbols::border::QUADRANT_OUTSIDE)
464            .border_style(Style::reset().fg(color).reversed())
465            .fg(Self::TEXT_COLOR)
466            .bg(color);
467        Paragraph::new(label)
468            .centered()
469            .fg(Self::TEXT_COLOR)
470            .bg(color)
471            .block(block)
472            .render(area, buf);
473
474        if !self.legend {
475            let border_color = if self.selected {
476                lighter_color
477            } else {
478                main_color
479            };
480            if let Some(last_row) = area.rows().last() {
481                buf.set_style(last_row, border_color);
482            }
483        }
484    }
Source

pub const fn bg(self, color: Color) -> Self

Changes the background color.

§Examples
use ratatui::style::{Color, Style};

let style = Style::default().bg(Color::Blue);
let diff = Style::default().bg(Color::Red);
assert_eq!(style.patch(diff), Style::default().bg(Color::Red));
Examples found in repository?
examples/list.rs (line 34)
34const TODO_HEADER_STYLE: Style = Style::new().fg(SLATE.c100).bg(BLUE.c800);
35const NORMAL_ROW_BG: Color = SLATE.c950;
36const ALT_ROW_BG_COLOR: Color = SLATE.c900;
37const SELECTED_STYLE: Style = Style::new().bg(SLATE.c800).add_modifier(Modifier::BOLD);
More examples
Hide additional examples
examples/barchart-grouped.rs (line 196)
189    fn vertical_revenue_bar(&self, revenue: u32) -> Bar {
190        let text_value = format!("{:.1}M", f64::from(revenue) / 1000.);
191        Bar::default()
192            .label(self.short_name.into())
193            .value(u64::from(revenue))
194            .text_value(text_value)
195            .style(self.color)
196            .value_style(Style::new().fg(Color::Black).bg(self.color))
197    }
198
199    /// Create a horizontal revenue bar for the company
200    ///
201    /// The label is the long name of the company combined with the revenue and will be displayed
202    /// on the bar
203    fn horizontal_revenue_bar(&self, revenue: u32) -> Bar {
204        let text_value = format!("{} ({:.1} M)", self.name, f64::from(revenue) / 1000.);
205        Bar::default()
206            .value(u64::from(revenue))
207            .text_value(text_value)
208            .style(self.color)
209            .value_style(Style::new().fg(Color::Black).bg(self.color))
210    }
examples/line_gauge.rs (line 146)
142    fn render_gauge2(&self, area: Rect, buf: &mut Buffer) {
143        let title = title_block("Blue / red only background");
144        LineGauge::default()
145            .block(title)
146            .filled_style(Style::default().fg(Color::Blue).bg(Color::Blue))
147            .unfilled_style(Style::default().fg(Color::Red).bg(Color::Red))
148            .label("Background:")
149            .ratio(self.progress)
150            .render(area, buf);
151    }
152
153    fn render_gauge3(&self, area: Rect, buf: &mut Buffer) {
154        let title = title_block("Fully styled with background");
155        LineGauge::default()
156            .block(title)
157            .filled_style(
158                Style::default()
159                    .fg(tailwind::BLUE.c400)
160                    .bg(tailwind::BLUE.c600),
161            )
162            .unfilled_style(
163                Style::default()
164                    .fg(tailwind::RED.c400)
165                    .bg(tailwind::RED.c800),
166            )
167            .label("Both:")
168            .ratio(self.progress)
169            .render(area, buf);
170    }
examples/flex.rs (line 506)
497    fn illustration(constraint: Constraint, width: u16) -> impl Widget {
498        let main_color = color_for_constraint(constraint);
499        let fg_color = Color::White;
500        let title = format!("{constraint}");
501        let content = format!("{width} px");
502        let text = format!("{title}\n{content}");
503        let block = Block::bordered()
504            .border_set(symbols::border::QUADRANT_OUTSIDE)
505            .border_style(Style::reset().fg(main_color).reversed())
506            .style(Style::default().fg(fg_color).bg(main_color));
507        Paragraph::new(text).centered().block(block)
508    }
examples/custom_widget.rs (line 116)
114    fn render(self, area: Rect, buf: &mut Buffer) {
115        let (background, text, shadow, highlight) = self.colors();
116        buf.set_style(area, Style::new().bg(background).fg(text));
117
118        // render top line if there's enough space
119        if area.height > 2 {
120            buf.set_string(
121                area.x,
122                area.y,
123                "▔".repeat(area.width as usize),
124                Style::new().fg(highlight).bg(background),
125            );
126        }
127        // render bottom line if there's enough space
128        if area.height > 1 {
129            buf.set_string(
130                area.x,
131                area.y + area.height - 1,
132                "▁".repeat(area.width as usize),
133                Style::new().fg(shadow).bg(background),
134            );
135        }
136        // render label centered
137        buf.set_line(
138            area.x + (area.width.saturating_sub(self.label.width() as u16)) / 2,
139            area.y + (area.height.saturating_sub(1)) / 2,
140            &self.label,
141            area.width,
142        );
143    }
examples/sparkline.rs (line 139)
116    fn draw(&self, frame: &mut Frame) {
117        let chunks = Layout::vertical([
118            Constraint::Length(3),
119            Constraint::Length(3),
120            Constraint::Min(0),
121        ])
122        .split(frame.area());
123        let sparkline = Sparkline::default()
124            .block(
125                Block::new()
126                    .borders(Borders::LEFT | Borders::RIGHT)
127                    .title("Data1"),
128            )
129            .data(&self.data1)
130            .style(Style::default().fg(Color::Yellow));
131        frame.render_widget(sparkline, chunks[0]);
132        let sparkline = Sparkline::default()
133            .block(
134                Block::new()
135                    .borders(Borders::LEFT | Borders::RIGHT)
136                    .title("Data2"),
137            )
138            .data(&self.data2)
139            .style(Style::default().bg(Color::Green));
140        frame.render_widget(sparkline, chunks[1]);
141        // Multiline
142        let sparkline = Sparkline::default()
143            .block(
144                Block::new()
145                    .borders(Borders::LEFT | Borders::RIGHT)
146                    .title("Data3"),
147            )
148            .data(&self.data3)
149            .style(Style::default().fg(Color::Red));
150        frame.render_widget(sparkline, chunks[2]);
151    }
Source

pub const fn underline_color(self, color: Color) -> Self

Available on crate feature underline-color only.

Changes the underline color. The text must be underlined with a modifier for this to work.

This uses a non-standard ANSI escape sequence. It is supported by most terminal emulators, but is only implemented in the crossterm backend and enabled by the underline-color feature flag.

See Wikipedia code 58 and 59 for more information.

§Examples
use ratatui::style::{Color, Modifier, Style};

let style = Style::default()
    .underline_color(Color::Blue)
    .add_modifier(Modifier::UNDERLINED);
let diff = Style::default()
    .underline_color(Color::Red)
    .add_modifier(Modifier::UNDERLINED);
assert_eq!(
    style.patch(diff),
    Style::default()
        .underline_color(Color::Red)
        .add_modifier(Modifier::UNDERLINED)
);
Source

pub const fn add_modifier(self, modifier: Modifier) -> Self

Changes the text emphasis.

When applied, it adds the given modifier to the Style modifiers.

§Examples
use ratatui::style::{Modifier, Style};

let style = Style::default().add_modifier(Modifier::BOLD);
let diff = Style::default().add_modifier(Modifier::ITALIC);
let patched = style.patch(diff);
assert_eq!(patched.add_modifier, Modifier::BOLD | Modifier::ITALIC);
assert_eq!(patched.sub_modifier, Modifier::empty());
Examples found in repository?
examples/list.rs (line 37)
37const SELECTED_STYLE: Style = Style::new().bg(SLATE.c800).add_modifier(Modifier::BOLD);
More examples
Hide additional examples
examples/chart.rs (line 136)
132    fn render_animated_chart(&self, frame: &mut Frame, area: Rect) {
133        let x_labels = vec![
134            Span::styled(
135                format!("{}", self.window[0]),
136                Style::default().add_modifier(Modifier::BOLD),
137            ),
138            Span::raw(format!("{}", (self.window[0] + self.window[1]) / 2.0)),
139            Span::styled(
140                format!("{}", self.window[1]),
141                Style::default().add_modifier(Modifier::BOLD),
142            ),
143        ];
144        let datasets = vec![
145            Dataset::default()
146                .name("data2")
147                .marker(symbols::Marker::Dot)
148                .style(Style::default().fg(Color::Cyan))
149                .data(&self.data1),
150            Dataset::default()
151                .name("data3")
152                .marker(symbols::Marker::Braille)
153                .style(Style::default().fg(Color::Yellow))
154                .data(&self.data2),
155        ];
156
157        let chart = Chart::new(datasets)
158            .block(Block::bordered())
159            .x_axis(
160                Axis::default()
161                    .title("X Axis")
162                    .style(Style::default().fg(Color::Gray))
163                    .labels(x_labels)
164                    .bounds(self.window),
165            )
166            .y_axis(
167                Axis::default()
168                    .title("Y Axis")
169                    .style(Style::default().fg(Color::Gray))
170                    .labels(["-20".bold(), "0".into(), "20".bold()])
171                    .bounds([-20.0, 20.0]),
172            );
173
174        frame.render_widget(chart, area);
175    }
examples/table.rs (line 219)
214    fn render_table(&mut self, frame: &mut Frame, area: Rect) {
215        let header_style = Style::default()
216            .fg(self.colors.header_fg)
217            .bg(self.colors.header_bg);
218        let selected_row_style = Style::default()
219            .add_modifier(Modifier::REVERSED)
220            .fg(self.colors.selected_row_style_fg);
221        let selected_col_style = Style::default().fg(self.colors.selected_column_style_fg);
222        let selected_cell_style = Style::default()
223            .add_modifier(Modifier::REVERSED)
224            .fg(self.colors.selected_cell_style_fg);
225
226        let header = ["Name", "Address", "Email"]
227            .into_iter()
228            .map(Cell::from)
229            .collect::<Row>()
230            .style(header_style)
231            .height(1);
232        let rows = self.items.iter().enumerate().map(|(i, data)| {
233            let color = match i % 2 {
234                0 => self.colors.normal_row_color,
235                _ => self.colors.alt_row_color,
236            };
237            let item = data.ref_array();
238            item.into_iter()
239                .map(|content| Cell::from(Text::from(format!("\n{content}\n"))))
240                .collect::<Row>()
241                .style(Style::new().fg(self.colors.row_fg).bg(color))
242                .height(4)
243        });
244        let bar = " █ ";
245        let t = Table::new(
246            rows,
247            [
248                // + 1 is for padding.
249                Constraint::Length(self.longest_item_lens.0 + 1),
250                Constraint::Min(self.longest_item_lens.1 + 1),
251                Constraint::Min(self.longest_item_lens.2),
252            ],
253        )
254        .header(header)
255        .row_highlight_style(selected_row_style)
256        .column_highlight_style(selected_col_style)
257        .cell_highlight_style(selected_cell_style)
258        .highlight_symbol(Text::from(vec![
259            "".into(),
260            bar.into(),
261            bar.into(),
262            "".into(),
263        ]))
264        .bg(self.colors.buffer_bg)
265        .highlight_spacing(HighlightSpacing::Always);
266        frame.render_stateful_widget(t, area, &mut self.state);
267    }
examples/inline.rs (line 205)
170fn run(
171    terminal: &mut Terminal<impl Backend>,
172    workers: Vec<Worker>,
173    mut downloads: Downloads,
174    rx: mpsc::Receiver<Event>,
175) -> Result<()> {
176    let mut redraw = true;
177    loop {
178        if redraw {
179            terminal.draw(|frame| draw(frame, &downloads))?;
180        }
181        redraw = true;
182
183        match rx.recv()? {
184            Event::Input(event) => {
185                if event.code == event::KeyCode::Char('q') {
186                    break;
187                }
188            }
189            Event::Resize => {
190                terminal.autoresize()?;
191            }
192            Event::Tick => {}
193            Event::DownloadUpdate(worker_id, _download_id, progress) => {
194                let download = downloads.in_progress.get_mut(&worker_id).unwrap();
195                download.progress = progress;
196                redraw = false;
197            }
198            Event::DownloadDone(worker_id, download_id) => {
199                let download = downloads.in_progress.remove(&worker_id).unwrap();
200                terminal.insert_before(1, |buf| {
201                    Paragraph::new(Line::from(vec![
202                        Span::from("Finished "),
203                        Span::styled(
204                            format!("download {download_id}"),
205                            Style::default().add_modifier(Modifier::BOLD),
206                        ),
207                        Span::from(format!(
208                            " in {}ms",
209                            download.started_at.elapsed().as_millis()
210                        )),
211                    ]))
212                    .render(buf.area, buf);
213                })?;
214                match downloads.next(worker_id) {
215                    Some(d) => workers[worker_id].tx.send(d).unwrap(),
216                    None => {
217                        if downloads.in_progress.is_empty() {
218                            terminal.insert_before(1, |buf| {
219                                Paragraph::new("Done !").render(buf.area, buf);
220                            })?;
221                            break;
222                        }
223                    }
224                };
225            }
226        };
227    }
228    Ok(())
229}
230
231fn draw(frame: &mut Frame, downloads: &Downloads) {
232    let area = frame.area();
233
234    let block = Block::new().title(Line::from("Progress").centered());
235    frame.render_widget(block, area);
236
237    let vertical = Layout::vertical([Constraint::Length(2), Constraint::Length(4)]).margin(1);
238    let horizontal = Layout::horizontal([Constraint::Percentage(20), Constraint::Percentage(80)]);
239    let [progress_area, main] = vertical.areas(area);
240    let [list_area, gauge_area] = horizontal.areas(main);
241
242    // total progress
243    let done = NUM_DOWNLOADS - downloads.pending.len() - downloads.in_progress.len();
244    #[allow(clippy::cast_precision_loss)]
245    let progress = LineGauge::default()
246        .filled_style(Style::default().fg(Color::Blue))
247        .label(format!("{done}/{NUM_DOWNLOADS}"))
248        .ratio(done as f64 / NUM_DOWNLOADS as f64);
249    frame.render_widget(progress, progress_area);
250
251    // in progress downloads
252    let items: Vec<ListItem> = downloads
253        .in_progress
254        .values()
255        .map(|download| {
256            ListItem::new(Line::from(vec![
257                Span::raw(symbols::DOT),
258                Span::styled(
259                    format!(" download {:>2}", download.id),
260                    Style::default()
261                        .fg(Color::LightGreen)
262                        .add_modifier(Modifier::BOLD),
263                ),
264                Span::raw(format!(
265                    " ({}ms)",
266                    download.started_at.elapsed().as_millis()
267                )),
268            ]))
269        })
270        .collect();
271    let list = List::new(items);
272    frame.render_widget(list, list_area);
273
274    #[allow(clippy::cast_possible_truncation)]
275    for (i, (_, download)) in downloads.in_progress.iter().enumerate() {
276        let gauge = Gauge::default()
277            .gauge_style(Style::default().fg(Color::Yellow))
278            .ratio(download.progress / 100.0);
279        if gauge_area.top().saturating_add(i as u16) > area.bottom() {
280            continue;
281        }
282        frame.render_widget(
283            gauge,
284            Rect {
285                x: gauge_area.left(),
286                y: gauge_area.top().saturating_add(i as u16),
287                width: gauge_area.width,
288                height: 1,
289            },
290        );
291    }
292}
examples/demo2/theme.rs (line 69)
63pub const THEME: Theme = Theme {
64    root: Style::new().bg(DARK_BLUE),
65    content: Style::new().bg(DARK_BLUE).fg(LIGHT_GRAY),
66    app_title: Style::new()
67        .fg(WHITE)
68        .bg(DARK_BLUE)
69        .add_modifier(Modifier::BOLD),
70    tabs: Style::new().fg(MID_GRAY).bg(DARK_BLUE),
71    tabs_selected: Style::new()
72        .fg(WHITE)
73        .bg(DARK_BLUE)
74        .add_modifier(Modifier::BOLD)
75        .add_modifier(Modifier::REVERSED),
76    borders: Style::new().fg(LIGHT_GRAY),
77    description: Style::new().fg(LIGHT_GRAY).bg(DARK_BLUE),
78    description_title: Style::new().fg(LIGHT_GRAY).add_modifier(Modifier::BOLD),
79    logo: Logo {
80        rat: WHITE,
81        rat_eye: BLACK,
82        rat_eye_alt: RED,
83        term: BLACK,
84    },
85    key_binding: KeyBinding {
86        key: Style::new().fg(BLACK).bg(DARK_GRAY),
87        description: Style::new().fg(DARK_GRAY).bg(BLACK),
88    },
89    email: Email {
90        tabs: Style::new().fg(MID_GRAY).bg(DARK_BLUE),
91        tabs_selected: Style::new()
92            .fg(WHITE)
93            .bg(DARK_BLUE)
94            .add_modifier(Modifier::BOLD),
95        inbox: Style::new().bg(DARK_BLUE).fg(LIGHT_GRAY),
96        item: Style::new().fg(LIGHT_GRAY),
97        selected_item: Style::new().fg(LIGHT_YELLOW),
98        header: Style::new().add_modifier(Modifier::BOLD),
99        header_value: Style::new().fg(LIGHT_GRAY),
100        body: Style::new().bg(DARK_BLUE).fg(LIGHT_GRAY),
101    },
102    traceroute: Traceroute {
103        header: Style::new()
104            .bg(DARK_BLUE)
105            .add_modifier(Modifier::BOLD)
106            .add_modifier(Modifier::UNDERLINED),
107        selected: Style::new().fg(LIGHT_YELLOW),
108        ping: Style::new().fg(WHITE),
109        map: Map {
110            style: Style::new().bg(DARK_BLUE),
111            background_color: DARK_BLUE,
112            color: LIGHT_GRAY,
113            path: LIGHT_BLUE,
114            source: LIGHT_GREEN,
115            destination: LIGHT_RED,
116        },
117    },
118    recipe: Recipe {
119        ingredients: Style::new().bg(DARK_BLUE).fg(LIGHT_GRAY),
120        ingredients_header: Style::new()
121            .add_modifier(Modifier::BOLD)
122            .add_modifier(Modifier::UNDERLINED),
123    },
124};
examples/calendar.rs (line 77)
74fn make_dates(current_year: i32) -> CalendarEventStore {
75    let mut list = CalendarEventStore::today(
76        Style::default()
77            .add_modifier(Modifier::BOLD)
78            .bg(Color::Blue),
79    );
80
81    // Holidays
82    let holiday_style = Style::default()
83        .fg(Color::Red)
84        .add_modifier(Modifier::UNDERLINED);
85
86    // new year's
87    list.add(
88        Date::from_calendar_date(current_year, Month::January, 1).unwrap(),
89        holiday_style,
90    );
91    // next new_year's for December "show surrounding"
92    list.add(
93        Date::from_calendar_date(current_year + 1, Month::January, 1).unwrap(),
94        holiday_style,
95    );
96    // groundhog day
97    list.add(
98        Date::from_calendar_date(current_year, Month::February, 2).unwrap(),
99        holiday_style,
100    );
101    // april fool's
102    list.add(
103        Date::from_calendar_date(current_year, Month::April, 1).unwrap(),
104        holiday_style,
105    );
106    // earth day
107    list.add(
108        Date::from_calendar_date(current_year, Month::April, 22).unwrap(),
109        holiday_style,
110    );
111    // star wars day
112    list.add(
113        Date::from_calendar_date(current_year, Month::May, 4).unwrap(),
114        holiday_style,
115    );
116    // festivus
117    list.add(
118        Date::from_calendar_date(current_year, Month::December, 23).unwrap(),
119        holiday_style,
120    );
121    // new year's eve
122    list.add(
123        Date::from_calendar_date(current_year, Month::December, 31).unwrap(),
124        holiday_style,
125    );
126
127    // seasons
128    let season_style = Style::default()
129        .fg(Color::White)
130        .bg(Color::Yellow)
131        .add_modifier(Modifier::UNDERLINED);
132    // spring equinox
133    list.add(
134        Date::from_calendar_date(current_year, Month::March, 22).unwrap(),
135        season_style,
136    );
137    // summer solstice
138    list.add(
139        Date::from_calendar_date(current_year, Month::June, 21).unwrap(),
140        season_style,
141    );
142    // fall equinox
143    list.add(
144        Date::from_calendar_date(current_year, Month::September, 22).unwrap(),
145        season_style,
146    );
147    list.add(
148        Date::from_calendar_date(current_year, Month::December, 21).unwrap(),
149        season_style,
150    );
151    list
152}
153
154mod cals {
155    #[allow(clippy::wildcard_imports)]
156    use super::*;
157
158    pub fn get_cal<'a, DS: DateStyler>(m: Month, y: i32, es: DS) -> Monthly<'a, DS> {
159        match m {
160            Month::May => example1(m, y, es),
161            Month::June => example2(m, y, es),
162            Month::July | Month::December => example3(m, y, es),
163            Month::February => example4(m, y, es),
164            Month::November => example5(m, y, es),
165            _ => default(m, y, es),
166        }
167    }
168
169    fn default<'a, DS: DateStyler>(m: Month, y: i32, es: DS) -> Monthly<'a, DS> {
170        let default_style = Style::default()
171            .add_modifier(Modifier::BOLD)
172            .bg(Color::Rgb(50, 50, 50));
173
174        Monthly::new(Date::from_calendar_date(y, m, 1).unwrap(), es)
175            .show_month_header(Style::default())
176            .default_style(default_style)
177    }
178
179    fn example1<'a, DS: DateStyler>(m: Month, y: i32, es: DS) -> Monthly<'a, DS> {
180        let default_style = Style::default()
181            .add_modifier(Modifier::BOLD)
182            .bg(Color::Rgb(50, 50, 50));
183
184        Monthly::new(Date::from_calendar_date(y, m, 1).unwrap(), es)
185            .show_surrounding(default_style)
186            .default_style(default_style)
187            .show_month_header(Style::default())
188    }
189
190    fn example2<'a, DS: DateStyler>(m: Month, y: i32, es: DS) -> Monthly<'a, DS> {
191        let header_style = Style::default()
192            .add_modifier(Modifier::BOLD)
193            .add_modifier(Modifier::DIM)
194            .fg(Color::LightYellow);
195
196        let default_style = Style::default()
197            .add_modifier(Modifier::BOLD)
198            .bg(Color::Rgb(50, 50, 50));
199
200        Monthly::new(Date::from_calendar_date(y, m, 1).unwrap(), es)
201            .show_weekdays_header(header_style)
202            .default_style(default_style)
203            .show_month_header(Style::default())
204    }
205
206    fn example3<'a, DS: DateStyler>(m: Month, y: i32, es: DS) -> Monthly<'a, DS> {
207        let header_style = Style::default()
208            .add_modifier(Modifier::BOLD)
209            .fg(Color::Green);
210
211        let default_style = Style::default()
212            .add_modifier(Modifier::BOLD)
213            .bg(Color::Rgb(50, 50, 50));
214
215        Monthly::new(Date::from_calendar_date(y, m, 1).unwrap(), es)
216            .show_surrounding(Style::default().add_modifier(Modifier::DIM))
217            .show_weekdays_header(header_style)
218            .default_style(default_style)
219            .show_month_header(Style::default())
220    }
221
222    fn example4<'a, DS: DateStyler>(m: Month, y: i32, es: DS) -> Monthly<'a, DS> {
223        let header_style = Style::default()
224            .add_modifier(Modifier::BOLD)
225            .fg(Color::Green);
226
227        let default_style = Style::default()
228            .add_modifier(Modifier::BOLD)
229            .bg(Color::Rgb(50, 50, 50));
230
231        Monthly::new(Date::from_calendar_date(y, m, 1).unwrap(), es)
232            .show_weekdays_header(header_style)
233            .default_style(default_style)
234    }
235
236    fn example5<'a, DS: DateStyler>(m: Month, y: i32, es: DS) -> Monthly<'a, DS> {
237        let header_style = Style::default()
238            .add_modifier(Modifier::BOLD)
239            .fg(Color::Green);
240
241        let default_style = Style::default()
242            .add_modifier(Modifier::BOLD)
243            .bg(Color::Rgb(50, 50, 50));
244
245        Monthly::new(Date::from_calendar_date(y, m, 1).unwrap(), es)
246            .show_month_header(header_style)
247            .default_style(default_style)
248    }
Source

pub const fn remove_modifier(self, modifier: Modifier) -> Self

Changes the text emphasis.

When applied, it removes the given modifier from the Style modifiers.

§Examples
use ratatui::style::{Modifier, Style};

let style = Style::default().add_modifier(Modifier::BOLD | Modifier::ITALIC);
let diff = Style::default().remove_modifier(Modifier::ITALIC);
let patched = style.patch(diff);
assert_eq!(patched.add_modifier, Modifier::BOLD);
assert_eq!(patched.sub_modifier, Modifier::ITALIC);
Source

pub fn patch<S: Into<Self>>(self, other: S) -> Self

Results in a combined style that is equivalent to applying the two individual styles to a style one after the other.

style accepts any type that is convertible to Style (e.g. Style, Color, or your own type that implements Into<Style>).

§Examples
use ratatui::style::{Color, Modifier, Style};

let style_1 = Style::default().fg(Color::Yellow);
let style_2 = Style::default().bg(Color::Red);
let combined = style_1.patch(style_2);
assert_eq!(
    Style::default().patch(style_1).patch(style_2),
    Style::default().patch(combined)
);

Trait Implementations§

Source§

impl Clone for Style

Source§

fn clone(&self) -> Style

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Style

A custom debug implementation that prints only the fields that are not the default, and unwraps the Options.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Style

Source§

fn default() -> Style

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Style

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<(Color, Color)> for Style

Source§

fn from((fg, bg): (Color, Color)) -> Self

Creates a new Style with the given foreground and background colors.

§Example
use ratatui::style::{Color, Style};

// red foreground, blue background
let style = Style::from((Color::Red, Color::Blue));
// default foreground, blue background
let style = Style::from((Color::Reset, Color::Blue));
Source§

impl From<(Color, Color, Modifier)> for Style

Source§

fn from((fg, bg, modifier): (Color, Color, Modifier)) -> Self

Creates a new Style with the given foreground and background colors and modifier added.

To specify multiple modifiers, use the | operator.

§Example
use ratatui::style::{Color, Modifier, Style};

// red foreground, blue background, add bold and italic
let style = Style::from((Color::Red, Color::Blue, Modifier::BOLD | Modifier::ITALIC));
Source§

impl From<(Color, Color, Modifier, Modifier)> for Style

Source§

fn from( (fg, bg, add_modifier, sub_modifier): (Color, Color, Modifier, Modifier), ) -> Self

Creates a new Style with the given foreground and background colors and modifiers added and removed.

§Example
use ratatui::style::{Color, Modifier, Style};

// red foreground, blue background, add bold and italic, remove dim
let style = Style::from((
    Color::Red,
    Color::Blue,
    Modifier::BOLD | Modifier::ITALIC,
    Modifier::DIM,
));
Source§

impl From<(Color, Modifier)> for Style

Source§

fn from((fg, modifier): (Color, Modifier)) -> Self

Creates a new Style with the given foreground color and modifier added.

To specify multiple modifiers, use the | operator.

§Example
use ratatui::style::{Color, Modifier, Style};

// red foreground, add bold and italic
let style = Style::from((Color::Red, Modifier::BOLD | Modifier::ITALIC));
Source§

impl From<(Modifier, Modifier)> for Style

Source§

fn from((add_modifier, sub_modifier): (Modifier, Modifier)) -> Self

Creates a new Style with the given modifiers added and removed.

§Example
use ratatui::style::{Modifier, Style};

// add bold and italic, remove dim
let style = Style::from((Modifier::BOLD | Modifier::ITALIC, Modifier::DIM));
Source§

impl From<Bg<AnsiValue>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(value: Bg<AnsiValue>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<Black>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<Black>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<Blue>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<Blue>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<Cyan>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<Cyan>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<Green>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<Green>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<LightBlack>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<LightBlack>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<LightBlue>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<LightBlue>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<LightCyan>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<LightCyan>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<LightGreen>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<LightGreen>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<LightMagenta>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<LightMagenta>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<LightRed>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<LightRed>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<LightWhite>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<LightWhite>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<LightYellow>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<LightYellow>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<Magenta>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<Magenta>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<Red>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<Red>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<Reset>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<Reset>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<Rgb>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(value: Bg<Rgb>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<White>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<White>) -> Self

Converts to this type from the input type.
Source§

impl From<Bg<Yellow>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Bg<Yellow>) -> Self

Converts to this type from the input type.
Source§

impl From<CellAttributes> for Style

Available on crate feature termwiz only.
Source§

fn from(value: CellAttributes) -> Self

Converts to this type from the input type.
Source§

impl From<Color> for Style

Source§

fn from(color: Color) -> Self

Creates a new Style with the given foreground color.

To specify a foreground and background color, use the from((fg, bg)) constructor.

§Example
use ratatui::style::{Color, Style};

let style = Style::from(Color::Red);
Source§

impl From<ContentStyle> for Style

Available on crate feature crossterm only.
Source§

fn from(value: ContentStyle) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<AnsiValue>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(value: Fg<AnsiValue>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<Black>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<Black>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<Blue>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<Blue>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<Cyan>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<Cyan>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<Green>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<Green>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<LightBlack>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<LightBlack>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<LightBlue>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<LightBlue>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<LightCyan>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<LightCyan>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<LightGreen>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<LightGreen>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<LightMagenta>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<LightMagenta>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<LightRed>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<LightRed>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<LightWhite>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<LightWhite>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<LightYellow>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<LightYellow>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<Magenta>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<Magenta>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<Red>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<Red>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<Reset>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<Reset>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<Rgb>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(value: Fg<Rgb>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<White>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<White>) -> Self

Converts to this type from the input type.
Source§

impl From<Fg<Yellow>> for Style

Available on non-Windows and crate feature termion only.
Source§

fn from(_: Fg<Yellow>) -> Self

Converts to this type from the input type.
Source§

impl From<Modifier> for Style

Source§

fn from(modifier: Modifier) -> Self

Creates a new Style with the given modifier added.

To specify multiple modifiers, use the | operator.

To specify modifiers to add and remove, use the from((add_modifier, sub_modifier)) constructor.

§Example
use ratatui::style::{Style, Modifier};

// add bold and italic
let style = Style::from(Modifier::BOLD|Modifier::ITALIC);
Source§

impl Hash for Style

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Style

Source§

fn eq(&self, other: &Style) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Style

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Styled for Style

Source§

type Item = Style

Source§

fn style(&self) -> Style

Returns the style of the object.
Source§

fn set_style<S: Into<Self>>(self, style: S) -> Self::Item

Sets the style of the object. Read more
Source§

impl Copy for Style

Source§

impl Eq for Style

Source§

impl StructuralPartialEq for Style

Auto Trait Implementations§

§

impl Freeze for Style

§

impl RefUnwindSafe for Style

§

impl Send for Style

§

impl Sync for Style

§

impl Unpin for Style

§

impl UnwindSafe for Style

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<'a, T, U> Stylize<'a, T> for U
where U: Styled<Item = T>,

Source§

fn bg<C>(self, color: C) -> T
where C: Into<Color>,

Source§

fn fg<C>(self, color: C) -> T
where C: Into<Color>,

Source§

fn add_modifier(self, modifier: Modifier) -> T

Source§

fn remove_modifier(self, modifier: Modifier) -> T

Source§

fn reset(self) -> T

Source§

fn black(self) -> T

Sets the foreground color to black.
Source§

fn on_black(self) -> T

Sets the background color to black.
Source§

fn red(self) -> T

Sets the foreground color to red.
Source§

fn on_red(self) -> T

Sets the background color to red.
Source§

fn green(self) -> T

Sets the foreground color to green.
Source§

fn on_green(self) -> T

Sets the background color to green.
Source§

fn yellow(self) -> T

Sets the foreground color to yellow.
Source§

fn on_yellow(self) -> T

Sets the background color to yellow.
Source§

fn blue(self) -> T

Sets the foreground color to blue.
Source§

fn on_blue(self) -> T

Sets the background color to blue.
Source§

fn magenta(self) -> T

Sets the foreground color to magenta.
Source§

fn on_magenta(self) -> T

Sets the background color to magenta.
Source§

fn cyan(self) -> T

Sets the foreground color to cyan.
Source§

fn on_cyan(self) -> T

Sets the background color to cyan.
Source§

fn gray(self) -> T

Sets the foreground color to gray.
Source§

fn on_gray(self) -> T

Sets the background color to gray.
Source§

fn dark_gray(self) -> T

Sets the foreground color to dark_gray.
Source§

fn on_dark_gray(self) -> T

Sets the background color to dark_gray.
Source§

fn light_red(self) -> T

Sets the foreground color to light_red.
Source§

fn on_light_red(self) -> T

Sets the background color to light_red.
Source§

fn light_green(self) -> T

Sets the foreground color to light_green.
Source§

fn on_light_green(self) -> T

Sets the background color to light_green.
Source§

fn light_yellow(self) -> T

Sets the foreground color to light_yellow.
Source§

fn on_light_yellow(self) -> T

Sets the background color to light_yellow.
Source§

fn light_blue(self) -> T

Sets the foreground color to light_blue.
Source§

fn on_light_blue(self) -> T

Sets the background color to light_blue.
Source§

fn light_magenta(self) -> T

Sets the foreground color to light_magenta.
Source§

fn on_light_magenta(self) -> T

Sets the background color to light_magenta.
Source§

fn light_cyan(self) -> T

Sets the foreground color to light_cyan.
Source§

fn on_light_cyan(self) -> T

Sets the background color to light_cyan.
Source§

fn white(self) -> T

Sets the foreground color to white.
Source§

fn on_white(self) -> T

Sets the background color to white.
Source§

fn bold(self) -> T

Adds the BOLD modifier.
Source§

fn not_bold(self) -> T

Removes the BOLD modifier.
Source§

fn dim(self) -> T

Adds the DIM modifier.
Source§

fn not_dim(self) -> T

Removes the DIM modifier.
Source§

fn italic(self) -> T

Adds the ITALIC modifier.
Source§

fn not_italic(self) -> T

Removes the ITALIC modifier.
Source§

fn underlined(self) -> T

Adds the UNDERLINED modifier.
Source§

fn not_underlined(self) -> T

Removes the UNDERLINED modifier.
Adds the SLOW_BLINK modifier.
Removes the SLOW_BLINK modifier.
Adds the RAPID_BLINK modifier.
Removes the RAPID_BLINK modifier.
Source§

fn reversed(self) -> T

Adds the REVERSED modifier.
Source§

fn not_reversed(self) -> T

Removes the REVERSED modifier.
Source§

fn hidden(self) -> T

Adds the HIDDEN modifier.
Source§

fn not_hidden(self) -> T

Removes the HIDDEN modifier.
Source§

fn crossed_out(self) -> T

Adds the CROSSED_OUT modifier.
Source§

fn not_crossed_out(self) -> T

Removes the CROSSED_OUT modifier.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,