Justify and overflow text to a given width. Args: console (Console): Console instance. width (int): Number of cells available per line. justify (str, optional): Default justify method for text: "left", "center", "full" or "right". Defaults to "left".
(
self,
console: "Console",
width: int,
justify: "JustifyMethod" = "left",
overflow: "OverflowMethod" = "fold",
)
| 109 | return self._lines.pop(index) |
| 110 | |
| 111 | def justify( |
| 112 | self, |
| 113 | console: "Console", |
| 114 | width: int, |
| 115 | justify: "JustifyMethod" = "left", |
| 116 | overflow: "OverflowMethod" = "fold", |
| 117 | ) -> None: |
| 118 | """Justify and overflow text to a given width. |
| 119 | |
| 120 | Args: |
| 121 | console (Console): Console instance. |
| 122 | width (int): Number of cells available per line. |
| 123 | justify (str, optional): Default justify method for text: "left", "center", "full" or "right". Defaults to "left". |
| 124 | overflow (str, optional): Default overflow for text: "crop", "fold", or "ellipsis". Defaults to "fold". |
| 125 | |
| 126 | """ |
| 127 | from .text import Text |
| 128 | |
| 129 | if justify == "left": |
| 130 | for line in self._lines: |
| 131 | line.truncate(width, overflow=overflow, pad=True) |
| 132 | elif justify == "center": |
| 133 | for line in self._lines: |
| 134 | line.rstrip() |
| 135 | line.truncate(width, overflow=overflow) |
| 136 | line.pad_left((width - cell_len(line.plain)) // 2) |
| 137 | line.pad_right(width - cell_len(line.plain)) |
| 138 | elif justify == "right": |
| 139 | for line in self._lines: |
| 140 | line.rstrip() |
| 141 | line.truncate(width, overflow=overflow) |
| 142 | line.pad_left(width - cell_len(line.plain)) |
| 143 | elif justify == "full": |
| 144 | for line_index, line in enumerate(self._lines): |
| 145 | if line_index == len(self._lines) - 1: |
| 146 | break |
| 147 | words = line.split(" ") |
| 148 | words_size = sum(cell_len(word.plain) for word in words) |
| 149 | num_spaces = len(words) - 1 |
| 150 | spaces = [1 for _ in range(num_spaces)] |
| 151 | index = 0 |
| 152 | if spaces: |
| 153 | while words_size + num_spaces < width: |
| 154 | spaces[len(spaces) - index - 1] += 1 |
| 155 | num_spaces += 1 |
| 156 | index = (index + 1) % len(spaces) |
| 157 | tokens: List[Text] = [] |
| 158 | for index, (word, next_word) in enumerate( |
| 159 | zip_longest(words, words[1:]) |
| 160 | ): |
| 161 | tokens.append(word) |
| 162 | if index < len(spaces): |
| 163 | style = word.get_style_at_offset(console, -1) |
| 164 | next_style = next_word.get_style_at_offset(console, 0) |
| 165 | space_style = style if style == next_style else line.style |
| 166 | tokens.append(Text(" " * spaces[index], style=space_style)) |
| 167 | self[line_index] = Text("").join(tokens) |