Skip to content

textual.content

Content is a container for text, with spans marked up with color / style. If is equivalent to Rich's Text object, with support for more of Textual features.

Unlike Rich Text, Content is immutable so you can't modify it in place, and most methods will return a new Content instance. This is more like the builtin str, and allows Textual to make some significant optimizations.

ANSI_DEFAULT module-attribute

ANSI_DEFAULT = Style(
    background=Color(0, 0, 0, 0, ansi=-1),
    foreground=Color(0, 0, 0, 0, ansi=-1),
)

A Style for ansi default background and foreground.

ContentType module-attribute

ContentType = Union['Content', str]

Type alias used where content and a str are interchangeable in a function.

TRANSPARENT_STYLE module-attribute

TRANSPARENT_STYLE = Style()

A null style.

Content

Content(text, spans=None, cell_length=None)

Bases: Visual

Text content with marked up spans.

This object can be considered immutable, although it might update its internal state in a way that is consistent with immutability.

spans: Optional list of spans.
cell_length: Cell length of text if known, otherwise `None`.

cell_length property

cell_length

The cell length of the content.

markup cached property

markup

Get Content markup to render this Text.

Returns:

Name Type Description
str str

A string potentially creating markup tags.

plain property

plain

Get the text as a single string.

spans property

spans

A sequence of spans used to markup regions of the content.

Warning

Never attempt to mutate the spans, as this would certainly break the output--possibly in quite subtle ways!

without_spans property

without_spans

The content with no spans

append

append(content)

Append text or content to this content.

Note this is a little inefficient, if you have many strings to append, consider join.

Parameters:

Name Type Description Default

content

Content | str

A content instance, or a string.

required

Returns:

Type Description
Content

New content.

append_text

append_text(text, style='')

Append text give as a string, with an optional style.

Parameters:

Name Type Description Default

text

str

Text to append.

required

style

Style | str

Optional style for new text.

''

Returns:

Type Description
Content

New content.

assemble classmethod

assemble(*parts, end='')

Construct new content from string, content, or tuples of (TEXT, STYLE).

This is an efficient way of constructing Content composed of smaller pieces of text and / or other Content objects.

Example
content = Content.assemble(
    Content.from_markup("[b]assemble[/b]: "),  # Other content
    "pieces of text or content into a",  # Simple string of text
    ("a single Content instance", "underline"),  # A tuple of text and a style
)

Parameters:

Name Type Description Default

*parts

str | Content | tuple[str, str]

Parts to join to gether. A part may be a simple string, another Content

()

end

str

Optional end to the Content.

''

center

center(width, ellipsis=False)

Align a line to the center.

Parameters:

Name Type Description Default

width

int

Desired width of output.

required

ellipsis

bool

Insert ellipsis if content is truncated.

False

Returns:

Type Description
Content

New line Content.

divide

divide(offsets)

Divide the content at the given offsets.

This will cut the content in to pieces, and return those pieces. Note that the number of pieces return will be one greater than the number of cuts.

Parameters:

Name Type Description Default

offsets

Sequence[int]

Sequence of offsets (in characters) of where to apply the cuts.

required

Returns:

Type Description
list[Content]

List of Content instances which combined would be equal to the whole.

expand_tabs

expand_tabs(tab_size=8)

Converts tabs to spaces.

Parameters:

Name Type Description Default

tab_size

int

Size of tabs. Defaults to 8.

8

extend_right

extend_right(count, character=' ')

Add repeating characters (typically spaces) to the content with the style(s) of the last character.

Parameters:

Name Type Description Default

count

int

Number of spaces.

required

character

str

Character to add with.

' '

Returns:

Type Description
Content

A Content instance.

extend_style

extend_style(spaces)

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

Parameters:

Name Type Description Default

spaces

int

Number of spaces to add to the Text.

required

Returns:

Type Description
Content

New content with additional spaces at the end.

from_markup classmethod

from_markup(markup, **variables)

Create content from Textual markup, optionally combined with template variables.

If markup is already a Content instance, it will be returned unmodified.

See the guide on Content for more details.

Example
content = Content.from_markup("Hello, [b]$name[/b]!", name="Will")

Parameters:

Name Type Description Default

markup

str | Content

Textual markup, or Content.

required

**variables

object

Optional template variables used

{}

Returns:

Type Description
Content

New Content instance.

from_rich_text classmethod

from_rich_text(text, console=None)

Create equivalent Visual Content for str or Text.

Parameters:

Name Type Description Default

text

str | Text

String or Rich Text.

required

Returns:

Type Description
Content

New Content.

get_height

get_height(rules, width)

Get the height of the visual if rendered with the given width. Part of the Textual Visual protocol.

Parameters:

Name Type Description Default

widget

Parent widget.

required

width

int

Width of visual.

required

Returns:

Type Description
int

A height in lines.

get_optimal_width

get_optimal_width(rules, container_width)

Get optimal width of the visual to display its content. Part of the Textual Visual protocol.

Parameters:

Name Type Description Default

widget

Parent widget.

required

container_size

The size of the container.

required

Returns:

Type Description
int

A width in cells.

get_style_at_offset

get_style_at_offset(offset)

Get the style of a character at give offset.

Parameters:

Name Type Description Default

offset

int

Offset into text (negative indexing supported)

