Skip to main content

Text

Struct Text 

Source
pub struct Text { /* private fields */ }
Expand description

Rich text with styled spans.

Text is the primary way to work with styled content in Rich. It stores plain text with a list of spans that define styled regions.

§Example

use rich_rs::Text;
use rich_rs::Style;

let mut text = Text::plain("Hello, World!");
text.stylize(0, 5, Style::new().with_bold(true));
text.stylize(7, 12, Style::new().with_italic(true));

Implementations§

Source§

impl Text

Source

pub fn new() -> Self

Create new empty text.

Source

pub fn plain(text: impl Into<String>) -> Self

Create text from a plain string.

Source

pub fn styled(text: impl Into<String>, style: Style) -> Self

Create text with a style applied to the entire content.

Note: Unlike creating Text::plain and then calling stylize(), this sets the base style which affects the entire text including any padding added later. The base style is applied as a background to all spans during rendering.

Source

pub fn styled_with_meta( text: impl Into<String>, style: Style, meta: StyleMeta, ) -> Self

Create text with a base style and base metadata applied to the entire content.

Source

pub fn from_markup(markup: &str, emoji: bool) -> Result<Text>

Create text from markup string.

Parses BBCode-like markup (e.g., [bold red]text[/]) into styled Text.

§Arguments
  • markup - The markup string to parse.
  • emoji - Whether to replace emoji codes (:smile: -> actual emoji).
§Returns

A Text object with styled spans, or an error if the markup is invalid.

§Example
use rich_rs::Text;

let text = Text::from_markup("[bold]Hello[/] World", true).unwrap();
assert_eq!(text.plain_text(), "Hello World");
Source

pub fn from_ansi(ansi_text: &str) -> Text

Create a Text object from a string containing ANSI escape codes.

This is a port of Python Rich’s Text.from_ansi, backed by AnsiDecoder. The decoder is lenient and will ignore unknown / malformed escape sequences.

Style state may persist across lines, matching Rich behavior.

Source

pub fn assemble<I, P>(parts: I) -> Self
where I: IntoIterator<Item = P>, P: Into<TextPart>,

Assemble text from multiple parts.

Each part can be:

  • A plain string (&str or String)
  • A Text object
  • A tuple of (text, Style)
§Example
use rich_rs::{Text, TextPart, Style};

let bold = Style::new().with_bold(true);
let text = Text::assemble([
    TextPart::from("Hello, "),
    TextPart::from(("World", bold)),
    TextPart::from("!"),
]);
assert_eq!(text.plain_text(), "Hello, World!");
Source

pub fn plain_text(&self) -> &str

Get the plain text content.

Source

pub fn cell_len(&self) -> usize

Get the cell width of the text.

Source

pub fn len(&self) -> usize

Get the character count.

Source

pub fn is_empty(&self) -> bool

Check if the text is empty.

Source

pub fn append(&mut self, text: impl Into<String>, style: Option<Style>)

Append text with an optional style.

Source

pub fn append_text(&mut self, other: &Text)

Append another Text object, preserving its spans and base style.

Source

pub fn stylize(&mut self, start: usize, end: usize, style: Style)

Apply a style to a range of the text (legacy API, kept for compatibility).

Spans are clamped to the text bounds. Out-of-bounds or empty spans are ignored. For the enhanced version with negative index support, use stylize_range.

Source

pub fn stylize_range(&mut self, style: Style, start: isize, end: Option<isize>)

Apply a style to a range of the text with negative index support.

Negative indices count from the end of the text (-1 is the last character). If end is None, styles to the end of the text.

§Arguments
  • style - The style to apply.
  • start - Start offset (negative indexing supported). Defaults to 0.
  • end - End offset (negative indexing supported), or None for end of text.
§Example
use rich_rs::{Text, Style};

let mut text = Text::plain("Hello World");
// Style the last 5 characters
text.stylize_range(Style::new().with_bold(true), -5, None);
Source

pub fn stylize_before(&mut self, style: Style, start: isize, end: Option<isize>)

Apply a style to the text, inserting at the beginning of the spans list.

Styles applied with stylize_before have lower priority than existing styles. This is useful for adding a base style that existing styles can override.

§Arguments
  • style - The style to apply.
  • start - Start offset (negative indexing supported). Defaults to 0.
  • end - End offset (negative indexing supported), or None for end of text.
Source

pub fn apply_meta( &mut self, meta: BTreeMap<String, MetaValue>, start: isize, end: Option<isize>, )

Apply metadata to the text (or a range), using a metadata-only span.

Negative indices count from the end of the text (-1 is the last character). If end is None, metadata is applied to the end of the text.

Source

pub fn highlight_regex(&mut self, pattern: &str, style: Style) -> usize

Highlight text matching a regular expression.

§Arguments
  • pattern - A regular expression pattern.
  • style - The style to apply to matches.
§Returns

