Struct ratatui::text::Line

source ·
pub struct Line<'a> {
    pub spans: Vec<Span<'a>>,
    pub style: Style,
    pub alignment: Option<Alignment>,
}
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).

§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::prelude::*;

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.

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.

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.

// 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.

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

Fields§

§spans: Vec<Span<'a>>

The spans that make up this line of text.

§style: Style

The style of this line of text.

§alignment: Option<Alignment>

The alignment of 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
Line::raw("test content");
Line::raw(String::from("test content"));
Line::raw(Cow::from("test content"));
Examples found in repository?
examples/tabs.rs (line 156)
155
156
157
158
159
fn render_footer(area: Rect, buf: &mut Buffer) {
    Line::raw("◄ ► to change tab | Press q to quit")
        .centered()
        .render(area, buf);
}
More examples
Hide additional examples
examples/flex.rs (line 487)
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
    fn render_spacer(spacer: Rect, buf: &mut Buffer) {
        if spacer.width > 1 {
            let corners_only = symbols::border::Set {
                top_left: line::NORMAL.top_left,
                top_right: line::NORMAL.top_right,
                bottom_left: line::NORMAL.bottom_left,
                bottom_right: line::NORMAL.bottom_right,
                vertical_left: " ",
                vertical_right: " ",
                horizontal_top: " ",
                horizontal_bottom: " ",
            };
            Block::bordered()
                .border_set(corners_only)
                .border_style(Style::reset().dark_gray())
                .render(spacer, buf);
        } else {
            Paragraph::new(Text::from(vec![
                Line::from(""),
                Line::from("│"),
                Line::from("│"),
                Line::from(""),
            ]))
            .style(Style::reset().dark_gray())
            .render(spacer, buf);
        }
        let width = spacer.width;
        let label = if width > 4 {
            format!("{width} px")
        } else if width > 2 {
            format!("{width}")
        } else {
            String::new()
        };
        let text = Text::from(vec![
            Line::raw(""),
            Line::raw(""),
            Line::styled(label, Style::reset().dark_gray()),
        ]);
        Paragraph::new(text)
            .style(Style::reset().dark_gray())
            .alignment(Alignment::Center)
            .render(spacer, buf);
    }
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. 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.

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/constraint-explorer.rs (line 558)
548
549
550
551
552
553
554
555
556
557
558
559
    fn label(width: u16) -> impl Widget {
        let long_label = format!("{width} px");
        let short_label = format!("{width}");
        let label = if long_label.len() < width as usize {
            long_label
        } else if short_label.len() < width as usize {
            short_label
        } else {
            String::new()
        };
        Line::styled(label, Self::TEXT_COLOR).centered()
    }
More examples
Hide additional examples
examples/list.rs (line 343)
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
    fn to_list_item(&self, index: usize) -> ListItem {
        let bg_color = match index % 2 {
            0 => NORMAL_ROW_COLOR,
            _ => ALT_ROW_COLOR,
        };
        let line = match self.status {
            Status::Todo => Line::styled(format!(" ☐ {}", self.todo), TEXT_COLOR),
            Status::Completed => Line::styled(
                format!(" ✓ {}", self.todo),
                (COMPLETED_TEXT_COLOR, bg_color),
            ),
        };

        ListItem::new(line).bg(bg_color)
    }