required

Returns:

Name Type Description
Style Style

A Style instance.

highlight_regex

highlight_regex(
    highlight_regex, *, style, maximum_highlights=None
)

Apply a style to text that matches a regular expression.

Parameters:

Name Type Description Default

highlight_regex

Pattern[str] | str

Regular expression as a string, or compiled.

required

style

Style

Style to apply.

required

maximum_highlights

int | None

Maximum number of matches to highlight, or None for no maximum.

None

Returns:

Type Description
Content

new content.

is_same

is_same(content)

Compare to another Content object.

Two Content objects are the same if their text and spans match. Note that if you use the == operator to compare Content instances, it will only consider the plain text portion of the content (and not the spans).

Parameters:

Name Type Description Default

content

Content

Content instance.

required

Returns:

Type Description
bool

True if this is identical to content, otherwise False.

join

join(lines)

Join an iterable of content or strings.

This works much like the join method on str objects. Self is the separator (which maybe empty) placed between each string or Content.

Parameters:

Name Type Description Default

lines

Iterable[Content | str]

An iterable of other Content instances or or strings.

required

Returns:

Type Description
Content

A single Content instance, containing all of the lines.

pad_left

pad_left(count, character=' ')

Pad the left with a given character.

Parameters:

Name Type Description Default

count

int

Number of characters to pad.

required

character

str

Character to pad with. Defaults to " ".

' '

pad_right

pad_right(count, character=' ')

Pad the right with a given character.

Parameters:

Name Type Description Default

count

int

Number of characters to pad.

required

character

str

Character to pad with. Defaults to " ".

' '

render_segments

render_segments(base_style=null(), end='')

Render the Content in to a list of segments.

Parameters:

Name Type Description Default

base_style

Style

Base style for render (style under the content). Defaults to Style.null().

null()

end

str

Character to end the segments with. Defaults to "".

''

Returns:

Type Description
list[Segment]

A list of segments.

render_strips

render_strips(
    rules,
    width,
    height,
    style,
    selection=None,
    selection_style=None,
)

Render the visual into an iterable of strips. Part of the Visual protocol.

Parameters:

Name Type Description Default

rules

RulesMap

A mapping of style rules, such as the Widgets styles object.

required

width

int

Width of desired render.

required

height

int | None

Height of desired render or None for any height.

required

style

Style

The base style to render on top of.

required

selection

Selection | None

Selection information, if applicable, otherwise None.

None

selection_style

Style | None

Selection style if selection is not None.

None

Returns:

Type Description
list[Strip]

An list of Strips.

right

right(width, ellipsis=False)

Align a line to the right.

Parameters:

Name Type Description Default

width

int

Desired width of output.

required

ellipsis

bool

Insert ellipsis if content is truncated.

False

Returns:

Type Description
Content

New line Content.

right_crop

right_crop(amount=1)

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

Parameters:

Name Type Description Default

amount

int

Number of characters to crop.

1

Returns:

Type Description
Content

New Content

rstrip

rstrip(chars=None)

Strip characters from end of text.

rstrip_end

rstrip_end(size)

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

Parameters:

Name Type Description Default

size

int

The desired size of the text.

required

split

split(
    separator="\n",
    *,
    include_separator=False,
    allow_blank=False
)

Split rich text into lines, preserving styles.

Parameters:

Name Type Description Default

separator

str

String to split on. Defaults to "\n".

'\n'

include_separator

bool

Include the separator in the lines. Defaults to False.

False

allow_blank

bool

Return a blank line if the text ends with a separator. Defaults to False.

False

Returns:

Type Description
list[Content]

List[Content]: A list of Content, one per line of the original.

styled classmethod

styled(text, style='', cell_length=None)

Create a Content instance from text and an optional style.

Parameters:

Name Type Description Default

text

str

String content.

required

style

Style | str

Desired style.

''

cell_length

int | None

Cell length of text if known, otherwise None.

None

Returns:

Type Description
Content

New Content instance.

stylize

stylize(style, start=0, end=None)

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

Parameters:

Name Type Description Default

style

Union[str, Style]

Style instance or style definition to apply.

required

start

int

Start offset (negative indexing is supported). Defaults to 0.

0

end

Optional[int]

End offset (negative indexing is supported), or None for end of text. Defaults to None.

None

stylize_before

stylize_before(style, start=0, end=None)

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

Styles applies with this method will be applied before other styles already present.

Parameters:

Name Type Description Default

style

Union[str, Style]

Style instance or style definition to apply.

required

start

int

Start offset (negative indexing is supported). Defaults to 0.

0

end

Optional[int]

End offset (negative indexing is supported), or None for end of text. Defaults to None.

None

truncate

truncate(max_width, *, ellipsis=False, pad=False)

Truncate the content at a given cell width.

Parameters:

Name Type Description Default

max_width

int

The maximum width in cells.

required

ellipsis

Insert an ellipsis when cropped.

False

pad

bool

Pad the content if less than max_width.

False

Returns:

Type Description
Content

New Content.

Span

Bases: NamedTuple

A style applied to a range of character offsets.

extend

extend(cells)

Extend the span by the given number of cells.

Parameters:

Name Type Description Default

cells

int

Additional space to add to end of span.

required

Returns:

Name Type Description
Span 'Span'

A span.