The number of matches found.

§Example
use rich_rs::{Text, Style};

let mut text = Text::plain("foo bar foo baz");
let count = text.highlight_regex(r"foo", Style::new().with_bold(true));
assert_eq!(count, 2);
Source

pub fn highlight_words( &mut self, words: &[&str], style: Style, case_sensitive: bool, ) -> usize

Highlight occurrences of specific words.

§Arguments
  • words - Words to highlight.
  • style - The style to apply.
  • case_sensitive - Whether matching should be case-sensitive.
§Returns

The number of words highlighted.

§Example
use rich_rs::{Text, Style};

let mut text = Text::plain("Hello World Hello");
let count = text.highlight_words(&["Hello"], Style::new().with_bold(true), true);
assert_eq!(count, 2);
Source

pub fn divide(&self, offsets: impl IntoIterator<Item = usize>) -> Vec<Text>

Divide text at multiple offsets.

This is a critical algorithm for text wrapping. It splits the text at the given character offsets and correctly distributes spans across the resulting Text objects.

§Arguments
  • offsets - Character offsets at which to divide the text.
§Returns

A vector of Text objects, one for each division.

§Example
use rich_rs::Text;

let text = Text::plain("Hello World!");
let divided = text.divide([5, 6]);
assert_eq!(divided.len(), 3);
assert_eq!(divided[0].plain_text(), "Hello");
assert_eq!(divided[1].plain_text(), " ");
assert_eq!(divided[2].plain_text(), "World!");
Source

pub fn spans(&self) -> &[Span]

Get the spans.

Source

pub fn spans_mut(&mut self) -> &mut Vec<Span>

Get mutable access to spans.

Source

pub fn base_style(&self) -> Option<Style>

Get the base style.

Source

pub fn set_base_style(&mut self, style: Option<Style>)

Set the base style.

Source

pub fn copy(&self) -> Text

Create a copy of this text.

Source

pub fn blank_copy(&self, plain: &str) -> Text

Create a blank copy with same metadata but no content.

Source

pub fn join<I>(&self, texts: I) -> Text
where I: IntoIterator<Item = Text>,

Join multiple Text objects with this text as separator.

Source

pub fn pad_right(&self, width: usize) -> Text

Pad text on the right to reach target cell width.

Returns a new Text with spaces appended to reach the target width. If the text is already wider than width, returns a clone unchanged.

§Example
use rich_rs::Text;

let text = Text::plain("hello");
let padded = text.pad_right(10);
assert_eq!(padded.plain_text(), "hello     ");
assert_eq!(padded.cell_len(), 10);
Source

pub fn pad_left(&self, width: usize) -> Text

Pad text on the left to reach target cell width.

Returns a new Text with spaces prepended to reach the target width. Existing spans are shifted by the padding amount.

§Example
use rich_rs::Text;

let text = Text::plain("hello");
let padded = text.pad_left(10);
assert_eq!(padded.plain_text(), "     hello");
assert_eq!(padded.cell_len(), 10);
Source

pub fn center(&self, width: usize) -> Text

Center text within a given cell width.

Returns a new Text padded on both sides to center within the width. Left padding is (width - cell_len) / 2, right padding fills the rest.

§Example
use rich_rs::Text;

let text = Text::plain("hi");
let centered = text.center(6);
assert_eq!(centered.plain_text(), "  hi  ");
assert_eq!(centered.cell_len(), 6);
Source

pub fn expand_tabs(&self, tab_size: usize) -> Text

Expand tabs to spaces.

Returns a new Text with tabs replaced by spaces, aligning to tab stops.

§Arguments
  • tab_size - The tab stop width (default 8).
§Example
use rich_rs::Text;

let text = Text::plain("a\tb");
let expanded = text.expand_tabs(4);
assert_eq!(expanded.plain_text(), "a   b");
Source

pub fn with_indent_guides( self, indent_size: usize, style: Option<Style>, ) -> Text

Add indentation guides to the text.

This adds visual indentation guides (like vertical lines) to show the indentation level of each line.

§Arguments
  • indent_size - The number of spaces per indentation level.
  • style - Optional style for the guide characters.
§Returns

A new Text with indentation guides added.

Source

pub fn rstrip(&self) -> Text

Strip trailing whitespace from the text.

Returns a new Text with trailing whitespace removed. Spans are adjusted to fit within the new text bounds.

Source

pub fn rstrip_end(&self, size: usize) -> Text

Remove trailing whitespace beyond a certain width.

Only removes whitespace characters that extend beyond the target size. This is used after wrapping to clean up trailing spaces on lines.

§Arguments
  • size - The desired cell width target.
Source

pub fn truncate( &self, max_width: usize, overflow: OverflowMethod, pad: bool, ) -> Text

Truncate text to fit within a cell width.

