Struct ratatui::text::Text

source ·
pub struct Text<'a> {
    pub lines: Vec<Line<'a>>,
    pub style: Style,
    pub alignment: Option<Alignment>,
}
Expand description

A string split over one or more lines.

Text is used wherever text is displayed in the terminal and represents one or more Lines of text. When a Text is rendered, each line is rendered as a single line of text from top to bottom of the area. The text can be styled and aligned.

§Constructor Methods

  • Text::raw creates a Text (potentially multiple lines) with no style.
  • Text::styled creates a Text (potentially multiple lines) with a style.
  • Text::default creates a Text with empty content and the default style.

§Conversion Methods

§Setter Methods

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

§Iteration Methods

§Other Methods

§Examples

§Creating Text

A Text, like a Line, can be constructed using one of the many From implementations or via the Text::raw and Text::styled methods. Helpfully, Text also implements core::iter::Extend which enables the concatenation of several Text blocks.

use std::{borrow::Cow, iter};

use ratatui::prelude::*;

let style = Style::new().yellow().italic();
let text = Text::raw("The first line\nThe second line").style(style);
let text = Text::styled("The first line\nThe second line", style);
let text = Text::styled(
    "The first line\nThe second line",
    (Color::Yellow, Modifier::ITALIC),
);

let text = Text::from("The first line\nThe second line");
let text = Text::from(String::from("The first line\nThe second line"));
let text = Text::from(Cow::Borrowed("The first line\nThe second line"));
let text = Text::from(Span::styled("The first line\nThe second line", style));
let text = Text::from(Line::from("The first line"));
let text = Text::from(vec![
    Line::from("The first line"),
    Line::from("The second line"),
]);
let text = Text::from_iter(iter::once("The first line").chain(iter::once("The second line")));

let mut text = Text::default();
text.extend(vec![
    Line::from("The first line"),
    Line::from("The second line"),
]);
text.extend(Text::from("The third line\nThe fourth line"));

§Styling Text

The text’s Style is used by the rendering widget to determine how to style the text. Each Line in the text will be styled with the Style of the text, and then with its own Style. Text also implements Styled which means you can use the methods of the Stylize trait.

let text = Text::from("The first line\nThe second line").style(Style::new().yellow().italic());
let text = Text::from("The first line\nThe second line")
    .yellow()
    .italic();
let text = Text::from(vec![
    Line::from("The first line").yellow(),
    Line::from("The second line").yellow(),
])
.italic();

§Aligning Text

The text’s Alignment can be set using Text::alignment or the related helper methods. Lines composing the text can also be individually aligned with Line::alignment.

let text = Text::from("The first line\nThe second line").alignment(Alignment::Right);
let text = Text::from("The first line\nThe second line").right_aligned();
let text = Text::from(vec![
    Line::from("The first line").left_aligned(),
    Line::from("The second line").right_aligned(),
    Line::from("The third line"),
])
.centered();

§Rendering Text

Text implements the Widget trait, which means it can be rendered to a Buffer or to a Frame.

// within another widget's `render` method:
let text = Text::from("The first line\nThe second line");
text.render(area, buf);

// within a terminal.draw closure:
let text = Text::from("The first line\nThe second line");
frame.render_widget(text, area);

§Rendering Text with a Paragraph Widget

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

let text = Text::from("The first line\nThe second line");
let paragraph = Paragraph::new(text)
    .wrap(Wrap { trim: true })
    .scroll((1, 1))
    .render(area, buf);

Fields§

§lines: Vec<Line<'a>>

The lines that make up this piece of text.

§style: Style

The style of this text.

§alignment: Option<Alignment>

The alignment of this text.

Implementations§

source§

impl<'a> Text<'a>

source

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

Create some text (potentially multiple lines) with no style.

§Examples
Text::raw("The first line\nThe second line");
Text::raw(String::from("The first line\nThe second line"));
source

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

Create some text (potentially multiple lines) with a style.

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

§Examples
let style = Style::default()
    .fg(Color::Yellow)
    .add_modifier(Modifier::ITALIC);
