Struct Line

Source
pub struct Line<'a> {
    pub style: Style,
    pub alignment: Option<Alignment>,
    pub spans: Vec<Span<'a>>,
}
Expand description

A line of text, consisting of one or more Spans.

Lines are used wherever text is displayed in the terminal and represent a single line of text. When a Line is rendered, it is rendered as a single line of text, with each Span being rendered in order (left to right).

Any newlines in the content are removed when creating a Line using the constructor or conversion methods.

§Constructor Methods

  • Line::default creates a line with empty content and the default style.
  • Line::raw creates a line with the given content and the default style.
  • Line::styled creates a line with the given content and style.

§Conversion Methods

§Setter Methods

These methods are fluent setters. They return a Line with the property set.

§Iteration Methods

  • Line::iter returns an iterator over the spans of this line.
  • Line::iter_mut returns a mutable iterator over the spans of this line.
  • Line::into_iter returns an iterator over the spans of this line.

§Other Methods

§Compatibility Notes

Before v0.26.0, Line did not have a style field and instead relied on only the styles that were set on each Span contained in the spans field. The Line::patch_style method was the only way to set the overall style for individual lines. For this reason, this field may not be supported yet by all widgets (outside of the ratatui crate itself).

§Examples

§Creating Lines

Lines can be created from Spans, Strings, and &strs. They can be styled with a Style.

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

let style = Style::new().yellow();
let line = Line::raw("Hello, world!").style(style);
let line = Line::styled("Hello, world!", style);
let line = Line::styled("Hello, world!", (Color::Yellow, Modifier::BOLD));

let line = Line::from("Hello, world!");
let line = Line::from(String::from("Hello, world!"));
let line = Line::from(vec![
    Span::styled("Hello", Style::new().blue()),
    Span::raw(" world!"),
]);

§Styling Lines

The line’s Style is used by the rendering widget to determine how to style the line. Each Span in the line will be styled with the Style of the line, and then with its own Style. If the line is longer than the available space, the style is applied to the entire line, and the line is truncated. Line also implements Styled which means you can use the methods of the Stylize trait.

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

let line = Line::from("Hello world!").style(Style::new().yellow().italic());
let line = Line::from("Hello world!").style(Color::Yellow);
let line = Line::from("Hello world!").style((Color::Yellow, Color::Black));
let line = Line::from("Hello world!").style((Color::Yellow, Modifier::ITALIC));
let line = Line::from("Hello world!").yellow().italic();

§Aligning Lines

The line’s Alignment is used by the rendering widget to determine how to align the line within the available space. If the line is longer than the available space, the alignment is ignored and the line is truncated.

use ratatui::{layout::Alignment, text::Line};

let line = Line::from("Hello world!").alignment(Alignment::Right);
let line = Line::from("Hello world!").centered();
let line = Line::from("Hello world!").left_aligned();
let line = Line::from("Hello world!").right_aligned();

§Rendering Lines

Line implements the Widget trait, which means it can be rendered to a Buffer.

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Style, Stylize},
    text::Line,
    widgets::Widget,
    Frame,
};

// in another widget's render method
let line = Line::from("Hello world!").style(Style::new().yellow().italic());
line.render(area, buf);

// in a terminal.draw closure
let line = Line::from("Hello world!").style(Style::new().yellow().italic());
frame.render_widget(line, area);

§Rendering Lines with a Paragraph widget

Usually apps will use the Paragraph widget instead of rendering a Line directly as it provides more functionality.

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::Stylize,
    text::Line,
    widgets::{Paragraph, Widget, Wrap},
};

let line = Line::from("Hello world!").yellow().italic();
Paragraph::new(line)
    .wrap(Wrap { trim: true })
    .render(area, buf);

Fields§

§style: Style

The style of this line of text.

§alignment: Option<Alignment>

The alignment of this line of text.

§spans: Vec<Span<'a>>

The spans that make up this line of text.

Implementations§

Source§

impl<'a> Line<'a>

Source

pub fn raw<T>(content: T) -> Self
where T: Into<Cow<'a, str>>,