§Arguments
  • max_width - Maximum cell width.
  • overflow - How to handle overflow (Fold, Crop, Ellipsis).
  • pad - If true, pad with spaces if text is shorter than max_width.
Source

pub fn split( &self, separator: &str, include_separator: bool, allow_blank: bool, ) -> Vec<Text>

Split text on a separator into a list of Text objects.

§Arguments
  • separator - The string to split on.
  • include_separator - If true, include the separator at the end of each line.
  • allow_blank - If true, include a blank line if text ends with separator.
§Returns

A vector of Text objects, one per split segment.

Source

pub fn wrap( &self, width: usize, justify: Option<JustifyMethod>, overflow: Option<OverflowMethod>, tab_size: usize, no_wrap: bool, ) -> Vec<Text>

Wrap text to fit within a given width.

This method word-wraps the text to fit within the specified cell width, applying justification and handling overflow as specified.

§Arguments
  • width - Maximum width in cells.
  • justify - Text justification (None for no justification).
  • overflow - How to handle words longer than width.
  • tab_size - Tab stop width (default 8).
  • no_wrap - If true, don’t wrap (just return self).
§Returns

A vector of Text objects, one per wrapped line.

§Example
use rich_rs::{Text, OverflowMethod};

let text = Text::plain("hello world this is a test");
let lines = text.wrap(10, None, Some(OverflowMethod::Fold), 8, false);
assert!(lines.len() >= 3);
Source§

impl Text

Source

pub fn slice(&self, start: usize, end: usize) -> Text

Return a sub-Text from character offsets start..end with correctly adjusted spans.

This is the equivalent of Python’s text[start:end]. Spans that partially overlap the range are clipped. Spans fully outside are dropped.

Source

pub fn align(&mut self, align: JustifyMethod, width: usize)

Align text within width: left (pad right), center (pad both sides), right (pad left), full (distribute spaces between words).

Source

pub fn contains(&self, text: &str) -> bool

Check if the plain text contains a substring.

Source

pub fn to_markup(&self) -> String

Reconstruct a markup string from the styled text.

For each span, wraps the text range in [style]...[/style] tags.

Source

pub fn get_style_at_offset(&self, offset: usize) -> Style

Get the combined style at a specific character offset by combining all overlapping spans.

Source

pub fn set_length(&mut self, length: usize)

Truncate or pad (with spaces) to exact character length.

Source

pub fn right_crop(&mut self, amount: usize)

Remove amount characters from the right side.

Source

pub fn fit(&self, width: usize) -> Vec<Text>

Fit text to width by splitting on newlines, then setting each line to exact width.

Source

pub fn remove_suffix(&mut self, suffix: &str)

Remove suffix from the text if present.

Source

pub fn extend_style(&mut self, count: usize)

Extend the last span’s style to cover count more characters.

Source

pub fn detect_indentation(&self) -> usize

Detect the common indentation level.

Source

pub fn copy_styles(&mut self, other: &Text)

Copy spans from another Text onto this one (direct copy, no offset adjustment).

Source

pub fn append_tokens<I, S>(&mut self, tokens: I)
where I: IntoIterator<Item = (S, Option<Style>)>, S: AsRef<str>,

Append an iterable of (content, style) tokens.

Control codes are stripped from each token before appending, matching append behavior.

Source

pub fn with_indent_guides_full( &self, indent_size: Option<usize>, character: &str, style: Style, ) -> Text

Implement real indent guide rendering.

Scans for leading whitespace and replaces indent positions with the guide character in the given style.

Trait Implementations§

Source§

impl Add<&str> for Text

Source§

type Output = Text

The resulting type after applying the + operator.
Source§

fn add(self, rhs: &str) -> Text

Performs the + operation. Read more
Source§

impl Add for Text

Source§

type Output = Text

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Text) -> Text

Performs the + operation. Read more
Source§

impl Clone for Text

Source§

fn clone(&self) -> Text

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Text

Source§

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

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

impl Default for Text

Source§

fn default() -> Text

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

impl From<&str> for Text

Source§

fn from(s: &str) -> Self

Converts to this type from the input type.
Source§

impl From<String> for Text

Source§

fn from(s: String) -> Self

Converts to this type from the input type.
Source§

impl From<Text> for TextPart

Source§

fn from(t: Text) -> Self

Converts to this type from the input type.
Source§

impl Renderable for Text

Implement Renderable for Text.

This converts Text to Segments for rendering to the terminal.

Source§

fn render(&self, _console: &Console, options: &ConsoleOptions) -> Segments

Render this object to a sequence of segments.
Source§

fn measure(&self, _console: &Console, options: &ConsoleOptions) -> Measurement

Measure the minimum and maximum width requirements. Read more

Auto Trait Implementations§

§

impl Freeze for Text

§

impl RefUnwindSafe for Text

§

impl Send for Text

§

impl Sync for Text

§

impl Unpin for Text

§

impl UnwindSafe for Text

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<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

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

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.