Text::styled("The first line\nThe second line", style);
Text::styled(String::from("The first line\nThe second line"), style);
source

pub fn width(&self) -> usize

Returns the max width of all the lines.

§Examples
let text = Text::from("The first line\nThe second line");
assert_eq!(15, text.width());
source

pub fn height(&self) -> usize

Returns the height.

§Examples
let text = Text::from("The first line\nThe second line");
assert_eq!(2, text.height());
source

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

Sets the style of this text.

Defaults to Style::default().

Note: This field was added in v0.26.0. Prior to that, the style of a text was determined only by the style of each Line 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 = Text::from("foo").style(Style::new().red());
source

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

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

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

Text also implements Styled which means you can use the methods of the Stylize trait.

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 raw_text = Text::styled("The first line\nThe second line", Modifier::ITALIC);
let styled_text = Text::styled(
    String::from("The first line\nThe second line"),
    (Color::Yellow, Modifier::ITALIC),
);
assert_ne!(raw_text, styled_text);

let raw_text = raw_text.patch_style(Color::Yellow);
assert_eq!(raw_text, styled_text);
Examples found in repository?
examples/user_input.rs (line 220)
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
fn ui(f: &mut Frame, app: &App) {
    let vertical = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(3),
        Constraint::Min(1),
    ]);
    let [help_area, input_area, messages_area] = vertical.areas(f.size());

    let (msg, style) = match app.input_mode {
        InputMode::Normal => (
            vec![
                "Press ".into(),
                "q".bold(),
                " to exit, ".into(),
                "e".bold(),
                " to start editing.".bold(),
            ],
            Style::default().add_modifier(Modifier::RAPID_BLINK),
        ),
        InputMode::Editing => (
            vec![
                "Press ".into(),
                "Esc".bold(),
                " to stop editing, ".into(),
                "Enter".bold(),
                " to record the message".into(),
            ],
            Style::default(),
        ),
    };
    let text = Text::from(Line::from(msg)).patch_style(style);
    let help_message = Paragraph::new(text);
    f.render_widget(help_message, help_area);

    let input = Paragraph::new(app.input.as_str())
        .style(match app.input_mode {
            InputMode::Normal => Style::default(),
            InputMode::Editing => Style::default().fg(Color::Yellow),
        })
        .block(Block::default().borders(Borders::ALL).title("Input"));
    f.render_widget(input, input_area);
    match app.input_mode {
        InputMode::Normal =>
            // Hide the cursor. `Frame` does this by default, so we don't need to do anything here
            {}

        InputMode::Editing => {
            // Make the cursor visible and ask ratatui to put it at the specified coordinates after
            // rendering
            #[allow(clippy::cast_possible_truncation)]
            f.set_cursor(
                // Draw the cursor at the current position in the input field.
                // This position is can be controlled via the left and right arrow key
                input_area.x + app.cursor_position as u16 + 1,
                // Move one line down, from the border to the input line
                input_area.y + 1,
            );
        }
    }

    let messages: Vec<ListItem> = app
        .messages
        .iter()
        .enumerate()
        .map(|(i, m)| {
            let content = Line::from(Span::raw(format!("{i}: {m}")));
            ListItem::new(content)
        })
        .collect();
    let messages =
        List::new(messages).block(Block::default().borders(Borders::ALL).title("Messages"));
    f.render_widget(messages, messages_area);
}
source

pub fn reset_style(self) -> Self

Resets the style of the Text.

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 text = Text::styled(
    "The first line\nThe second line",
    (Color::Yellow, Modifier::ITALIC),
);

let text = text.reset_style();
assert_eq!(Style::reset(), text.style);
source

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

Sets the alignment for this text.

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

Alignment can be set individually on each line to override this text’s alignment.

§Examples

Set alignment to the whole text.

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

Set a default alignment and override it on a per line basis.

