rich.text

class rich.text.Text(text='', style='', *, justify=None, overflow=None, no_wrap=None, end='\n', tab_size=None, spans=None)[source]

Text with color / style.

Parameters
  • text (str, optional) – Default unstyled text. Defaults to “”.

  • style (Union[str, Style], optional) – Base style for text. Defaults to “”.

  • justify (str, optional) – Justify method: “left”, “center”, “full”, “right”. Defaults to None.

  • overflow (str, optional) – Overflow method: “crop”, “fold”, “ellipsis”. Defaults to None.

  • no_wrap (bool, optional) – Disable text wrapping, or None for default. Defaults to None.

  • end (str, optional) – Character to end text with. Defaults to “\n”.

  • tab_size (int) – Number of spaces per tab, or None to use console.tab_size. Defaults to None.

  • spans (List[Span], optional) –

align(align, width, character=' ')[source]

Align text to a given width.

Parameters
  • align (AlignMethod) – One of “left”, “center”, or “right”.

  • width (int) – Desired width.

  • character (str, optional) – Character to pad with. Defaults to ” “.

Return type

None

append(text, style=None)[source]

Add text with an optional style.

Parameters
  • text (Union[Text, str]) – A str or Text to append.

  • style (str, optional) – A style name. Defaults to None.

Returns

Returns self for chaining.

Return type

Text

append_text(text)[source]

Append another Text instance. This method is more performant that Text.append, but only works for Text.

Returns

Returns self for chaining.

Return type

Text

Parameters

text (Text) –

append_tokens(tokens)[source]

Append iterable of str and style. Style may be a Style instance or a str style definition.

Parameters
Returns

Returns self for chaining.

Return type

Text

apply_meta(meta, start=0, end=None)[source]

Apply meta data to the text, or a portion of the text.

Parameters
  • meta (Dict[str, Any]) – A dict of meta information.

  • start (int) – Start offset (negative indexing is supported). Defaults to 0.

  • end (Optional[int], optional) – End offset (negative indexing is supported), or None for end of text. Defaults to None.

Return type

None

classmethod assemble(*parts, style='', justify=None, overflow=None, no_wrap=None, end='\n', tab_size=8, meta=None)[source]

Construct a text instance by combining a sequence of strings with optional styles. The positional arguments should be either strings, or a tuple of string + style.

Parameters
  • style (Union[str, Style], optional) – Base style for text. Defaults to “”.

  • justify (str, optional) – Justify method: “left”, “center”, “full”, “right”. Defaults to None.

  • overflow (str, optional) – Overflow method: “crop”, “fold”, “ellipsis”. Defaults to None.

  • end (str, optional) – Character to end text with. Defaults to “\n”.

  • tab_size (int) – Number of spaces per tab, or None to use console.tab_size. Defaults to None.

  • meta (Dict[str, Any], optional) –

  • parts (Union[str, Text, Tuple[str, Union[str, Style]]]) –

  • no_wrap (Optional[bool]) –

Returns

A new text instance.

Return type

Text

blank_copy(plain='')[source]

Return a new Text instance with copied meta data (but not the string or spans).

Parameters

plain (str) –

Return type

Text

property cell_len: int

Get the number of cells required to render this text.

copy()[source]

Return a copy of this instance.

Return type

Text

copy_styles(text)[source]

Copy styles from another Text instance.

Parameters

text (Text) – A Text instance to copy styles from, must be the same length.

Return type

None

detect_indentation()[source]

Auto-detect indentation of code.

Returns

Number of spaces used to indent code.

Return type

int

divide(offsets)[source]

Divide text in to a number of lines at given offsets.

Parameters

offsets (Iterable[int]) – Offsets used to divide text.

Returns

New RichText instances between offsets.

Return type

Lines

expand_tabs(tab_size=None)[source]

Converts tabs to spaces.

Parameters

tab_size (int, optional) – Size of tabs. Defaults to 8.

Return type

None

extend_style(spaces)[source]

Extend the Text given number of spaces where the spaces have the same style as the last character.

Parameters

spaces (int) – Number of spaces to add to the Text.

Return type

None

fit(width)[source]

