Skip to main content

Text

Struct Text 

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

Styled text. Mirrors rich.text.Text.

Implementations§

Source§

impl Text

Source

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

Plain, unstyled text.

Source

pub fn styled(plain: impl Into<String>, style: impl Into<StyleType>) -> Self

Text with a base style, which may be a style name resolved at render time (Text::styled("hi", "repr.number")) or a resolved Style.

Source

pub fn justify(self, justify: Justify) -> Self

Set how lines are justified within the render width (builder form).

Source

pub fn set_justify(&mut self, justify: Justify)

Set how lines are justified within the render width.

Justify::Default means unset here (upstream’s justify=None), deferring to the console options; use set_justify_option for an explicit justify="default".

Source

pub fn get_justify(&self) -> Justify

This text’s own justify method (Justify::Default when unset).

Source

pub fn set_justify_option(&mut self, justify: Option<Justify>)

Set this text’s justify, distinguishing an explicit Some(Justify::Default) (upstream’s justify="default", which a table column’s or the print call’s justify does not override) from None (upstream’s justify=None, which defers to them).

Source

pub fn get_justify_option(&self) -> Option<Justify>

This text’s own justify, None when unset. See set_justify_option.

Source

pub fn overflow(self, overflow: Overflow) -> Self

Set what happens to lines wider than the render width (builder form).

Source

pub fn set_overflow(&mut self, overflow: Option<Overflow>)

Set what happens to lines wider than the render width. Pass None to defer to the console options.

Source

pub fn get_overflow(&self) -> Option<Overflow>

This text’s own overflow method, if it set one.

Source

pub fn no_wrap(self, no_wrap: bool) -> Self

Disable (or re-enable) wrapping for this text (builder form).

Source

pub fn set_no_wrap(&mut self, no_wrap: Option<bool>)

Disable (or re-enable) wrapping. Pass None to defer to the console options.

Source

pub fn get_no_wrap(&self) -> Option<bool>

This text’s own no-wrap setting, if it set one.

Source

pub fn tab_size(self, tab_size: usize) -> Self

Set the tab stop width (builder form). Port of Text(tab_size=…).

Source

pub fn set_tab_size(&mut self, tab_size: Option<usize>)

Set the tab stop width. Pass None to defer to the console’s tab_size. Upstream’s Text.tab_size attribute.

Source

pub fn get_tab_size(&self) -> Option<usize>

This text’s own tab stop width, if it set one.

Source

pub fn truncate( &mut self, max_width: usize, overflow: Option<Overflow>, pad: bool, )

Shorten this text to at most max_width cells, optionally padding it out to exactly max_width when it is shorter. Port of Text.truncate.

overflow defaults to this text’s own method, then to Overflow::Fold; Overflow::Ignore leaves the text alone entirely. Note that Fold and Crop behave identically here — folding is a property of wrapping, and a line that has already been wrapped can only be cut.

Source

pub fn blank_copy(&self) -> Text

An empty Text carrying this one’s style, justify, overflow and no-wrap. Port of Text.blank_copy.

Source

pub fn divide(&self, offsets: &[usize]) -> Vec<Text>

Cut this text at each byte offset in offsets, returning the pieces. Port of Text.divide.

Every piece inherits the base style, justify, overflow and no-wrap, and each span is re-based onto the pieces it covers. Spans that would come out empty are dropped, matching upstream’s new_end > new_start.

Offsets are byte offsets (as everywhere else in this port’s span arithmetic) and must fall on char boundaries.

Source

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

Split on separator. Port of Text.split.

include_separator keeps the separator at the end of each piece. allow_blank keeps the trailing empty piece that a text ending in the separator would otherwise produce.

§Panics

If separator is empty, which upstream asserts against.

Source

pub fn pad(&mut self, count: usize, character: char)

Pad both sides with count copies of character. Port of Text.pad.

Source

pub fn pad_left(&mut self, count: usize, character: char)

Pad the left with count copies of character, shifting every span to follow the text. Port of Text.pad_left.

Source

pub fn pad_right(&mut self, count: usize, character: char)

Pad the right with count copies of character. Port of Text.pad_right. Spans are untouched, so the padding is unstyled.

Source

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

Drop the last amount bytes, clipping any span that reached into them. Port of Text.right_crop.

Source

pub fn rstrip(&mut self)

Remove trailing whitespace. Port of Text.rstrip.

Source

pub fn rstrip_end(&mut self, size: usize)

Remove only as much trailing whitespace as it takes to get down to size characters, leaving the rest. Port of Text.rstrip_end.