examples/flex.rs (line 489)
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
    fn render_spacer(spacer: Rect, buf: &mut Buffer) {
        if spacer.width > 1 {
            let corners_only = symbols::border::Set {
                top_left: line::NORMAL.top_left,
                top_right: line::NORMAL.top_right,
                bottom_left: line::NORMAL.bottom_left,
                bottom_right: line::NORMAL.bottom_right,
                vertical_left: " ",
                vertical_right: " ",
                horizontal_top: " ",
                horizontal_bottom: " ",
            };
            Block::bordered()
                .border_set(corners_only)
                .border_style(Style::reset().dark_gray())
                .render(spacer, buf);
        } else {
            Paragraph::new(Text::from(vec![
                Line::from(""),
                Line::from("│"),
                Line::from("│"),
                Line::from(""),
            ]))
            .style(Style::reset().dark_gray())
            .render(spacer, buf);
        }
        let width = spacer.width;
        let label = if width > 4 {
            format!("{width} px")
        } else if width > 2 {
            format!("{width}")
        } else {
            String::new()
        };
        let text = Text::from(vec![
            Line::raw(""),
            Line::raw(""),
            Line::styled(label, Style::reset().dark_gray()),
        ]);
        Paragraph::new(text)
            .style(Style::reset().dark_gray())
            .alignment(Alignment::Center)
            .render(spacer, buf);
    }
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
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
let mut line = Line::from("foo").style(Style::new().red());
Examples found in repository?
examples/demo2/app.rs (line 198)
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
    fn render_bottom_bar(area: Rect, buf: &mut Buffer) {
        let keys = [
            ("H/←", "Left"),
            ("L/→", "Right"),
            ("K/↑", "Up"),
            ("J/↓", "Down"),
            ("D/Del", "Destroy"),
            ("Q/Esc", "Quit"),
        ];
        let spans = keys
            .iter()
            .flat_map(|(key, desc)| {
                let key = Span::styled(format!(" {key} "), THEME.key_binding.key);
                let desc = Span::styled(format!(" {desc} "), THEME.key_binding.description);
                [key, desc]
            })
            .collect_vec();
        Line::from(spans)
            .centered()
            .style((Color::Indexed(236), Color::Indexed(232)))
            .render(area, buf);
    }
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
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
let line = Line::from("Hi, what's up?").left_aligned();
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
let line = Line::from("Hi, what's up?").centered();
Examples found in repository?
examples/tabs.rs (line 157)
155
156
157
158
159
fn render_footer(area: Rect, buf: &mut Buffer) {
    Line::raw("◄ ► to change tab | Press q to quit")
        .centered()
        .render(area, buf);
}
More examples
Hide additional examples
examples/demo2/app.rs (line 197)
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
    fn render_bottom_bar(area: Rect, buf: &mut Buffer) {
        let keys = [
            ("H/←", "Left"),
            ("L/→", "Right"),
            ("K/↑", "Up"),
            ("J/↓", "Down"),
            ("D/Del", "Destroy"),
            ("Q/Esc", "Quit"),
        ];
        let spans = keys
            .iter()
            .flat_map(|(key, desc)| {
                let key = Span::styled(format!(" {key} "), THEME.key_binding.key);
                let desc = Span::styled(format!(" {desc} "), THEME.key_binding.description);
                [key, desc]
            })
            .collect_vec();
        Line::from(spans)
            .centered()
            .style((Color::Indexed(236), Color::Indexed(232)))
            .render(area, buf);
    }
examples/constraint-explorer.rs (line 318)
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
    fn swap_legend() -> impl Widget {
        #[allow(unstable_name_collisions)]
        Paragraph::new(
            Line::from(
                [
                    ConstraintName::Min,
                    ConstraintName::Max,
                    ConstraintName::Length,
                    ConstraintName::Percentage,
                    ConstraintName::Ratio,
                    ConstraintName::Fill,
                ]
                .iter()
                .enumerate()
                .map(|(i, name)| {
                    format!("  {i}: {name}  ", i = i + 1)
                        .fg(SLATE.c200)
                        .bg(name.color())
                })
                .intersperse(Span::from(" "))
                .collect_vec(),
            )
            .centered(),
        )
        .wrap(Wrap { trim: false })
    }

    /// A bar like `<----- 80 px (gap: 2 px) ----->`
    ///
    /// Only shows the gap when spacing is not zero
    fn axis(&self, width: u16) -> impl Widget {
        let label = if self.spacing != 0 {
            format!("{} px (gap: {} px)", width, self.spacing)
        } else {
            format!("{width} px")
        };
        let bar_width = width.saturating_sub(2) as usize; // we want to `<` and `>` at the ends
        let width_bar = format!("<{label:-^bar_width$}>");
        Paragraph::new(width_bar).fg(Self::AXIS_COLOR).centered()
    }

    fn render_layout_blocks(&self, area: Rect, buf: &mut Buffer) {
        let [user_constraints, area] = Layout::vertical([Length(3), Fill(1)])
            .spacing(1)
            .areas(area);

        self.render_user_constraints_legend(user_constraints, buf);

        let [start, center, end, space_around, space_between] =
            Layout::vertical([Length(7); 5]).areas(area);

        self.render_layout_block(Flex::Start, start, buf);
        self.render_layout_block(Flex::Center, center, buf);
        self.render_layout_block(Flex::End, end, buf);
        self.render_layout_block(Flex::SpaceAround, space_around, buf);
        self.render_layout_block(Flex::SpaceBetween, space_between, buf);
    }

    fn render_user_constraints_legend(&self, area: Rect, buf: &mut Buffer) {
        let blocks = Layout::horizontal(
            self.constraints
                .iter()
                .map(|_| Constraint::Fill(1))
                .collect_vec(),
        )
        .split(area);

        for (i, (area, constraint)) in blocks.iter().zip(self.constraints.iter()).enumerate() {
            let selected = self.selected_index == i;
            ConstraintBlock::new(*constraint, selected, true).render(*area, buf);
        }
    }

    fn render_layout_block(&self, flex: Flex, area: Rect, buf: &mut Buffer) {
        let [label_area, axis_area, blocks_area] =
            Layout::vertical([Length(1), Max(1), Length(4)]).areas(area);

        if label_area.height > 0 {
            format!("Flex::{flex:?}").bold().render(label_area, buf);
        }

        self.axis(area.width).render(axis_area, buf);

        let (blocks, spacers) = Layout::horizontal(&self.constraints)
            .flex(flex)
            .spacing(self.spacing)
            .split_with_spacers(blocks_area);

        for (i, (area, constraint)) in blocks.iter().zip(self.constraints.iter()).enumerate() {
            let selected = self.selected_index == i;
            ConstraintBlock::new(*constraint, selected, false).render(*area, buf);
        }

        for area in spacers.iter() {
            SpacerBlock.render(*area, buf);
        }
    }
}