Create a line with the default style.

content can be any type that is convertible to Cow<str> (e.g. &str, String, Cow<str>, or your own type that implements Into<Cow<str>>).

A Line can specify a Style, which will be applied before the style of each Span in the line.

Any newlines in the content are removed.

§Examples
use std::borrow::Cow;

use ratatui::text::Line;

Line::raw("test content");
Line::raw(String::from("test content"));
Line::raw(Cow::from("test content"));
Examples found in repository?
examples/tabs.rs (line 150)
149fn render_footer(area: Rect, buf: &mut Buffer) {
150    Line::raw("◄ ► to change tab | Press q to quit")
151        .centered()
152        .render(area, buf);
153}
More examples
Hide additional examples
examples/paragraph.rs (line 144)
128fn create_lines(area: Rect) -> Vec<Line<'static>> {
129    let short_line = "A long line to demonstrate line wrapping. ";
130    let long_line = short_line.repeat(usize::from(area.width) / short_line.len() + 4);
131    let mut styled_spans = vec![];
132    for span in [
133        "Styled".blue(),
134        "Spans".red().on_white(),
135        "Bold".bold(),
136        "Italic".italic(),
137        "Underlined".underlined(),
138        "Strikethrough".crossed_out(),
139    ] {
140        styled_spans.push(span);
141        styled_spans.push(" ".into());
142    }
143    vec![
144        Line::raw("Unstyled Line"),
145        Line::raw("Styled Line").black().on_red().bold().italic(),
146        Line::from(styled_spans),
147        Line::from(long_line.green().italic()),
148        Line::from_iter([
149            "Masked text: ".into(),
150            Span::styled(Masked::new("my secret password", '*'), Color::Red),
151        ]),
152    ]
153}
examples/list.rs (line 210)
208    fn render_list(&mut self, area: Rect, buf: &mut Buffer) {
209        let block = Block::new()
210            .title(Line::raw("TODO List").centered())
211            .borders(Borders::TOP)
212            .border_set(symbols::border::EMPTY)
213            .border_style(TODO_HEADER_STYLE)
214            .bg(NORMAL_ROW_BG);
215
216        // Iterate through all elements in the `items` and stylize them.
217        let items: Vec<ListItem> = self
218            .todo_list
219            .items
220            .iter()
221            .enumerate()
222            .map(|(i, todo_item)| {
223                let color = alternate_colors(i);
224                ListItem::from(todo_item).bg(color)
225            })
226            .collect();
227
228        // Create a List from all list items and highlight the currently selected one
229        let list = List::new(items)
230            .block(block)
231            .highlight_style(SELECTED_STYLE)
232            .highlight_symbol(">")
233            .highlight_spacing(HighlightSpacing::Always);
234
235        // We need to disambiguate this trait method as both `Widget` and `StatefulWidget` share the
236        // same method name `render`.
237        StatefulWidget::render(list, area, buf, &mut self.todo_list.state);
238    }
239
240    fn render_selected_item(&self, area: Rect, buf: &mut Buffer) {
241        // We get the info depending on the item's state.
242        let info = if let Some(i) = self.todo_list.state.selected() {
243            match self.todo_list.items[i].status {
244                Status::Completed => format!("✓ DONE: {}", self.todo_list.items[i].info),
245                Status::Todo => format!("☐ TODO: {}", self.todo_list.items[i].info),
246            }
247        } else {
248            "Nothing selected...".to_string()
249        };
250
251        // We show the list item's info under the list in this paragraph
252        let block = Block::new()
253            .title(Line::raw("TODO Info").centered())
254            .borders(Borders::TOP)
255            .border_set(symbols::border::EMPTY)
256            .border_style(TODO_HEADER_STYLE)
257            .bg(NORMAL_ROW_BG)
258            .padding(Padding::horizontal(1));
259
260        // We can now render the item info
261        Paragraph::new(info)
262            .block(block)
263            .fg(TEXT_FG_COLOR)
264            .wrap(Wrap { trim: false })
265            .render(area, buf);
266    }
examples/flex.rs (line 487)
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    }
Source