let text = Text::from(vec![
    Line::from("left").alignment(Alignment::Left),
    Line::from("default"),
    Line::from("default"),
    Line::from("right").alignment(Alignment::Right),
])
.alignment(Alignment::Center);

Will render the following

left
  default
  default
      right
source

pub fn left_aligned(self) -> Self

Left-aligns the whole text.

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

Alignment can be set individually on each line to override this text’s alignment.

§Examples
let text = Text::from("Hi, what's up?").left_aligned();
source

pub fn centered(self) -> Self

Center-aligns the whole text.

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

Alignment can be set individually on each line to override this text’s alignment.

§Examples
let text = Text::from("Hi, what's up?").centered();
Examples found in repository?
examples/colors_rgb.rs (line 149)
143
144
145
146
147
148
149
150
151
152
153
    fn render(self, area: Rect, buf: &mut Buffer) {
        #[allow(clippy::enum_glob_use)]
        use Constraint::*;
        let [top, colors] = Layout::vertical([Length(1), Min(0)]).areas(area);
        let [title, fps] = Layout::horizontal([Min(0), Length(8)]).areas(top);
        Text::from("colors_rgb example. Press q to quit")
            .centered()
            .render(title, buf);
        self.fps_widget.render(fps, buf);
        self.colors_widget.render(colors, buf);
    }
source

pub fn right_aligned(self) -> Self

Right-aligns the whole text.

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

Alignment can be set individually on each line to override this text’s alignment.

§Examples
let text = Text::from("Hi, what's up?").right_aligned();
source

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

Returns an iterator over the lines of the text.

source

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

Returns an iterator that allows modifying each line.

source

pub fn push_line<T: Into<Line<'a>>>(&mut self, line: T)

Adds a line to the text.

line can be any type that can be converted into a Line. For example, you can pass a &str, a String, a Span, or a Line.

§Examples
let mut text = Text::from("Hello, world!");
text.push_line(Line::from("How are you?"));
text.push_line(Span::from("How are you?"));
text.push_line("How are you?");
source

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

Adds a span to the last line of the text.

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 text = Text::from("Hello, world!");
text.push_span(Span::from("How are you?"));
text.push_span("How are you?");

Trait Implementations§

source§

impl<'a> Clone for Text<'a>

source§

fn clone(&self) -> Text<'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 Text<'a>

source§

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

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

impl<'a> Default for Text<'a>

source§

fn default() -> Text<'a>

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

impl Display for Text<'_>

source§

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

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

impl<'a, T> Extend<T> for Text<'a>
where T: Into<Line<'a>>,

source§

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

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 Masked<'_>> for Text<'a>

source§

fn from(masked: &'a Masked<'_>) -> Self

Converts to this type from the input type.
source§

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

source§

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

Converts to this type from the input type.
source§

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

source§

fn from(s: Cow<'a, str>) -> 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<Masked<'a>> for Text<'a>

source§

fn from(masked: Masked<'a>) -> Self

Converts to this type from the input type.
source§

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

source§

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

Converts to this type from the input type.
source§

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

source§

fn from(s: String) -> Self

Converts to this type from the input type.
source§

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

source§

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

Converts to this type from the input type.
source§

impl<'a, T> FromIterator<T> for Text<'a>
where T: Into<Line<'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 Text<'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 Text<'a>

§

type Item = &'a Line<'a>

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, Line<'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 Text<'a>

§

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

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a, Line<'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 Text<'a>

§

type Item = Line<'a>

The type of the elements being iterated over.
§

type IntoIter = IntoIter<<Text<'a> as IntoIterator>::Item>

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 Text<'a>

source§

fn eq(&self, other: &Text<'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 Text<'a>

§

type Item = Text<'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 Text<'_>

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

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 Text<'a>

source§

impl<'a> StructuralPartialEq for Text<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for Text<'a>

§

impl<'a> RefUnwindSafe for Text<'a>

§

impl<'a> Send for Text<'a>

§

impl<'a> Sync for Text<'a>

§

impl<'a> Unpin for Text<'a>

§

impl<'a> UnwindSafe for Text<'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.