impl Widget for ConstraintBlock {
    fn render(self, area: Rect, buf: &mut Buffer) {
        match area.height {
            1 => self.render_1px(area, buf),
            2 => self.render_2px(area, buf),
            _ => self.render_4px(area, buf),
        }
    }
}

impl ConstraintBlock {
    const TEXT_COLOR: Color = SLATE.c200;

    const fn new(constraint: Constraint, selected: bool, legend: bool) -> Self {
        Self {
            constraint,
            legend,
            selected,
        }
    }

    fn label(&self, width: u16) -> String {
        let long_width = format!("{width} px");
        let short_width = format!("{width}");
        // border takes up 2 columns
        let available_space = width.saturating_sub(2) as usize;
        let width_label = if long_width.len() < available_space {
            long_width
        } else if short_width.len() < available_space {
            short_width
        } else {
            String::new()
        };
        format!("{}\n{}", self.constraint, width_label)
    }

    fn render_1px(&self, area: Rect, buf: &mut Buffer) {
        let lighter_color = ConstraintName::from(self.constraint).lighter_color();
        let main_color = ConstraintName::from(self.constraint).color();
        let selected_color = if self.selected {
            lighter_color
        } else {
            main_color
        };
        Block::default()
            .fg(Self::TEXT_COLOR)
            .bg(selected_color)
            .render(area, buf);
    }

    fn render_2px(&self, area: Rect, buf: &mut Buffer) {
        let lighter_color = ConstraintName::from(self.constraint).lighter_color();
        let main_color = ConstraintName::from(self.constraint).color();
        let selected_color = if self.selected {
            lighter_color
        } else {
            main_color
        };
        Block::bordered()
            .border_set(symbols::border::QUADRANT_OUTSIDE)
            .border_style(Style::reset().fg(selected_color).reversed())
            .render(area, buf);
    }

    fn render_4px(&self, area: Rect, buf: &mut Buffer) {
        let lighter_color = ConstraintName::from(self.constraint).lighter_color();
        let main_color = ConstraintName::from(self.constraint).color();
        let selected_color = if self.selected {
            lighter_color
        } else {
            main_color
        };
        let color = if self.legend {
            selected_color
        } else {
            main_color
        };
        let label = self.label(area.width);
        let block = Block::bordered()
            .border_set(symbols::border::QUADRANT_OUTSIDE)
            .border_style(Style::reset().fg(color).reversed())
            .fg(Self::TEXT_COLOR)
            .bg(color);
        Paragraph::new(label)
            .centered()
            .fg(Self::TEXT_COLOR)
            .bg(color)
            .block(block)
            .render(area, buf);

        if !self.legend {
            let border_color = if self.selected {
                lighter_color
            } else {
                main_color
            };
            if let Some(last_row) = area.rows().last() {
                buf.set_style(last_row, border_color);
            }
        }
    }
}