Fit the text in to given width by chopping in to lines.

Parameters

width (int) – Maximum characters in a line.

Returns

Lines container.

Return type

Lines

classmethod from_ansi(text, *, style='', justify=None, overflow=None, no_wrap=None, end='\n', tab_size=8)[source]

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

Parameters
  • text (str) – A string containing escape codes.

  • style (Union[str, Style], optional) – Base style for text. Defaults to “”.

  • justify (str, optional) – Justify method: “left”, “center”, “full”, “right”. Defaults to None.

  • overflow (str, optional) – Overflow method: “crop”, “fold”, “ellipsis”. Defaults to None.

  • no_wrap (bool, optional) – Disable text wrapping, or None for default. Defaults to None.

  • end (str, optional) – Character to end text with. Defaults to “\n”.

  • tab_size (int) – Number of spaces per tab, or None to use console.tab_size. Defaults to None.

Return type

Text

classmethod from_markup(text, *, style='', emoji=True, emoji_variant=None, justify=None, overflow=None, end='\n')[source]

Create Text instance from markup.

Parameters
  • text (str) – A string containing console markup.

  • emoji (bool, optional) – Also render emoji code. Defaults to True.

  • justify (str, optional) – Justify method: “left”, “center”, “full”, “right”. Defaults to None.

  • overflow (str, optional) – Overflow method: “crop”, “fold”, “ellipsis”. Defaults to None.

  • end (str, optional) – Character to end text with. Defaults to “\n”.

  • style (Union[str, Style]) –

  • emoji_variant (Optional[typing_extensions.Literal[emoji, text]]) –

Returns

A Text instance with markup rendered.

Return type

Text

get_style_at_offset(console, offset)[source]

Get the style of a character at give offset.

Parameters
  • console (~Console) – Console where text will be rendered.

  • offset (int) – Offset in to text (negative indexing supported)

Returns

A Style instance.

Return type

Style

highlight_regex(re_highlight, style=None, *, style_prefix='')[source]

Highlight text with a regular expression, where group names are translated to styles.

Parameters
  • re_highlight (str) – A regular expression.

  • style (Union[GetStyleCallable, StyleType]) – Optional style to apply to whole match, or a callable which accepts the matched text and returns a style. Defaults to None.

  • style_prefix (str, optional) – Optional prefix to add to style group names.

Returns

Number of regex matches

Return type

int

highlight_words(words, style, *, case_sensitive=True)[source]

Highlight words with a style.

Parameters
  • words (Iterable[str]) – Worlds to highlight.

  • style (Union[str, Style]) – Style to apply.

  • case_sensitive (bool, optional) – Enable case sensitive matchings. Defaults to True.

Returns

Number of words highlighted.

Return type

int

join(lines)[source]

Join text together with this instance as the separator.

Parameters

lines (Iterable[Text]) – An iterable of Text instances to join.

Returns

A new text instance containing join text.

Return type

Text

property markup: str

Get console markup to render this Text.

Returns

A string potentially creating markup tags.

Return type

str

on(meta=None, **handlers)[source]

Apply event handlers (used by Textual project).

Example

>>> from rich.text import Text
>>> text = Text("hello world")
>>> text.on(click="view.toggle('world')")
Parameters
  • meta (Dict[str, Any]) – Mapping of meta information.

  • **handlers – Keyword args are prefixed with “@” to defined handlers.

Returns

Self is returned to method may be chained.

Return type

Text

pad(count, character=' ')[source]

Pad left and right with a given number of characters.

Parameters
  • count (int) – Width of padding.

  • character (str) –

Return type

None

pad_left(count, character=' ')[source]

Pad the left with a given character.

Parameters
  • count (int) – Number of characters to pad.

  • character (str, optional) – Character to pad with. Defaults to ” “.

Return type

None

pad_right(count, character=' ')[source]

Pad the right with a given character.

Parameters
  • count (int) – Number of characters to pad.

  • character (str, optional) – Character to pad with. Defaults to ” “.

Return type

None

property plain: str

Get the text as a single string.

remove_suffix(suffix)[source]

Remove a suffix if it exists.

Parameters

suffix (str) – Suffix to remove.

