[go: up one dir, main page]

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.

use ratatui::prelude::*;

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
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 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 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
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
fn ui(f: &mut Frame, app: &App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),
            Constraint::Length(3),
            Constraint::Min(1),
        ])
        .split(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 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(
                // Draw the cursor at the current position in the input field.
                // This position is can be controlled via the left and right arrow key
                chunks[1].x + app.cursor_position 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<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>>> for Text<'a>

source§

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

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

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

§

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

§

type Output = T

Should always be Self
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, 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.