pub fn styled<T, S>(content: T, style: S) -> Self
where T: Into<Cow<'a, str>>, S: Into<Style>,

Create a line with the given style.

content can be any type that is convertible to Cow<str> (e.g. &str, String, Cow<str>, or your own type that implements Into<Cow<str>>).

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

§Examples

Any newlines in the content are removed.

use std::borrow::Cow;

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

let style = Style::new().yellow().italic();
Line::styled("My text", style);
Line::styled(String::from("My text"), style);
Line::styled(Cow::from("test content"), style);
Examples found in repository?
examples/list.rs (line 280)
278    fn from(value: &TodoItem) -> Self {
279        let line = match value.status {
280            Status::Todo => Line::styled(format!(" ☐ {}", value.todo), TEXT_FG_COLOR),
281            Status::Completed => {
282                Line::styled(format!(" ✓ {}", value.todo), COMPLETED_TEXT_FG_COLOR)
283            }
284        };
285        ListItem::new(line)
286    }
More examples
Hide additional examples
examples/constraint-explorer.rs (line 547)
537    fn label(width: u16) -> impl Widget {
538        let long_label = format!("{width} px");
539        let short_label = format!("{width}");
540        let label = if long_label.len() < width as usize {
541            long_label
542        } else if short_label.len() < width as usize {
543            short_label
544        } else {
545            String::new()
546        };
547        Line::styled(label, Self::TEXT_COLOR).centered()
548    }
examples/flex.rs (line 489)
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    }
Source

pub fn spans<I>(self, spans: I) -> Self
where I: IntoIterator, I::Item: Into<Span<'a>>,

Sets the spans of this line of text.

spans accepts any iterator that yields items that are convertible to Span (e.g. &str, String, Span, or your own type that implements Into<Span>).

§Examples
use ratatui::{style::Stylize, text::Line};

let line = Line::default().spans(vec!["Hello".blue(), " world!".green()]);
let line = Line::default().spans([1, 2, 3].iter().map(|i| format!("Item {}", i)));
Source

pub fn style<S: Into<Style>>(self, style: S) -> Self

Sets the style of this line of text.

Defaults to Style::default().

Note: This field was added in v0.26.0. Prior to that, the style of a line was determined only by the style of each Span contained in the line. For this reason, this field may not be supported by all widgets (outside of the ratatui crate itself).

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::{Style, Stylize},
    text::Line,
};

let mut line = Line::from("foo").style(Style::new().red());
Examples found in repository?
examples/demo2/app.rs (line 201)
182    fn render_bottom_bar(area: Rect, buf: &mut Buffer) {
183        let keys = [
184            ("H/←", "Left"),
185            ("L/→", "Right"),
186            ("K/↑", "Up"),
187            ("J/↓", "Down"),
188            ("D/Del", "Destroy"),
189            ("Q/Esc", "Quit"),
190        ];
191        let spans = keys
192            .iter()
193            .flat_map(|(key, desc)| {
194                let key = Span::styled(format!(" {key} "), THEME.key_binding.key);
195                let desc = Span::styled(format!(" {desc} "), THEME.key_binding.description);
196                [key, desc]
197            })
198            .collect_vec();
199        Line::from(spans)
200            .centered()
201            .style((Color::Indexed(236), Color::Indexed(232)))
202            .render(area, buf);
203    }
Source

pub fn alignment(self, alignment: Alignment) -> Self

Sets the target alignment for this line of text.

Defaults to: None, meaning the alignment is determined by the rendering widget. Setting the alignment of a Line generally overrides the alignment of its parent Text or Widget.

§Examples
use ratatui::{layout::Alignment, text::Line};

let mut line = Line::from("Hi, what's up?");
assert_eq!(None, line.alignment);
assert_eq!(
    Some(Alignment::Right),
    line.alignment(Alignment::Right).alignment
)
Source

pub fn left_aligned(self) -> Self

Left-aligns this line of text.

Convenience shortcut for Line::alignment(Alignment::Left). Setting the alignment of a Line generally overrides the alignment of its parent Text or Widget, with the default alignment being inherited from the parent.