impl Widget for SpacerBlock {
    fn render(self, area: Rect, buf: &mut Buffer) {
        match area.height {
            1 => (),
            2 => Self::render_2px(area, buf),
            3 => Self::render_3px(area, buf),
            _ => Self::render_4px(area, buf),
        }
    }
}

impl SpacerBlock {
    const TEXT_COLOR: Color = SLATE.c500;
    const BORDER_COLOR: Color = SLATE.c600;

    /// A block with a corner borders
    fn block() -> impl Widget {
        let corners_only = symbols::border::Set {
            top_left: line::NORMAL.top_left,
            top_right: line::NORMAL.top_right,
            bottom_left: line::NORMAL.bottom_left,
            bottom_right: line::NORMAL.bottom_right,
            vertical_left: " ",
            vertical_right: " ",
            horizontal_top: " ",
            horizontal_bottom: " ",
        };
        Block::bordered()
            .border_set(corners_only)
            .border_style(Self::BORDER_COLOR)
    }

    /// A vertical line used if there is not enough space to render the block
    fn line() -> impl Widget {
        Paragraph::new(Text::from(vec![
            Line::from(""),
            Line::from("│"),
            Line::from("│"),
            Line::from(""),
        ]))
        .style(Self::BORDER_COLOR)
    }

    /// A label that says "Spacer" if there is enough space
    fn spacer_label(width: u16) -> impl Widget {
        let label = if width >= 6 { "Spacer" } else { "" };
        label.fg(Self::TEXT_COLOR).into_centered_line()
    }

    /// A label that says "8 px" if there is enough space
    fn label(width: u16) -> impl Widget {
        let long_label = format!("{width} px");
        let short_label = format!("{width}");
        let label = if long_label.len() < width as usize {
            long_label
        } else if short_label.len() < width as usize {
            short_label
        } else {
            String::new()
        };
        Line::styled(label, Self::TEXT_COLOR).centered()
    }
examples/barchart.rs (line 207)
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
fn create_groups<'a>(app: &'a App, combine_values_and_labels: bool) -> Vec<BarGroup<'a>> {
    app.months
        .iter()
        .enumerate()
        .map(|(i, &month)| {
            let bars: Vec<Bar> = app
                .companies
                .iter()
                .map(|c| {
                    let mut bar = Bar::default()
                        .value(c.revenue[i])
                        .style(c.bar_style)
                        .value_style(
                            Style::default()
                                .bg(c.bar_style.fg.unwrap())
                                .fg(Color::Black),
                        );

                    if combine_values_and_labels {
                        bar = bar.text_value(format!(
                            "{} ({:.1} M)",
                            c.label,
                            (c.revenue[i] as f64) / 1000.
                        ));
                    } else {
                        bar = bar
                            .text_value(format!("{:.1}", (c.revenue[i] as f64) / 1000.))
                            .label(c.label.into());
                    }
                    bar
                })
                .collect();
            BarGroup::default()
                .label(Line::from(month).centered())
                .bars(&bars)
        })
        .collect()
}
examples/layout.rs (line 83)
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
fn ui(frame: &mut Frame) {
    let vertical = Layout::vertical([
        Length(4),  // text
        Length(50), // examples
        Min(0),     // fills remaining space
    ]);
    let [text_area, examples_area, _] = vertical.areas(frame.size());

    // title
    frame.render_widget(
        Paragraph::new(vec![
            Line::from("Horizontal Layout Example. Press q to quit".dark_gray()).centered(),
            Line::from("Each line has 2 constraints, plus Min(0) to fill the remaining space."),
            Line::from("E.g. the second line of the Len/Min box is [Length(2), Min(2), Min(0)]"),
            Line::from("Note: constraint labels that don't fit are truncated"),
        ]),
        text_area,
    );

    let example_rows = Layout::vertical([
        Length(9),
        Length(9),
        Length(9),
        Length(9),
        Length(9),
        Min(0), // fills remaining space
    ])
    .split(examples_area);
    let example_areas = example_rows
        .iter()
        .flat_map(|area| {
            Layout::horizontal([
                Length(14),
                Length(14),
                Length(14),
                Length(14),
                Length(14),
                Min(0), // fills remaining space
            ])
            .split(*area)
            .iter()
            .copied()
            .take(5) // ignore Min(0)
            .collect_vec()
        })
        .collect_vec();

    // the examples are a cartesian product of the following constraints
    // e.g. Len/Len, Len/Min, Len/Max, Len/Perc, Len/Ratio, Min/Len, Min/Min, ...
    let examples = [
        (
            "Len",
            vec![
                Length(0),
                Length(2),
                Length(3),
                Length(6),
                Length(10),
                Length(15),
            ],
        ),
        (
            "Min",
            vec![Min(0), Min(2), Min(3), Min(6), Min(10), Min(15)],
        ),
        (
            "Max",
            vec![Max(0), Max(2), Max(3), Max(6), Max(10), Max(15)],
        ),
        (
            "Perc",
            vec![
                Percentage(0),
                Percentage(25),
                Percentage(50),
                Percentage(75),
                Percentage(100),
                Percentage(150),
            ],
        ),
        (
            "Ratio",
            vec![
                Ratio(0, 4),
                Ratio(1, 4),
                Ratio(2, 4),
                Ratio(3, 4),
                Ratio(4, 4),
                Ratio(6, 4),
            ],
        ),
    ];

    for (i, (a, b)) in examples
        .iter()
        .cartesian_product(examples.iter())
        .enumerate()
    {
        let (name_a, examples_a) = a;
        let (name_b, examples_b) = b;
        let constraints = examples_a
            .iter()
            .copied()
            .zip(examples_b.iter().copied())
            .collect_vec();
        render_example_combination(
            frame,
            example_areas[i],
            &format!("{name_a}/{name_b}"),
            constraints,
        );
    }
}
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
let line = Line::from("Hi, what's up?").right_aligned();
source

