This page is the complete API reference for the Text class, Span NamedTuple, Lines container, and the TextType / GetStyleCallable type aliases defined in rich/text.py It covers construction, mutation, highlighting, splitting, wrapping, and rendering.
For a conceptual explanation of how Text and Span fit into the rendering pipeline, see Text and Spans. For markup syntax and how Text.from_markup parses tags, see Markup and Formatting. For the Style and Color types referenced throughout this page, see Styles and Colors.
Defined at the top of rich/text.py41-44:
| Name | Type | Description |
|---|---|---|
TextType | Union[str, Text] | Accepts either a plain string or a Text instance |
GetStyleCallable | Callable[[str], Optional[StyleType]] | A callable that maps matched text to a style |
DEFAULT_JUSTIFY | "default" | Fallback justify mode |
DEFAULT_OVERFLOW | "fold" | Fallback overflow mode |
SpanSource: rich/text.py47-115
Span is a NamedTuple that marks a styled region inside a Text object. It records which character range carries which style.
Span(start: int, end: int, style: Union[str, Style])
| Field | Type | Description |
|---|---|---|
start | int | Inclusive start index into the parent text |
end | int | Exclusive end index into the parent text |
style | Union[str, Style] | The style applied to this range |
bool(span) returns True only when end > start.
| Method | Signature | Returns | Description |
|---|---|---|---|
split | (offset: int) | Tuple[Span, Optional[Span]] | Split into two spans at offset. Returns (self, None) if offset is outside the span. |
move | (offset: int) | Span | Shift both start and end by offset |
right_crop | (offset: int) | Span | Clip end to min(end, offset) |
extend | (cells: int) | Span | Extend end by cells |
Sources: rich/text.py47-115
TextSource: rich/text.py118
Text holds a styled string. Internally, it stores the raw string as a list of string fragments (_text) and a list of Span objects (_spans). The list-of-strings structure avoids repeated string concatenation during append operations; it is collapsed to a single string lazily when .plain is accessed.
Text implements JupyterMixin so it renders correctly in Jupyter notebooks, and implements __rich_console__ and __rich_measure__ for the Rich rendering protocol.
Diagram: Text internal data model
Sources: rich/text.py132-165
Text(
text: str = "",
style: Union[str, Style] = "",
*,
justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None,
no_wrap: Optional[bool] = None,
end: str = "\n",
tab_size: Optional[int] = None,
spans: Optional[List[Span]] = None,
)
| Parameter | Default | Description |
|---|---|---|
text | "" | Initial plain text. Control codes are stripped automatically. |
style | "" | Base style applied to the whole text. Used for padding when justified. |
justify | None | "left", "center", "right", "full", or "default" |
overflow | None | "fold", "crop", "ellipsis", or "ignore" |
no_wrap | None | Disable wrapping if True |
end | "\n" | Appended to output after rendering |
tab_size | None | Spaces per tab; None defers to console.tab_size |
spans | None | Pre-existing list of Span objects |
Diagram: Text construction paths
Sources: rich/text.py259-400
Text.from_markupText.from_markup(
text: str,
*,
style: Union[str, Style] = "",
emoji: bool = True,
emoji_variant: Optional[EmojiVariant] = None,
justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None,
end: str = "\n",
) -> Text
Parses Rich console markup (BBCode-style tags) by calling markup.render(). Emoji codes (:smile:) are resolved when emoji=True.
Text.from_ansiText.from_ansi(
text: str,
*,
style: Union[str, Style] = "",
justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None,
no_wrap: Optional[bool] = None,
end: str = "\n",
tab_size: Optional[int] = 8,
) -> Text
Decodes ANSI escape codes using AnsiDecoder, converting them to Span objects. Multi-line input is joined with a newline separator Text.
Text.styledText.styled(
text: str,
style: StyleType = "",
*,
justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None,
) -> Text
Creates a Text instance where the style is added as a Span (not as Text.style). This means the style is not used to pad the text when justifying.
Text.assembleText.assemble(
*parts: Union[str, Text, Tuple[str, StyleType]],
style: Union[str, Style] = "",
justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None,
no_wrap: Optional[bool] = None,
end: str = "\n",
tab_size: int = 8,
meta: Optional[Dict[str, Any]] = None,
) -> Text
Builds a Text by appending each part in sequence. Each part can be a plain str, a Text instance, or a (str, style) tuple. Optional meta dict is applied to the whole result via apply_meta.
| Property | Type | Description |
|---|---|---|
plain | str | Get/set the raw text. Setting it strips control codes and trims out-of-bounds spans. |
spans | List[Span] | Get/set a copy of the span list |
cell_len | int | Number of terminal cells the text occupies (accounts for wide Unicode characters) |
markup | str | Reconstruct console markup string representing this Text with all spans encoded as tags |
Sources: rich/text.py402-427 rich/text.py224-257
| Method | Description |
|---|---|
__len__ | Returns character count (_length) |
__bool__ | True if non-empty |
__str__ | Returns .plain |
__repr__ | Debug representation |
__add__ | Concatenates Text + str or Text + Text via .copy() + .append() |
__eq__ | Compares .plain and ._spans |
__contains__ | str in text or Text in text checks via .plain |
__getitem__ | Integer or slice indexing; slices use .divide(); step != 1 raises TypeError |
__rich_console__ | Rendering protocol: wraps, justifies, and yields Segment objects |
__rich_measure__ | Returns Measurement(min_width, max_width) |
Sources: rich/text.py167-223 rich/text.py689-717
| Method | Signature | Description |
|---|---|---|
copy | () -> Text | Full copy: same text, style, spans, and metadata |
blank_copy | (plain: str = "") -> Text | New instance with same metadata but empty text and no spans |
Sources: rich/text.py430-455
Diagram: Styling method flow
Sources: rich/text.py457-541
stylizestylize(
style: Union[str, Style],
start: int = 0,
end: Optional[int] = None,
) -> None
Appends a new Span to _spans. Negative indices are supported. No-op if style is falsy or the range is invalid.
stylize_beforeSame signature as stylize but inserts the span at position 0 so it is applied before any existing spans.
apply_metaapply_meta(
meta: Dict[str, Any],
start: int = 0,
end: Optional[int] = None,
) -> None
Converts a dict to a Style using Style.from_meta and calls stylize.
onon(meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> Text
Convenience method for attaching event handler metadata (used by the Textual project). Keyword arguments are prefixed with @ before being passed to apply_meta. Returns self for chaining.
| Method | Signature | Returns | Notes |
|---|---|---|---|
append | (text: Union[Text, str], style=None) | Text | General-purpose append. Raises ValueError if style is set when appending a Text. Returns self. |
append_text | (text: Text) | Text | Faster Text-only variant. Returns self. |
append_tokens | (tokens: Iterable[Tuple[str, Optional[StyleType]]]) | Text | Batch-append (content, style) pairs. Returns self. |
Sources: rich/text.py964-1052
copy_styles rich/text.py1054-1060 extends _spans from another Text instance of equal length.
| Method | Signature | Description |
|---|---|---|
rstrip | () | Strip trailing whitespace from .plain |
rstrip_end | (size: int) | Remove trailing whitespace only beyond size characters |
right_crop | (amount: int = 1) | Remove amount characters from end, clipping spans |
remove_suffix | (suffix: str) | Call right_crop(len(suffix)) if plain ends with suffix |
truncate | (max_width, overflow=None, pad=False) | Clip text to max_width cells; optionally pad if shorter |
set_length | (new_length: int) | Pad or crop to exactly new_length characters |
pad | (count: int, character=" ") | Add count characters on both sides |
pad_left | (count: int, character=" ") | Add count characters on left, shifts spans |
pad_right | (count: int, character=" ") | Add count characters on right |
align | (align: AlignMethod, width: int, character=" ") | Truncate then pad to fit width; align is "left", "center", or "right" |
extend_style | (spaces: int) | Append spaces that inherit the style of the last character |
Sources: rich/text.py543-551 rich/text.py662-688 rich/text.py859-963 rich/text.py572-591
highlight_regexhighlight_regex(
re_highlight: Union[Pattern[str], str],
style: Optional[Union[GetStyleCallable, StyleType]] = None,
*,
style_prefix: str = "",
) -> int
Applies styles to all regex matches. Named capture groups in the pattern are automatically turned into style names (optionally prefixed with style_prefix). The style argument may be a static style or a GetStyleCallable that receives the matched text and returns a style. Returns the number of matches found.
highlight_wordshighlight_words(
words: Iterable[str],
style: Union[str, Style],
*,
case_sensitive: bool = True,
) -> int
Highlights exact word occurrences using re.escape. Returns match count.
Diagram: split and divide
Sources: rich/text.py1062-1267
splitsplit(
separator: str = "\n",
*,
include_separator: bool = False,
allow_blank: bool = False,
) -> Lines
Splits on separator, preserving Span associations across line boundaries. Returns a Lines container.
dividedivide(offsets: Iterable[int]) -> Lines
Cuts the text at each offset, producing len(offsets) + 1 fragments. Spans are clipped and redistributed to each fragment using a binary search for efficiency.
wrapwrap(
console: Console,
width: int,
*,
justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None,
tab_size: int = 8,
no_wrap: Optional[bool] = None,
) -> Lines
Word-wraps the text to width terminal cells. Tabs are expanded first. If no_wrap is True the text is returned as a single line (subject to overflow handling). Calls divide_line from rich/_wrap.py26-78 to find break positions.
fitfit(width: int) -> Lines
Splits on newlines and then calls set_length(width) on each line to hard-clip to width.
joinjoin(lines: Iterable[Text]) -> Text
Acts like str.join, concatenating Text instances using self as the separator. Spans are offset-adjusted correctly.
expand_tabsexpand_tabs(tab_size: Optional[int] = None) -> None
Replaces tab characters with the correct number of spaces to advance to the next tab stop. Modifies _text and _spans in place.
| Method | Signature | Description |
|---|---|---|
get_style_at_offset | (console: Console, offset: int) -> Style | Compute the combined Style at a character position by walking all spans |
detect_indentation | () -> int | Return the auto-detected indent size (GCD of all leading space counts) |
with_indent_guides | (indent_size=None, character="│", style="dim green") -> Text | Return a new Text with vertical indent guide lines inserted |
Sources: rich/text.py552-570 rich/text.py1268-1338
renderrender(console: Console, end: str = "") -> Iterable[Segment]
Converts the Text and its Span list into a sequence of Segment objects. Builds a sorted event list of span open/close positions, then walks through them, combining the active style stack at each boundary using Style.combine.
Diagram: Rendering pipeline for Text
Sources: rich/text.py689-776
LinesSource: rich/containers.py66-167
Lines is a list-like container of Text instances, returned by Text.split, Text.divide, Text.wrap, and Text.fit.
| Method | Signature | Description |
|---|---|---|
append | (line: Text) | Append a single line |
extend | (lines: Iterable[Text]) | Extend with multiple lines |
pop | (index: int = -1) -> Text | Remove and return a line |
justify | (console, width, justify, overflow) | Apply justification in-place to all lines |
__rich_console__ | — | Yields lines for the rendering pipeline |
Lines.justify handles "left", "center", "right", and "full" alignment modes. Full justification distributes extra spaces between words on all lines except the last.
Sources: rich/containers.py66-167
The table below groups all Text public methods by category for quick lookup.
| Category | Methods |
|---|---|
| Construction | from_markup, from_ansi, styled, assemble |
| Copy | copy, blank_copy |
| Properties | plain, spans, cell_len, markup |
| Style application | stylize, stylize_before, apply_meta, on |
| Append | append, append_text, append_tokens, copy_styles |
| Trim / crop | rstrip, rstrip_end, right_crop, remove_suffix, truncate, set_length |
| Pad / align | pad, pad_left, pad_right, align, extend_style |
| Highlight | highlight_regex, highlight_words |
| Split / divide | split, divide, wrap, fit |
| Join | join |
| Tab handling | expand_tabs |
| Inspection | get_style_at_offset, detect_indentation, with_indent_guides |
| Render | render, __rich_console__, __rich_measure__ |
Refresh this wiki
This wiki was recently refreshed. Please wait 2 days to refresh again.