§Examples
use ratatui::text::Line;

let line = Line::from("Hi, what's up?").left_aligned();
Examples found in repository?
examples/block.rs (line 164)
162fn render_multiple_title_positions(paragraph: &Paragraph, frame: &mut Frame, area: Rect) {
163    let block = Block::bordered()
164        .title(Line::from("top left").left_aligned())
165        .title(Line::from("top center").centered())
166        .title(Line::from("top right").right_aligned())
167        .title_bottom(Line::from("bottom left").left_aligned())
168        .title_bottom(Line::from("bottom center").centered())
169        .title_bottom(Line::from("bottom right").right_aligned());
170    frame.render_widget(paragraph.clone().block(block), area);
171}
Source

pub fn centered(self) -> Self

Center-aligns this line of text.

Convenience shortcut for Line::alignment(Alignment::Center). Setting the alignment of a Line generally overrides the alignment of its parent Text or Widget, with the default alignment being inherited from the parent.

§Examples
use ratatui::text::Line;

let line = Line::from("Hi, what's up?").centered();
Examples found in repository?
examples/tabs.rs (line 151)
149fn render_footer(area: Rect, buf: &mut Buffer) {
150    Line::raw("◄ ► to change tab | Press q to quit")
151        .centered()
152        .render(area, buf);
153}
More examples
Hide additional examples
examples/line_gauge.rs (line 175)
173fn title_block(title: &str) -> Block {
174    Block::default()
175        .title(Line::from(title).centered())
176        .borders(Borders::NONE)
177        .fg(CUSTOM_LABEL_COLOR)
178        .padding(Padding::vertical(1))
179}
examples/gauge.rs (line 199)
198fn title_block(title: &str) -> Block {
199    let title = Line::from(title).centered();
200    Block::new()
201        .borders(Borders::NONE)
202        .padding(Padding::vertical(1))
203        .title(title)
204        .fg(CUSTOM_LABEL_COLOR)
205}
examples/async.rs (line 103)
100    fn draw(&self, frame: &mut Frame) {
101        let vertical = Layout::vertical([Constraint::Length(1), Constraint::Fill(1)]);
102        let [title_area, body_area] = vertical.areas(frame.area());
103        let title = Line::from("Ratatui async example").centered().bold();
104        frame.render_widget(title, title_area);
105        frame.render_widget(&self.pull_requests, body_area);
106    }
examples/barchart.rs (line 89)
83fn vertical_barchart(temperatures: &[u8]) -> BarChart {
84    let bars: Vec<Bar> = temperatures
85        .iter()
86        .enumerate()
87        .map(|(hour, value)| vertical_bar(hour, value))
88        .collect();
89    let title = Line::from("Weather (Vertical)").centered();
90    BarChart::default()
91        .data(BarGroup::default().bars(&bars))
92        .block(Block::new().title(title))
93        .bar_width(5)
94}
95
96fn vertical_bar(hour: usize, temperature: &u8) -> Bar {
97    Bar::default()
98        .value(u64::from(*temperature))
99        .label(Line::from(format!("{hour:>02}:00")))
100        .text_value(format!("{temperature:>3}°"))
101        .style(temperature_style(*temperature))
102        .value_style(temperature_style(*temperature).reversed())
103}
104
105/// Create a horizontal bar chart from the temperatures data.
106fn horizontal_barchart(temperatures: &[u8]) -> BarChart {
107    let bars: Vec<Bar> = temperatures
108        .iter()
109        .enumerate()
110        .map(|(hour, value)| horizontal_bar(hour, value))
111        .collect();
112    let title = Line::from("Weather (Horizontal)").centered();
113    BarChart::default()
114        .block(Block::new().title(title))
115        .data(BarGroup::default().bars(&bars))
116        .bar_width(1)
117        .bar_gap(0)
118        .direction(Direction::Horizontal)
119}
examples/barchart-grouped.rs (line 95)
93    fn vertical_revenue_barchart(&self) -> BarChart<'_> {
94        let mut barchart = BarChart::default()
95            .block(Block::new().title(Line::from("Company revenues (Vertical)").centered()))
96            .bar_gap(0)
97            .bar_width(6)
98            .group_gap(2);
99
100        for group in self
101            .revenues
102            .iter()
103            .map(|revenue| revenue.to_vertical_bar_group(&self.companies))
104        {
105            barchart = barchart.data(group);
106        }
107        barchart
108    }
109
110    /// Create a horizontal revenue bar chart with the data from the `revenues` field.
111    fn horizontal_revenue_barchart(&self) -> BarChart<'_> {
112        let title = Line::from("Company Revenues (Horizontal)").centered();
113        let mut barchart = BarChart::default()
114            .block(Block::new().title(title))
115            .bar_width(1)
116            .group_gap(2)
117            .bar_gap(0)
118            .direction(Direction::Horizontal);
119        for group in self
120            .revenues
121            .iter()
122            .map(|revenue| revenue.to_horizontal_bar_group(&self.companies))
123        {
124            barchart = barchart.data(group);
125        }
126        barchart
127    }
128}
129
130/// Generate fake company data
131const fn fake_companies() -> [Company; COMPANY_COUNT] {
132    [
133        Company::new("BAKE", "Bake my day", Color::LightRed),
134        Company::new("BITE", "Bits and Bites", Color::Blue),
135        Company::new("TART", "Tart of the Table", Color::White),
136    ]
137}
138
139/// Some fake revenue data
140const fn fake_revenues() -> [Revenues; PERIOD_COUNT] {
141    [
142        Revenues::new("Jan", [8500, 6500, 7000]),
143        Revenues::new("Feb", [9000, 7500, 8500]),
144        Revenues::new("Mar", [9500, 4500, 8200]),
145        Revenues::new("Apr", [6300, 4000, 5000]),
146    ]
147}
148
149impl Revenues {
150    /// Create a new instance of `Revenues`
151    const fn new(period: &'static str, revenues: [u32; COMPANY_COUNT]) -> Self {
152        Self { period, revenues }
153    }
154
155    /// Create a `BarGroup` with vertical bars for each company
156    fn to_vertical_bar_group<'a>(&self, companies: &'a [Company]) -> BarGroup<'a> {
157        let bars: Vec<Bar> = zip(companies, self.revenues)
158            .map(|(company, revenue)| company.vertical_revenue_bar(revenue))
159            .collect();
160        BarGroup::default()
161            .label(Line::from(self.period).centered())
162            .bars(&bars)
163    }
164
165    /// Create a `BarGroup` with horizontal bars for each company
166    fn to_horizontal_bar_group<'a>(&'a self, companies: &'a [Company]) -> BarGroup<'a> {
167        let bars: Vec<Bar> = zip(companies, self.revenues)
168            .map(|(company, revenue)| company.horizontal_revenue_bar(revenue))
169            .collect();
170        BarGroup::default()
171            .label(Line::from(self.period).centered())
172            .bars(&bars)
173    }
Source

