Struct ratatui::text::Text

source ·
pub struct Text<'a> {
    pub lines: Vec<Line<'a>>,
}
Expand description

A string split over multiple lines where each line is composed of several clusters, each with their own style.

A Text, like a Span, 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.

let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);

// An initial two lines of `Text` built from a `&str`
let mut text = Text::from("The first line\nThe second line");
assert_eq!(2, text.height());

// Adding two more unstyled lines
text.extend(Text::raw("These are two\nmore lines!"));
assert_eq!(4, text.height());

// Adding a final two styled lines
text.extend(Text::styled("Some more lines\nnow with more style!", style));
assert_eq!(6, text.height());

Fields§

§lines: Vec<Line<'a>>

Implementations§

source§

impl<'a> Text<'a>

source

pub fn raw<T>(content: T) -> Text<'a>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>(content: T, style: Style) -> Text<'a>where T: Into<Cow<'a, str>>,

Create some text (potentially multiple lines) with a 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
use ratatui::text::Text;
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
use ratatui::text::Text;
let text = Text::from("The first line\nThe second line");
assert_eq!(2, text.height());
source

pub fn patch_style(&mut self, style: Style)

Patches the style of each line in an existing Text, adding modifiers from the given style.

Examples
let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
let mut raw_text = Text::raw("The first line\nThe second line");
let styled_text = Text::styled(String::from("The first line\nThe second line"), style);
assert_ne!(raw_text, styled_text);

raw_text.patch_style(style);
assert_eq!(raw_text, styled_text);
Examples found in repository?
examples/user_input.rs (line 154)
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
185
186
187
188
189
190
191
192
193
fn ui<B: Backend>(f: &mut Frame<B>, app: &App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(2)
        .constraints(
            [
                Constraint::Length(1),
                Constraint::Length(3),
                Constraint::Min(1),
            ]
            .as_ref(),
        )
        .split(f.size());

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

    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, chunks[1]);
    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
            f.set_cursor(
                // Put cursor past the end of the input text
                chunks[1].x + app.input.width() as u16 + 1,
                // Move one line down, from the border to the input line
                chunks[1].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, chunks[2]);
}
source

pub fn reset_style(&mut self)

Resets the style of the Text. Equivalent to calling patch_style(Style::reset()).

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

text.reset_style();
for line in &text.lines {
    for span in &line.spans {
        assert_eq!(Style::reset(), span.style);
    }
}

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

Converts to this type from the input type.
source§

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

source§

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

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

Converts to this type from the input type.
source§

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

source§

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

Converts to this type from the input type.
source§

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

source§

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

Converts to this type from the input type.
source§

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

source§

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

Converts to this type from the input type.
source§

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

source§

fn from(spans: Spans<'a>) -> Text<'a>

Converts to this type from the input type.
source§

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

source§

fn from(s: String) -> Text<'a>

Converts to this type from the input type.
source§

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

source§

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

Converts to this type from the input type.
source§

impl<'a> From<Vec<Spans<'a>, Global>> for Text<'a>

source§

fn from(lines: Vec<Spans<'a>>) -> Text<'a>

Converts to this type from the input type.
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, Global>

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

source§

impl<'a> StructuralEq for Text<'a>

source§

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

Auto Trait Implementations§

§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. 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 Twhere 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> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for Twhere 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, U> TryFrom<U> for Twhere 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 Twhere 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.