A piece of text with associated style. Segments are produced by the Console render process and are ultimately converted in to strings to be written to the terminal. Args: text (str): A piece of text. style (:class:`~rich.style.Style`, optional): An optional style to apply to
| 59 | |
| 60 | @rich_repr() |
| 61 | class Segment(NamedTuple): |
| 62 | """A piece of text with associated style. Segments are produced by the Console render process and |
| 63 | are ultimately converted in to strings to be written to the terminal. |
| 64 | |
| 65 | Args: |
| 66 | text (str): A piece of text. |
| 67 | style (:class:`~rich.style.Style`, optional): An optional style to apply to the text. |
| 68 | control (Tuple[ControlCode], optional): Optional sequence of control codes. |
| 69 | |
| 70 | Attributes: |
| 71 | cell_length (int): The cell length of this Segment. |
| 72 | """ |
| 73 | |
| 74 | text: str |
| 75 | style: Optional[Style] = None |
| 76 | control: Optional[Sequence[ControlCode]] = None |
| 77 | |
| 78 | @property |
| 79 | def cell_length(self) -> int: |
| 80 | """The number of terminal cells required to display self.text. |
| 81 | |
| 82 | Returns: |
| 83 | int: A number of cells. |
| 84 | """ |
| 85 | text, _style, control = self |
| 86 | return 0 if control else cell_len(text) |
| 87 | |
| 88 | def __rich_repr__(self) -> Result: |
| 89 | yield self.text |
| 90 | if self.control is None: |
| 91 | if self.style is not None: |
| 92 | yield self.style |
| 93 | else: |
| 94 | yield self.style |
| 95 | yield self.control |
| 96 | |
| 97 | def __bool__(self) -> bool: |
| 98 | """Check if the segment contains text.""" |
| 99 | return bool(self.text) |
| 100 | |
| 101 | @property |
| 102 | def is_control(self) -> bool: |
| 103 | """Check if the segment contains control codes.""" |
| 104 | return self.control is not None |
| 105 | |
| 106 | @classmethod |
| 107 | @lru_cache(1024 * 16) |
| 108 | def _split_cells(cls, segment: "Segment", cut: int) -> Tuple["Segment", "Segment"]: |
| 109 | """Split a segment in to two at a given cell position. |
| 110 | |
| 111 | Note that splitting a double-width character, may result in that character turning |
| 112 | into two spaces. |
| 113 | |
| 114 | Args: |
| 115 | segment (Segment): A segment to split. |
| 116 | cut (int): A cell position to cut on. |
| 117 | |
| 118 | Returns: |
no outgoing calls