pub fn right_aligned(self) -> Self

Right-aligns this line of text.

Convenience shortcut for Line::alignment(Alignment::Right). Setting the alignment of a Line generally overrides the alignment of its parent Text or Widget, with the default alignment being inherited from the parent.

§Examples
use ratatui::text::Line;

let line = Line::from("Hi, what's up?").right_aligned();
Examples found in repository?
examples/block.rs (line 166)
162fn render_multiple_title_positions(paragraph: &Paragraph, frame: &mut Frame, area: Rect) {
163    let block = Block::bordered()
164        .title(Line::from("top left").left_aligned())
165        .title(Line::from("top center").centered())
166        .title(Line::from("top right").right_aligned())
167        .title_bottom(Line::from("bottom left").left_aligned())
168        .title_bottom(Line::from("bottom center").centered())
169        .title_bottom(Line::from("bottom right").right_aligned());
170    frame.render_widget(paragraph.clone().block(block), area);
171}
More examples
Hide additional examples
examples/async.rs (line 230)
226    fn render(self, area: Rect, buf: &mut Buffer) {
227        let mut state = self.state.write().unwrap();
228
229        // a block with a right aligned title with the loading state on the right
230        let loading_state = Line::from(format!("{:?}", state.loading_state)).right_aligned();
231        let block = Block::bordered()
232            .title("Pull Requests")
233            .title(loading_state)
234            .title_bottom("j/k to scroll, q to quit");
235
236        // a table with the list of pull requests
237        let rows = state.pull_requests.iter();
238        let widths = [
239            Constraint::Length(5),
240            Constraint::Fill(1),
241            Constraint::Max(49),
242        ];
243        let table = Table::new(rows, widths)
244            .block(block)
245            .highlight_spacing(HighlightSpacing::Always)
246            .highlight_symbol(">>")
247            .row_highlight_style(Style::new().on_blue());
248
249        StatefulWidget::render(table, area, buf, &mut state.table_state);
250    }
Source