Return type

None

render(console, end='')[source]

Render the text as Segments.

Parameters
  • console (Console) – Console instance.

  • end (Optional[str], optional) – Optional end character.

Returns

Result of render that may be written to the console.

Return type

Iterable[Segment]

right_crop(amount=1)[source]

Remove a number of characters from the end of the text.

Parameters

amount (int) –

Return type

None

rstrip()[source]

Strip whitespace from end of text.

Return type

None

rstrip_end(size)[source]

Remove whitespace beyond a certain width at the end of the text.

Parameters

size (int) – The desired size of the text.

Return type

None

set_length(new_length)[source]

Set new length of the text, clipping or padding is required.

Parameters

new_length (int) –

Return type

None

property spans: List[Span]

Get a reference to the internal list of spans.

split(separator='\n', *, include_separator=False, allow_blank=False)[source]

Split rich text in to lines, preserving styles.

Parameters
  • separator (str, optional) – String to split on. Defaults to “\n”.

  • include_separator (bool, optional) – Include the separator in the lines. Defaults to False.

  • allow_blank (bool, optional) – Return a blank line if the text ends with a separator. Defaults to False.

Returns

A list of rich text, one per line of the original.

Return type

List[RichText]

classmethod styled(text, style='', *, justify=None, overflow=None)[source]

Construct a Text instance with a pre-applied styled. A style applied in this way won’t be used to pad the text when it is justified.

Parameters
  • text (str) – A string containing console markup.

  • style (Union[str, Style]) – Style to apply to the text. Defaults to “”.

  • justify (str, optional) – Justify method: “left”, “center”, “full”, “right”. Defaults to None.

  • overflow (str, optional) – Overflow method: “crop”, “fold”, “ellipsis”. Defaults to None.

Returns

A text instance with a style applied to the entire string.

Return type

Text

stylize(style, start=0, end=None)[source]

Apply a style to the text, or a portion of the text.

Parameters
  • style (Union[str, Style]) – Style instance or style definition to apply.

  • start (int) – Start offset (negative indexing is supported). Defaults to 0.

  • end (Optional[int], optional) – End offset (negative indexing is supported), or None for end of text. Defaults to None.

Return type

None

stylize_before(style, start=0, end=None)[source]

Apply a style to the text, or a portion of the text. Styles will be applied before other styles already present.

Parameters
  • style (Union[str, Style]) – Style instance or style definition to apply.

  • start (int) – Start offset (negative indexing is supported). Defaults to 0.

  • end (Optional[int], optional) – End offset (negative indexing is supported), or None for end of text. Defaults to None.

Return type

None

truncate(max_width, *, overflow=None, pad=False)[source]

Truncate text if it is longer that a given width.

Parameters
  • max_width (int) – Maximum number of characters in text.

  • overflow (str, optional) – Overflow method: “crop”, “fold”, or “ellipsis”. Defaults to None, to use self.overflow.

  • pad (bool, optional) – Pad with spaces if the length is less than max_width. Defaults to False.

Return type

None

with_indent_guides(indent_size=None, *, character='│', style='dim green')[source]

Adds indent guide lines to text.

Parameters
  • indent_size (Optional[int]) – Size of indentation, or None to auto detect. Defaults to None.

  • character (str, optional) – Character to use for indentation. Defaults to “│”.

  • style (Union[Style, str], optional) – Style of indent guides.

Returns

New text with indentation guides.

Return type

Text

wrap(console, width, *, justify=None, overflow=None, tab_size=8, no_wrap=None)[source]

Word wrap the text.

Parameters
  • console (Console) – Console instance.

  • width (int) – Number of characters per line.

  • emoji (bool, optional) – Also render emoji code. Defaults to True.

  • justify (str, optional) – Justify method: “default”, “left”, “center”, “full”, “right”. Defaults to “default”.

  • overflow (str, optional) – Overflow method: “crop”, “fold”, or “ellipsis”. Defaults to None.

  • tab_size (int, optional) – Default tab size. Defaults to 8.

  • no_wrap (bool, optional) – Disable wrapping, Defaults to False.

Returns

Number of lines.

Return type

Lines