pub fn width(&self) -> usize

Returns the width of the underlying string.

§Examples
let line = Line::from(vec!["Hello".blue(), " world!".green()]);
assert_eq!(12, line.width());
Examples found in repository?
examples/custom_widget.rs (line 119)
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
    fn render(self, area: Rect, buf: &mut Buffer) {
        let (background, text, shadow, highlight) = self.colors();
        buf.set_style(area, Style::new().bg(background).fg(text));

        // render top line if there's enough space
        if area.height > 2 {
            buf.set_string(
                area.x,
                area.y,
                "▔".repeat(area.width as usize),
                Style::new().fg(highlight).bg(background),
            );
        }
        // render bottom line if there's enough space
        if area.height > 1 {
            buf.set_string(
                area.x,
                area.y + area.height - 1,
                "▁".repeat(area.width as usize),
                Style::new().fg(shadow).bg(background),
            );
        }
        // render label centered
        buf.set_line(
            area.x + (area.width.saturating_sub(self.label.width() as u16)) / 2,
            area.y + (area.height.saturating_sub(1)) / 2,
            &self.label,
            area.width,
        );
    }
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::{prelude::*, text::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)),
    ]
);
Examples found in repository?
examples/demo2/big_text.rs (line 141)
138
139
140
141
142
143
144
145
    fn render(self, area: Rect, buf: &mut Buffer) {
        let layout = layout(area, self.pixel_size);
        for (line, line_layout) in self.lines.iter().zip(layout) {
            for (g, cell) in line.styled_graphemes(self.style).zip(line_layout) {
                render_symbol(&g, cell, buf, self.pixel_size);
            }
        }
    }
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
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
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
let mut line = Line::from("Hello, ");
line.push_span(Span::raw("world!"));
line.push_span(" How are you?");

Trait Implementations§

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

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> 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<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>

§

type Item = &'a Span<'a>

The type of the elements being iterated over.
§

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>

§

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

The type of the elements being iterated over.
§

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>

§

type Item = Span<'a>

The type of the elements being iterated over.
§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method 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>

§

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<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
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<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

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

Checks if this value is equivalent to the given key. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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> Same for T

§

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(self, color: Color) -> T

source§

fn fg<S>(self, color: S) -> T
where S: 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§

fn to_compact_string(&self) -> CompactString

Converts the given value to a CompactString. Read more
source§

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

§

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> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

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

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

§

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>,

§

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.