pub fn width(&self) -> usize

Returns the width of the underlying string.

§Examples
use ratatui::{style::Stylize, text::Line};

let line = Line::from(vec!["Hello".blue(), " world!".green()]);
assert_eq!(12, line.width());
Examples found in repository?
examples/custom_widget.rs (line 138)
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    }
Source

pub fn styled_graphemes<S: Into<Style>>( &'a self, base_style: S, ) -> impl Iterator<Item = StyledGrapheme<'a>>

Returns an iterator over the graphemes held by this line.

base_style is the Style that will be patched with each grapheme Style to get the resulting Style.

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

§Examples
use std::iter::Iterator;

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

let line = Line::styled("Text", Style::default().fg(Color::Yellow));
let style = Style::default().fg(Color::Green).bg(Color::Black);
assert_eq!(
    line.styled_graphemes(style)
        .collect::<Vec<StyledGrapheme>>(),
    vec![
        StyledGrapheme::new("T", Style::default().fg(Color::Yellow).bg(Color::Black)),
        StyledGrapheme::new("e", Style::default().fg(Color::Yellow).bg(Color::Black)),
        StyledGrapheme::new("x", Style::default().fg(Color::Yellow).bg(Color::Black)),
        StyledGrapheme::new("t", Style::default().fg(Color::Yellow).bg(Color::Black)),
    ]
);
Source

pub fn patch_style<S: Into<Style>>(self, style: S) -> Self

Patches the style of this Line, adding modifiers from the given style.

This is useful for when you want to apply a style to a line that already has some styling. In contrast to Line::style, this method will not overwrite the existing style, but instead will add the given style’s modifiers to this Line’s style.

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

This is a fluent setter method which must be chained or used as it consumes self

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

let line = Line::styled("My text", Modifier::ITALIC);

let styled_line = Line::styled("My text", (Color::Yellow, Modifier::ITALIC));

assert_eq!(styled_line, line.patch_style(Color::Yellow));
Source

pub fn reset_style(self) -> Self

Resets the style of this Line.

Equivalent to calling patch_style(Style::reset()).

This is a fluent setter method which must be chained or used as it consumes self

§Examples
use ratatui::{
    style::{Style, Stylize},
    text::Line,
};

let line = Line::styled("My text", style);

assert_eq!(Style::reset(), line.reset_style().style);
Source

pub fn iter(&self) -> Iter<'_, Span<'a>>

Returns an iterator over the spans of this line.

Source

pub fn iter_mut(&mut self) -> IterMut<'_, Span<'a>>

Returns a mutable iterator over the spans of this line.

Source

pub fn push_span<T: Into<Span<'a>>>(&mut self, span: T)

Adds a span to the line.

span can be any type that is convertible into a Span. For example, you can pass a &str, a String, or a Span.

§Examples
use ratatui::text::{Line, Span};

let mut line = Line::from("Hello, ");
line.push_span(Span::raw("world!"));
line.push_span(" How are you?");

Trait Implementations§

Source§

impl<'a> Add<Line<'a>> for Text<'a>

Source§

type Output = Text<'a>

The resulting type after applying the + operator.
Source§

fn add(self, line: Line<'a>) -> Self::Output

Performs the + operation. Read more
Source§

impl<'a> Add<Span<'a>> for Line<'a>

Adds a Span to a Line, returning a new Line with the Span added.

Source§

type Output = Line<'a>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Span<'a>) -> Self::Output

Performs the + operation. Read more
Source§

impl<'a> Add for Line<'a>

Adds two Lines together, returning a new Text with the contents of the two Lines.

Source§

type Output = Text<'a>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Self) -> Self::Output

Performs the + operation. Read more
Source§

impl<'a> AddAssign<Line<'a>> for Text<'a>

Source§

fn add_assign(&mut self, line: Line<'a>)

Performs the += operation. Read more
Source§

impl<'a> AddAssign<Span<'a>> for Line<'a>

Source§

fn add_assign(&mut self, rhs: Span<'a>)

Performs the += operation. Read more
Source§

impl<'a> Clone for Line<'a>

Source§

fn clone(&self) -> Line<'a>

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 Line<'_>

Source§

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

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

impl<'a> Default for Line<'a>

Source§

fn default() -> Line<'a>

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

impl Display for Line<'_>

Source§

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

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

impl<'a> Extend<Span<'a>> for Line<'a>

Source§

fn extend<T: IntoIterator<Item = Span<'a>>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<'a> From<&'a str> for Line<'a>

Source§

fn from(s: &'a str) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<Cow<'a, str>> for Line<'a>

Source§

fn from(s: Cow<'a, str>) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<Line<'a>> for String

Source§

fn from(line: Line<'a>) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<Line<'a>> for Text<'a>

Source§

fn from(line: Line<'a>) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<Span<'a>> for Line<'a>

Source§

fn from(span: Span<'a>) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<String> for Line<'a>

Source§

fn from(s: String) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<Vec<Span<'a>>> for Line<'a>

Source§

fn from(spans: Vec<Span<'a>>) -> Self

Converts to this type from the input type.
Source§

impl<'a, T> FromIterator<T> for Line<'a>
where T: Into<Span<'a>>,

Source§

fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl<'a> Hash for Line<'a>

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<'a> IntoIterator for &'a Line<'a>

Source§

type Item = &'a Span<'a>

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, Span<'a>>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for &'a mut Line<'a>

Source§

type Item = &'a mut Span<'a>

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, Span<'a>>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for Line<'a>

Source§

type Item = Span<'a>

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<Span<'a>>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> PartialEq for Line<'a>

Source§

fn eq(&self, other: &Line<'a>) -> 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<'a> Styled for Line<'a>

Source§

type Item = Line<'a>

Source§

fn style(&self) -> Style

Returns the style of the object.
Source§

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

Sets the style of the object. Read more
Source§

impl Widget for Line<'_>

Source§

fn render(self, area: Rect, buf: &mut Buffer)

Draws the current state of the widget in the given buffer. That is the only method required to implement a custom widget.
Source§

impl WidgetRef for Line<'_>

Source§

fn render_ref(&self, area: Rect, buf: &mut Buffer)

Available on crate feature unstable-widget-ref only.
Draws the current state of the widget in the given buffer. That is the only method required to implement a custom widget.
Source§

impl<'a> Eq for Line<'a>

Source§

impl<'a> StructuralPartialEq for Line<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for Line<'a>

§

impl<'a> RefUnwindSafe for Line<'a>

§

impl<'a> Send for Line<'a>

§

impl<'a> Sync for Line<'a>

§

impl<'a> Unpin for Line<'a>

§

impl<'a> UnwindSafe for Line<'a>

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> ToCompactString for T
where T: Display,

Source§

impl<T> ToLine for T
where T: Display,

Source§

fn to_line(&self) -> Line<'_>

Converts the value to a Line.
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> ToSpan for T
where T: Display,

Source§

fn to_span(&self) -> Span<'_>

Converts the value to a Span.
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T> ToText for T
where T: Display,

Source§

fn to_text(&self) -> Text<'_>

Converts the value to a Text.
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.