This is what lets a wrapped line keep the space that ended it while a line that overshot the width gives its padding back. As upstream, the length is len(self) — characters, not cells.

Source

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

Append count spaces, extending any span that reached the end so the padding takes its style. Port of Text.extend_style.

Source

pub fn expand_tabs(&mut self, tab_size: usize)

Replace tabs with spaces up to the next tab_size stop. Port of Text.expand_tabs.

Styles extend over the inserted spaces, so a styled tab pads in its own style rather than punching an unstyled hole (upstream reaches the same result via extend_style).

Source

pub fn join(&self, lines: &[Text]) -> Text

Join lines with this text as the separator, carrying each piece’s base style across as a covering span. Port of Text.join.

Source

pub fn from_ansi(text: &str, style: impl Into<StyleType>) -> Text

A Text from a string containing ANSI escape codes, one decoded line per line joined by newlines, with base style. Port of Text.from_ansi (its tab_size defaults to 8; set justify, overflow and no_wrap with the builders).

Source

pub fn detect_indentation(&self) -> usize

The indentation unit of the text: the greatest common divisor of its even line indents, or 1. Port of Text.detect_indentation.

Source

pub fn with_indent_guides( &self, indent_size: Option<usize>, character: &str, style: impl Into<StyleType>, ) -> Text

A copy with indent guides drawn in each line’s leading spaces: every indent_size spaces (auto-detected for None) become character then padding, styled style. Port of Text.with_indent_guides (upstream’s defaults are "│" and "dim green").

Source

pub fn highlight_words( &mut self, words: &[&str], style: impl Into<StyleType>, case_sensitive: bool, ) -> Result<usize>

Style every occurrence of any of words. Port of Text.highlight_words, returning the number of matches.

Source

pub fn highlight_regex( &mut self, pattern: &str, style: Option<StyleType>, style_prefix: &str, ) -> Result<usize>

Style every match of pattern, returning the number of matches. Full port of Text.highlight_regex.

style, when given, styles the whole match. Each named group is then styled with {style_prefix}{name} as a style name, left for the theme to resolve at render time — which is how a highlighter colours its groups without ever seeing a console.

Groups that did not participate in the match, and zero-width ones, are skipped.

Source

pub fn from_markup(markup_text: &str) -> Result<Text>

Build styled text from console markup. Port of Text.from_markup.

Tag names are stored on the spans and resolved when the text is rendered, so no theme is needed here. :emoji: codes are replaced, as upstream’s default emoji=True does.

Source

pub fn from_markup_with( markup_text: &str, style: impl Into<StyleType>, emoji: bool, emoji_variant: Option<EmojiVariant>, ) -> Result<Text>

Text from console markup with a base style, :emoji: codes replaced when emoji is set. Port of Text.from_markup(text, style=…, emoji=…, emoji_variant=…); set justify, overflow and end with the builders.

Source

pub fn markup(&self) -> String

