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
impl Text
Sourcepub fn styled(text: impl Into<String>, style: Style) -> Self
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.
Sourcepub fn styled_with_meta(
text: impl Into<String>,
style: Style,
meta: StyleMeta,
) -> Self
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.
Sourcepub fn from_markup(markup: &str, emoji: bool) -> Result<Text>
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");Sourcepub fn from_ansi(ansi_text: &str) -> Text
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.
Sourcepub fn assemble<I, P>(parts: I) -> Self
pub fn assemble<I, P>(parts: I) -> Self
Assemble text from multiple parts.
Each part can be:
- A plain string (
&strorString) - A
Textobject - 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!");Sourcepub fn plain_text(&self) -> &str
pub fn plain_text(&self) -> &str
Get the plain text content.
Sourcepub fn append(&mut self, text: impl Into<String>, style: Option<Style>)
pub fn append(&mut self, text: impl Into<String>, style: Option<Style>)
Append text with an optional style.
Sourcepub fn append_text(&mut self, other: &Text)
pub fn append_text(&mut self, other: &Text)
Append another Text object, preserving its spans and base style.
Sourcepub fn stylize(&mut self, start: usize, end: usize, style: Style)
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.
Sourcepub fn stylize_range(&mut self, style: Style, start: isize, end: Option<isize>)
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), orNonefor 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);Sourcepub fn stylize_before(&mut self, style: Style, start: isize, end: Option<isize>)
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), orNonefor end of text.
Sourcepub fn apply_meta(
&mut self,
meta: BTreeMap<String, MetaValue>,
start: isize,
end: Option<isize>,
)
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.
Sourcepub fn highlight_regex(&mut self, pattern: &str, style: Style) -> usize
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);Sourcepub fn highlight_words(
&mut self,
words: &[&str],
style: Style,
case_sensitive: bool,
) -> usize
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);Sourcepub fn divide(&self, offsets: impl IntoIterator<Item = usize>) -> Vec<Text>
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!");Sourcepub fn base_style(&self) -> Option<Style>
pub fn base_style(&self) -> Option<Style>
Get the base style.
Sourcepub fn set_base_style(&mut self, style: Option<Style>)
pub fn set_base_style(&mut self, style: Option<Style>)
Set the base style.
Sourcepub fn blank_copy(&self, plain: &str) -> Text
pub fn blank_copy(&self, plain: &str) -> Text
Create a blank copy with same metadata but no content.
Sourcepub fn join<I>(&self, texts: I) -> Textwhere
I: IntoIterator<Item = Text>,
pub fn join<I>(&self, texts: I) -> Textwhere
I: IntoIterator<Item = Text>,
Join multiple Text objects with this text as separator.
Sourcepub fn pad_right(&self, width: usize) -> Text
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);Sourcepub fn pad_left(&self, width: usize) -> Text
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);Sourcepub fn center(&self, width: usize) -> Text
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);Sourcepub fn expand_tabs(&self, tab_size: usize) -> Text
pub fn expand_tabs(&self, tab_size: usize) -> Text
Sourcepub fn with_indent_guides(
self,
indent_size: usize,
style: Option<Style>,
) -> Text
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.
Sourcepub fn rstrip(&self) -> Text
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.
Sourcepub fn rstrip_end(&self, size: usize) -> Text
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.
Sourcepub fn truncate(
&self,
max_width: usize,
overflow: OverflowMethod,
pad: bool,
) -> Text
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.
Sourcepub fn split(
&self,
separator: &str,
include_separator: bool,
allow_blank: bool,
) -> Vec<Text>
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.
Sourcepub fn wrap(
&self,
width: usize,
justify: Option<JustifyMethod>,
overflow: Option<OverflowMethod>,
tab_size: usize,
no_wrap: bool,
) -> Vec<Text>
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
impl Text
Sourcepub fn slice(&self, start: usize, end: usize) -> Text
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.
Sourcepub fn align(&mut self, align: JustifyMethod, width: usize)
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).
Sourcepub fn to_markup(&self) -> String
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.
Sourcepub fn get_style_at_offset(&self, offset: usize) -> Style
pub fn get_style_at_offset(&self, offset: usize) -> Style
Get the combined style at a specific character offset by combining all overlapping spans.
Sourcepub fn set_length(&mut self, length: usize)
pub fn set_length(&mut self, length: usize)
Truncate or pad (with spaces) to exact character length.
Sourcepub fn right_crop(&mut self, amount: usize)
pub fn right_crop(&mut self, amount: usize)
Remove amount characters from the right side.
Sourcepub fn fit(&self, width: usize) -> Vec<Text>
pub fn fit(&self, width: usize) -> Vec<Text>
Fit text to width by splitting on newlines, then setting each line to exact width.
Sourcepub fn remove_suffix(&mut self, suffix: &str)
pub fn remove_suffix(&mut self, suffix: &str)
Remove suffix from the text if present.
Sourcepub fn extend_style(&mut self, count: usize)
pub fn extend_style(&mut self, count: usize)
Extend the last span’s style to cover count more characters.
Sourcepub fn detect_indentation(&self) -> usize
pub fn detect_indentation(&self) -> usize
Detect the common indentation level.
Sourcepub fn copy_styles(&mut self, other: &Text)
pub fn copy_styles(&mut self, other: &Text)
Copy spans from another Text onto this one (direct copy, no offset adjustment).
Sourcepub fn append_tokens<I, S>(&mut self, tokens: I)
pub fn append_tokens<I, S>(&mut self, tokens: I)
Append an iterable of (content, style) tokens.
Control codes are stripped from each token before appending, matching append behavior.
Trait Implementations§
Source§impl Renderable for Text
Implement Renderable for Text.
impl Renderable for Text
Implement Renderable for Text.
This converts Text to Segments for rendering to the terminal.