Console markup that renders this text: the plain string with every tag-opening [ escaped, and a tag around each span and the base style. Port of the Text.markup property.

As upstream, tags are emitted in (offset, closing) order with the base style outermost, so at a shared offset every opening tag precedes every closing one, and a falsy style (a null Style or an empty name) adds no tag. A resolved style is written as its Style::definition.

Source

pub fn assemble<P: Into<TextPart>>( parts: impl IntoIterator<Item = P>, style: impl Into<StyleType>, ) -> Text

Text assembled from parts, under a base style. Port of Text.assemble (set justify, overflow, no_wrap and tab_size with the builders, and meta with apply_meta).

Source

pub fn set_plain_text(&mut self, plain: &str)

Replace the plain string. Port of the Text.plain setter: control codes are stripped, and when the text gets shorter, spans past the new end are dropped and the rest clipped to it.

Source

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

Whether needle occurs in the plain text. Port of Text.__contains__ (pass a Text’s plain for a Text).

Source

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

The text from byte start to byte end, with its spans. Port of Text.__getitem__ with a slice (text[start:end]).

Source

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

Remove suffix from the end, if the text ends with it. Port of Text.remove_suffix.

Source

pub fn get_style_at_offset(&self, console: &Console, offset: isize) -> Style

The style at byte offset (from the end when negative): the base style combined with every span covering it, resolved against console’s theme. Port of Text.get_style_at_offset.

Source

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

Pad or crop to exactly new_length bytes. Port of Text.set_length (padding with spaces, which are one byte each).

Source

pub fn align(&mut self, align: HorizontalAlign, width: usize, character: char)

Truncate to width cells, then pad with character to align the text left, center or right (any other value is right). Port of Text.align.

Source

pub fn append_tokens<S: Into<StyleType>>( &mut self, tokens: impl IntoIterator<Item = (String, Option<S>)>, ) -> &mut Self

Append (content, style) tokens, faster than appending one at a time. Port of Text.append_tokens.

Source

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

Add the spans of text to this one, unchanged. Port of Text.copy_styles.

Source

pub fn fit(&self, width: usize) -> Lines

One line per line of the text, each padded or cropped to width bytes. Port of Text.fit.

Source

pub fn wrap( &self, console: &Console, width: usize, justify: Option<Justify>, overflow: Option<Overflow>, tab_size: usize, no_wrap: Option<bool>, ) -> Lines

Word-wrap into lines no wider than width cells, justified and overflowed. Port of Text.wrap: justify, overflow and no_wrap fall back to the text’s own, then to the defaults.

Source

pub fn get_end(&self) -> &str

What a printed Text ends with: a newline unless set otherwise. Upstream’s Text.end. Containers in this port always break lines between renderables (DIVERGENCES §29), so only callers that join texts themselves see it.

Source

pub fn end(self, end: impl Into<String>) -> Self

Set what the text ends with. Upstream’s Text(end=…).

Source

pub fn plain(&self) -> &str

The unstyled string content.

Source

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

The spans currently applied.

Source

pub fn cell_len(&self) -> usize

Length in terminal cells.

Source

pub fn is_empty(&self) -> bool

True when there is no content.

Source

pub fn append(&mut self, text: &str, style: Option<StyleType>)

Append more text, optionally under style (a resolved Style or a style name).

Source

pub fn append_text(self, other: &Text) -> Text

Append another Text, carrying over its base style (as a covering span) and all of its spans, shifted to their new offsets. Port of Text.append_text. Consumes self and returns it for chaining.

Source

pub fn stylize(&mut self, style: impl Into<StyleType>, start: usize, end: usize)

Apply style to the byte range [start, end). Port of Text.stylize, including its argument order.

style may be a resolved Style or a name ("repr.number") left for the renderer to look up. Byte offsets, not char offsets; ASCII-only callers such as highlighters are unaffected by the distinction.

A range that is empty or inverted is ignored, which is what gives us upstream’s end > start skip for non-participating regex groups.

Source

pub fn stylize_before( &mut self, style: impl Into<StyleType>, start: usize, end: usize, )

As stylize, but the span goes first, beneath every existing span. Port of Text.stylize_before.

Source

pub fn apply_meta(&mut self, meta: Meta, start: usize, end: Option<usize>)

Apply metadata to the byte range start..end (the rest of the text when end is None). Port of Text.apply_meta: a span of Style.from_meta(meta), which an empty map (a null style) skips.

Source

pub fn on( &mut self, meta: Option<Meta>, handlers: &[(&str, MetaValue)], ) -> &mut Self

Apply event-handler metadata to the whole text. Port of Text.on: handlers are stored as "@name" keys over meta.

Source

pub fn push_span(&mut self, span: Span)

Append a raw span, as upstream’s text.spans.append(span) does: no clamping and no falsy-style check.

Offsets are byte offsets into plain and must fall on char boundaries (upstream’s are character offsets; convert first). A span may extend past the end of the text, as upstream allows.

Source

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

The spans, mutably. Upstream’s Text.spans is a public, mutable list; the same byte-offset rules as push_span apply.

Source

pub fn set_spans(&mut self, spans: Vec<Span>)

Replace every span. Port of the Text.spans setter.

Source

pub fn base_style(&self) -> &StyleType

The whole-text base style, resolved or named. Port of the Text.style attribute.

Source

pub fn set_base_style(&mut self, style: impl Into<StyleType>)

Set the whole-text base style, resolved or named.

Source

pub fn render(&self, theme: &Theme, base_style: &Style) -> Vec<Segment>

Flatten into non-overlapping segments (newlines become Segment::line), combining base_style, this text’s base style, and every covering span. Does not wrap. Port of the core of Text.render.

Named span styles are resolved against theme.

Source

pub fn measurement(&self) -> (usize, usize)

The (minimum, maximum) cell width of this text: maximum is the widest hard line, minimum the widest word. Port of Text.__rich_measure__.

Source

pub fn render_lines( &self, theme: &Theme, base_style: &Style, width: Option<usize>, ) -> Vec<Vec<Segment>>

Render into visual lines, wrapping each hard line to width cells when Some, and justifying per this text’s own justify.

Source

pub fn render_lines_justified( &self, theme: &Theme, base_style: &Style, width: Option<usize>, justify: Justify, ) -> Vec<Vec<Segment>>

Like render_lines but with an explicit justify (used by the console to apply options.justify).

Source

pub fn render_lines_wrapped( &self, theme: &Theme, base_style: &Style, width: Option<usize>, justify: Justify, overflow: Overflow, no_wrap: bool, ) -> Vec<Vec<Segment>>

The full wrap-justify-truncate pipeline, with every knob resolved by the caller. Port of Text.wrap.

Lines are split on \n, wrapped to width (folding over-long words only when overflow is Overflow::Fold), justified, and finally truncated to width. Overflow::Ignore skips wrapping and truncation both, so lines may come back wider than width.

Tabs expand to this text’s own tab_size, else DEFAULT_TAB_SIZE; render_lines_wrapped_tabs takes the width explicitly (upstream’s wrap(tab_size=…)).

Source

pub fn console_tab_size(&self, console: &Console) -> usize

The tab stop width Text.__rich_console__ wraps with on console: this text’s own, else the console’s, and 8 for zero (tab_size or 8).

Source

pub fn render_lines_wrapped_tabs( &self, theme: &Theme, base_style: &Style, width: Option<usize>, justify: Justify, overflow: Overflow, no_wrap: bool, tab_size: usize, ) -> Vec<Vec<Segment>>

render_lines_wrapped with an explicit tab stop width. Port of Text.wrap(…, tab_size=…).

Source

pub fn render_joined_wrapped( &self, theme: &Theme, base_style: &Style, width: usize, justify: Justify, overflow: Overflow, no_wrap: bool, ) -> Vec<Segment>

As render_lines_wrapped, flattened into a single segment stream with Segment::line between visual lines.

Source

pub fn render_joined_wrapped_tabs( &self, theme: &Theme, base_style: &Style, width: usize, justify: Justify, overflow: Overflow, no_wrap: bool, tab_size: usize, ) -> Vec<Segment>

render_joined_wrapped with an explicit tab stop width (see console_tab_size).

Trait Implementations§

Source§

impl Add<&Text> for &Text

text + other: a copy with other appended. Port of Text.__add__.

Source§

type Output = Text

The resulting type after applying the + operator.
Source§

fn add(self, other: &Text) -> Text

Performs the + operation. Read more
Source§

impl Add<&str> for &Text

text + "str". Port of Text.__add__.

Source§

type Output = Text

The resulting type after applying the + operator.
Source§

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

Performs the + operation. Read more
Source§

impl Clone for Text

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · 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() -> Self

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

impl From<Text> for Cell

Source§

fn from(text: Text) -> Self

Converts to this type from the input type.
Source§

impl From<Text> for TextPart

Source§

fn from(text: Text) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for Text

Two texts are equal when their plain strings and spans are. Port of Text.__eq__.

Source§

fn eq(&self, other: &Text) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Renderable for Text

Source§

fn rich_render( &self, console: &Console, options: &ConsoleOptions, ) -> Vec<Segment>

Source§

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

The (minimum, maximum) cell width this renderable wants. Port of __rich_measure__. The default is what upstream’s Measurement.get returns for a renderable without one: anything from nothing to the whole width, (0, max_width).
Source§

fn fit_to_measurement(&self) -> bool

Whether a top-level Console::print shrinks this renderable to its measured width. Upstream renders every top-level renderable at the full console width, so the default is false; an extension may opt in.
Source§

fn vertical(&self) -> Option<VerticalAlign>

The vertical alignment a Table cell holding this renderable uses in place of its column’s. Upstream reads getattr(renderable, "vertical", None); Align sets it.
Source§

fn print_end_line(&self, _options: &ConsoleOptions) -> bool

Whether a top-level print ends this renderable’s last line. This port’s renderables separate lines, where upstream’s end each line with "\n", so a print adds the final line break. A renderable whose upstream output stops without one (Screen, LiveRender, a Rule whose end has no newline) returns false, and the next output continues its last line. options are the print’s options.

Auto Trait Implementations§

§

impl Freeze for Text

§

impl RefUnwindSafe for Text

§

impl Send for Text

§

impl Sync for Text

§

impl Unpin for Text

§

impl UnsafeUnpin 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 = !

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

fn try_from(value: U) -> Result<T, !>

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.