Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/rich/text.py: 66%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

612 statements  

1import re 

2from functools import partial, reduce 

3from math import gcd 

4from operator import itemgetter 

5from typing import TYPE_CHECKING, Any, Callable, Iterable, NamedTuple, Pattern, Union 

6 

7from ._loop import loop_last 

8from ._pick import pick_bool 

9from ._wrap import divide_line 

10from .align import AlignMethod 

11from .cells import cell_len, set_cell_size 

12from .containers import Lines 

13from .control import strip_control_codes 

14from .emoji import EmojiVariant 

15from .jupyter import JupyterMixin 

16from .measure import Measurement 

17from .segment import Segment 

18from .style import Style, StyleType 

19 

20if TYPE_CHECKING: # pragma: no cover 

21 from .console import Console, ConsoleOptions, JustifyMethod, OverflowMethod 

22 

23DEFAULT_JUSTIFY: "JustifyMethod" = "default" 

24DEFAULT_OVERFLOW: "OverflowMethod" = "fold" 

25 

26 

27_re_whitespace = re.compile(r"\s+$") 

28 

29TextType = Union[str, "Text"] 

30"""A plain string or a :class:`Text` instance.""" 

31 

32GetStyleCallable = Callable[[str], StyleType | None] 

33 

34 

35class Span(NamedTuple): 

36 """A marked up region in some text.""" 

37 

38 start: int 

39 """Span start index.""" 

40 end: int 

41 """Span end index.""" 

42 style: str | Style 

43 """Style associated with the span.""" 

44 

45 def __repr__(self) -> str: 

46 return f"Span({self.start}, {self.end}, {self.style!r})" 

47 

48 def __bool__(self) -> bool: 

49 return self.end > self.start 

50 

51 def split(self, offset: int) -> "tuple[Span, Span | None]": 

52 """Split a span in to 2 from a given offset.""" 

53 

54 if offset < self.start: 

55 return self, None 

56 if offset >= self.end: 

57 return self, None 

58 

59 start, end, style = self 

60 span1 = Span(start, min(end, offset), style) 

61 span2 = Span(span1.end, end, style) 

62 return span1, span2 

63 

64 def move(self, offset: int) -> "Span": 

65 """Move start and end by a given offset. 

66 

67 Args: 

68 offset (int): Number of characters to add to start and end. 

69 

70 Returns: 

71 TextSpan: A new TextSpan with adjusted position. 

72 """ 

73 start, end, style = self 

74 return Span(start + offset, end + offset, style) 

75 

76 def right_crop(self, offset: int) -> "Span": 

77 """Crop the span at the given offset. 

78 

79 Args: 

80 offset (int): A value between start and end. 

81 

82 Returns: 

83 Span: A new (possibly smaller) span. 

84 """ 

85 start, end, style = self 

86 if offset >= end: 

87 return self 

88 return Span(start, min(offset, end), style) 

89 

90 def extend(self, cells: int) -> "Span": 

91 """Extend the span by the given number of cells. 

92 

93 Args: 

94 cells (int): Additional space to add to end of span. 

95 

96 Returns: 

97 Span: A span. 

98 """ 

99 if cells: 

100 start, end, style = self 

101 return Span(start, end + cells, style) 

102 else: 

103 return self 

104 

105 

106class Text(JupyterMixin): 

107 """Text with color / style. 

108 

109 Args: 

110 text (str, optional): Default unstyled text. Defaults to "". 

111 style (str | Style, optional): Base style for text. Defaults to "". 

112 justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. 

113 overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. 

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

115 end (str, optional): Character to end text with. Defaults to "\\\\n". 

116 tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None. 

117 spans (list[Span], optional). A list of predefined style spans. Defaults to None. 

118 """ 

119 

120 __slots__ = [ 

121 "_text", 

122 "style", 

123 "justify", 

124 "overflow", 

125 "no_wrap", 

126 "end", 

127 "tab_size", 

128 "_spans", 

129 "_length", 

130 ] 

131 

132 def __init__( 

133 self, 

134 text: str = "", 

135 style: str | Style = "", 

136 *, 

137 justify: "JustifyMethod | None" = None, 

138 overflow: "OverflowMethod | None" = None, 

139 no_wrap: bool | None = None, 

140 end: str = "\n", 

141 tab_size: int | None = None, 

142 spans: list[Span] | None = None, 

143 ) -> None: 

144 sanitized_text = strip_control_codes(text) 

145 self._text = [sanitized_text] 

146 self.style = style 

147 self.justify: "JustifyMethod | None" = justify 

148 self.overflow: "OverflowMethod | None" = overflow 

149 self.no_wrap = no_wrap 

150 self.end = end 

151 self.tab_size = tab_size 

152 self._spans: list[Span] = spans or [] 

153 self._length: int = len(sanitized_text) 

154 

155 def __len__(self) -> int: 

156 return self._length 

157 

158 def __bool__(self) -> bool: 

159 return bool(self._length) 

160 

161 def __str__(self) -> str: 

162 return self.plain 

163 

164 def __repr__(self) -> str: 

165 return f"<text {self.plain!r} {self._spans!r} {self.style!r}>" 

166 

167 def __add__(self, other: Any) -> "Text": 

168 if isinstance(other, (str, Text)): 

169 result = self.copy() 

170 result.append(other) 

171 return result 

172 return NotImplemented 

173 

174 def __eq__(self, other: object) -> bool: 

175 if not isinstance(other, Text): 

176 return NotImplemented 

177 return self.plain == other.plain and self._spans == other._spans 

178 

179 def __contains__(self, other: object) -> bool: 

180 if isinstance(other, str): 

181 return other in self.plain 

182 elif isinstance(other, Text): 

183 return other.plain in self.plain 

184 return False 

185 

186 def __getitem__(self, slice: int | slice) -> "Text": 

187 def get_text_at(offset: int) -> "Text": 

188 _Span = Span 

189 text = Text( 

190 self.plain[offset], 

191 spans=[ 

192 _Span(0, 1, style) 

193 for start, end, style in self._spans 

194 if end > offset >= start 

195 ], 

196 end="", 

197 ) 

198 return text 

199 

200 if isinstance(slice, int): 

201 return get_text_at(slice) 

202 else: 

203 start, stop, step = slice.indices(len(self.plain)) 

204 if step == 1: 

205 lines = self.divide([start, stop]) 

206 return lines[1] 

207 else: 

208 # This would be a bit of work to implement efficiently 

209 # For now, its not required 

210 raise TypeError("slices with step!=1 are not supported") 

211 

212 @property 

213 def cell_len(self) -> int: 

214 """Get the number of cells required to render this text.""" 

215 return cell_len(self.plain) 

216 

217 @property 

218 def markup(self) -> str: 

219 """Get console markup to render this Text. 

220 

221 Returns: 

222 str: A string potentially creating markup tags. 

223 """ 

224 from .markup import escape 

225 

226 output: list[str] = [] 

227 

228 plain = self.plain 

229 markup_spans = [ 

230 (0, False, self.style), 

231 *((span.start, False, span.style) for span in self._spans), 

232 *((span.end, True, span.style) for span in self._spans), 

233 (len(plain), True, self.style), 

234 ] 

235 markup_spans.sort(key=itemgetter(0, 1)) 

236 position = 0 

237 append = output.append 

238 for offset, closing, style in markup_spans: 

239 if offset > position: 

240 append(escape(plain[position:offset])) 

241 position = offset 

242 if style: 

243 append(f"[/{style}]" if closing else f"[{style}]") 

244 markup = "".join(output) 

245 return markup 

246 

247 @classmethod 

248 def from_markup( 

249 cls, 

250 text: str, 

251 *, 

252 style: str | Style = "", 

253 emoji: bool = True, 

254 emoji_variant: EmojiVariant | None = None, 

255 justify: "JustifyMethod | None" = None, 

256 overflow: "OverflowMethod | None" = None, 

257 end: str = "\n", 

258 ) -> "Text": 

259 """Create Text instance from markup. 

260 

261 Args: 

262 text (str): A string containing console markup. 

263 style (str | Style, optional): Base style for text. Defaults to "". 

264 emoji (bool, optional): Also render emoji code. Defaults to True. 

265 emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None. 

266 justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. 

267 overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. 

268 end (str, optional): Character to end text with. Defaults to "\\\\n". 

269 

270 Returns: 

271 Text: A Text instance with markup rendered. 

272 """ 

273 from .markup import render 

274 

275 rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant) 

276 rendered_text.justify = justify 

277 rendered_text.overflow = overflow 

278 rendered_text.end = end 

279 return rendered_text 

280 

281 @classmethod 

282 def from_ansi( 

283 cls, 

284 text: str, 

285 *, 

286 style: str | Style = "", 

287 justify: "JustifyMethod | None" = None, 

288 overflow: "OverflowMethod | None" = None, 

289 no_wrap: bool | None = None, 

290 end: str = "\n", 

291 tab_size: int | None = 8, 

292 ) -> "Text": 

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

294 

295 Args: 

296 text (str): A string containing escape codes. 

297 style (str | Style, optional): Base style for text. Defaults to "". 

298 justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. 

299 overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. 

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

301 end (str, optional): Character to end text with. Defaults to "\\\\n". 

302 tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None. 

303 """ 

304 from .ansi import AnsiDecoder 

305 

306 joiner = Text( 

307 "\n", 

308 justify=justify, 

309 overflow=overflow, 

310 no_wrap=no_wrap, 

311 end=end, 

312 tab_size=tab_size, 

313 style=style, 

314 ) 

315 decoder = AnsiDecoder() 

316 result = joiner.join(line for line in decoder.decode(text)) 

317 return result 

318 

319 @classmethod 

320 def styled( 

321 cls, 

322 text: str, 

323 style: StyleType = "", 

324 *, 

325 justify: "JustifyMethod | None" = None, 

326 overflow: "OverflowMethod | None" = None, 

327 ) -> "Text": 

328 """Construct a Text instance with a pre-applied styled. A style applied in this way won't be used 

329 to pad the text when it is justified. 

330 

331 Args: 

332 text (str): A string containing console markup. 

333 style (str | Style): Style to apply to the text. Defaults to "". 

334 justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. 

335 overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. 

336 

337 Returns: 

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

339 """ 

340 styled_text = cls(text, justify=justify, overflow=overflow) 

341 styled_text.stylize(style) 

342 return styled_text 

343 

344 @classmethod 

345 def assemble( 

346 cls, 

347 *parts: "str | Text | tuple[str, StyleType]", 

348 style: str | Style = "", 

349 justify: "JustifyMethod | None" = None, 

350 overflow: "OverflowMethod | None" = None, 

351 no_wrap: bool | None = None, 

352 end: str = "\n", 

353 tab_size: int = 8, 

354 meta: dict[str, Any] | None = None, 

355 ) -> "Text": 

356 """Construct a text instance by combining a sequence of strings with optional styles. 

357 The positional arguments should be either strings, or a tuple of string + style. 

358 

359 Args: 

360 style (str | Style, optional): Base style for text. Defaults to "". 

361 justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. 

362 overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. 

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

364 end (str, optional): Character to end text with. Defaults to "\\\\n". 

365 tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None. 

366 meta (dict[str, Any], optional). Meta data to apply to text, or None for no meta data. Default to None 

367 

368 Returns: 

369 Text: A new text instance. 

370 """ 

371 text = cls( 

372 style=style, 

373 justify=justify, 

374 overflow=overflow, 

375 no_wrap=no_wrap, 

376 end=end, 

377 tab_size=tab_size, 

378 ) 

379 append = text.append 

380 _Text = Text 

381 for part in parts: 

382 if isinstance(part, (_Text, str)): 

383 append(part) 

384 else: 

385 append(*part) 

386 if meta: 

387 text.apply_meta(meta) 

388 return text 

389 

390 @property 

391 def plain(self) -> str: 

392 """Get the text as a single string.""" 

393 if len(self._text) != 1: 

394 self._text[:] = ["".join(self._text)] 

395 return self._text[0] 

396 

397 @plain.setter 

398 def plain(self, new_text: str) -> None: 

399 """Set the text to a new value.""" 

400 if new_text != self.plain: 

401 sanitized_text = strip_control_codes(new_text) 

402 self._text[:] = [sanitized_text] 

403 old_length = self._length 

404 self._length = len(sanitized_text) 

405 if old_length > self._length: 

406 self._trim_spans() 

407 

408 @property 

409 def spans(self) -> list[Span]: 

410 """Get a reference to the internal list of spans.""" 

411 return self._spans 

412 

413 @spans.setter 

414 def spans(self, spans: list[Span]) -> None: 

415 """Set spans.""" 

416 self._spans = spans[:] 

417 

418 def blank_copy(self, plain: str = "") -> "Text": 

419 """Return a new Text instance with copied metadata (but not the string or spans).""" 

420 copy_self = Text( 

421 plain, 

422 style=self.style, 

423 justify=self.justify, 

424 overflow=self.overflow, 

425 no_wrap=self.no_wrap, 

426 end=self.end, 

427 tab_size=self.tab_size, 

428 ) 

429 return copy_self 

430 

431 def copy(self) -> "Text": 

432 """Return a copy of this instance.""" 

433 copy_self = Text( 

434 self.plain, 

435 style=self.style, 

436 justify=self.justify, 

437 overflow=self.overflow, 

438 no_wrap=self.no_wrap, 

439 end=self.end, 

440 tab_size=self.tab_size, 

441 ) 

442 copy_self._spans[:] = self._spans 

443 return copy_self 

444 

445 def stylize( 

446 self, 

447 style: str | Style, 

448 start: int = 0, 

449 end: int | None = None, 

450 ) -> None: 

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

452 

453 Args: 

454 style (str | Style): Style instance or style definition to apply. 

455 start (int): Start offset (negative indexing is supported). Defaults to 0. 

456 end (int | None, optional): End offset (negative indexing is supported), or None for end of text. Defaults to None. 

457 """ 

458 if style: 

459 length = len(self) 

460 if start < 0: 

461 start = length + start 

462 if end is None: 

463 end = length 

464 if end < 0: 

465 end = length + end 

466 if start >= length or end <= start: 

467 # Span not in text or not valid 

468 return 

469 self._spans.append(Span(start, min(length, end), style)) 

470 

471 def stylize_before( 

472 self, 

473 style: str | Style, 

474 start: int = 0, 

475 end: int | None = None, 

476 ) -> None: 

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

478 

479 Args: 

480 style (str | Style): Style instance or style definition to apply. 

481 start (int): Start offset (negative indexing is supported). Defaults to 0. 

482 end (int | None, optional): End offset (negative indexing is supported), or None for end of text. Defaults to None. 

483 """ 

484 if style: 

485 length = len(self) 

486 if start < 0: 

487 start = length + start 

488 if end is None: 

489 end = length 

490 if end < 0: 

491 end = length + end 

492 if start >= length or end <= start: 

493 # Span not in text or not valid 

494 return 

495 self._spans.insert(0, Span(start, min(length, end), style)) 

496 

497 def apply_meta( 

498 self, meta: dict[str, Any], start: int = 0, end: int | None = None 

499 ) -> None: 

500 """Apply metadata to the text, or a portion of the text. 

501 

502 Args: 

503 meta (dict[str, Any]): A dict of meta information. 

504 start (int): Start offset (negative indexing is supported). Defaults to 0. 

505 end (int | None, optional): End offset (negative indexing is supported), or None for end of text. Defaults to None. 

506 

507 """ 

508 style = Style.from_meta(meta) 

509 self.stylize(style, start=start, end=end) 

510 

511 def on(self, meta: dict[str, Any] | None = None, **handlers: Any) -> "Text": 

512 """Apply event handlers (used by Textual project). 

513 

514 Example: 

515 >>> from rich.text import Text 

516 >>> text = Text("hello world") 

517 >>> text.on(click="view.toggle('world')") 

518 

519 Args: 

520 meta (dict[str, Any]): Mapping of meta information. 

521 **handlers: Keyword args are prefixed with "@" to defined handlers. 

522 

523 Returns: 

524 Text: Self is returned to method may be chained. 

525 """ 

526 meta = {} if meta is None else meta 

527 meta.update({f"@{key}": value for key, value in handlers.items()}) 

528 self.stylize(Style.from_meta(meta)) 

529 return self 

530 

531 def remove_suffix(self, suffix: str) -> None: 

532 """Remove a suffix if it exists. 

533 

534 Args: 

535 suffix (str): Suffix to remove. 

536 """ 

537 if self.plain.endswith(suffix): 

538 self.right_crop(len(suffix)) 

539 

540 def get_style_at_offset(self, console: "Console", offset: int) -> Style: 

541 """Get the style of a character at give offset. 

542 

543 Args: 

544 console (~Console): Console where text will be rendered. 

545 offset (int): Offset in to text (negative indexing supported) 

546 

547 Returns: 

548 Style: A Style instance. 

549 """ 

550 # TODO: This is a little inefficient, it is only used by full justify 

551 if offset < 0: 

552 offset = len(self) + offset 

553 get_style = console.get_style 

554 style = get_style(self.style).copy() 

555 for start, end, span_style in self._spans: 

556 if end > offset >= start: 

557 style += get_style(span_style, default="") 

558 return style 

559 

560 def extend_style(self, spaces: int) -> None: 

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

562 

563 Args: 

564 spaces (int): Number of spaces to add to the Text. 

565 """ 

566 if spaces <= 0: 

567 return 

568 spans = self.spans 

569 new_spaces = " " * spaces 

570 if spans: 

571 end_offset = len(self) 

572 self._spans[:] = [ 

573 span.extend(spaces) if span.end >= end_offset else span 

574 for span in spans 

575 ] 

576 self._text.append(new_spaces) 

577 self._length += spaces 

578 else: 

579 self.plain += new_spaces 

580 

581 def highlight_regex( 

582 self, 

583 re_highlight: Pattern[str] | str, 

584 style: GetStyleCallable | StyleType | None = None, 

585 *, 

586 style_prefix: str = "", 

587 ) -> int: 

588 """Highlight text with a regular expression, where group names are 

589 translated to styles. 

590 

591 Args: 

592 re_highlight (re.Pattern | str): A regular expression object or string. 

593 style (GetStyleCallable | StyleType): Optional style to apply to whole match, or a callable 

594 which accepts the matched text and returns a style. Defaults to None. 

595 style_prefix (str, optional): Optional prefix to add to style group names. 

596 

597 Returns: 

598 int: Number of regex matches 

599 """ 

600 count = 0 

601 append_span = self._spans.append 

602 _Span = Span 

603 plain = self.plain 

604 if isinstance(re_highlight, str): 

605 re_highlight = re.compile(re_highlight) 

606 for match in re_highlight.finditer(plain): 

607 get_span = match.span 

608 if style: 

609 start, end = get_span() 

610 match_style = style(plain[start:end]) if callable(style) else style 

611 if match_style is not None and end > start: 

612 append_span(_Span(start, end, match_style)) 

613 

614 count += 1 

615 for name in match.groupdict().keys(): 

616 start, end = get_span(name) 

617 if start != -1 and end > start: 

618 append_span(_Span(start, end, f"{style_prefix}{name}")) 

619 return count 

620 

621 def highlight_words( 

622 self, 

623 words: Iterable[str], 

624 style: str | Style, 

625 *, 

626 case_sensitive: bool = True, 

627 ) -> int: 

628 """Highlight words with a style. 

629 

630 Args: 

631 words (Iterable[str]): Words to highlight. 

632 style (str | Style): Style to apply. 

633 case_sensitive (bool, optional): Enable case sensitive matching. Defaults to True. 

634 

635 Returns: 

636 int: Number of words highlighted. 

637 """ 

638 re_words = "|".join(re.escape(word) for word in words) 

639 add_span = self._spans.append 

640 count = 0 

641 _Span = Span 

642 for match in re.finditer( 

643 re_words, self.plain, flags=0 if case_sensitive else re.IGNORECASE 

644 ): 

645 start, end = match.span(0) 

646 add_span(_Span(start, end, style)) 

647 count += 1 

648 return count 

649 

650 def rstrip(self) -> None: 

651 """Strip whitespace from end of text.""" 

652 self.plain = self.plain.rstrip() 

653 

654 def rstrip_end(self, size: int) -> None: 

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

656 

657 Args: 

658 size (int): The desired size of the text. 

659 """ 

660 text_length = len(self) 

661 if text_length > size: 

662 excess = text_length - size 

663 whitespace_match = _re_whitespace.search(self.plain) 

664 if whitespace_match is not None: 

665 whitespace_count = len(whitespace_match.group(0)) 

666 self.right_crop(min(whitespace_count, excess)) 

667 

668 def set_length(self, new_length: int) -> None: 

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

670 length = len(self) 

671 if length != new_length: 

672 if length < new_length: 

673 self.pad_right(new_length - length) 

674 else: 

675 self.right_crop(length - new_length) 

676 

677 def __rich_console__( 

678 self, console: "Console", options: "ConsoleOptions" 

679 ) -> Iterable[Segment]: 

680 tab_size: int = console.tab_size if self.tab_size is None else self.tab_size 

681 justify = self.justify or options.justify or DEFAULT_JUSTIFY 

682 overflow = self.overflow or options.overflow or DEFAULT_OVERFLOW 

683 

684 lines = self.wrap( 

685 console, 

686 options.max_width, 

687 justify=justify, 

688 overflow=overflow, 

689 tab_size=tab_size or 8, 

690 no_wrap=pick_bool(self.no_wrap, options.no_wrap, False), 

691 ) 

692 all_lines = Text("\n").join(lines) 

693 yield from all_lines.render(console, end=self.end) 

694 

695 def __rich_measure__( 

696 self, console: "Console", options: "ConsoleOptions" 

697 ) -> Measurement: 

698 text = self.plain 

699 lines = text.splitlines() 

700 max_text_width = max(cell_len(line) for line in lines) if lines else 0 

701 words = text.split() 

702 min_text_width = ( 

703 max(cell_len(word) for word in words) if words else max_text_width 

704 ) 

705 return Measurement(min_text_width, max_text_width) 

706 

707 def render(self, console: "Console", end: str = "") -> Iterable["Segment"]: 

708 """Render the text as Segments. 

709 

710 Args: 

711 console (Console): Console instance. 

712 end (str | None, optional): Optional end character. 

713 

714 Returns: 

715 Iterable[Segment]: Result of render that may be written to the console. 

716 """ 

717 _Segment = Segment 

718 text = self.plain 

719 if not self._spans: 

720 yield Segment(text) 

721 if end: 

722 yield _Segment(end) 

723 return 

724 get_style = partial(console.get_style, default=Style.null()) 

725 

726 enumerated_spans = list(enumerate(self._spans, 1)) 

727 style_map = {index: get_style(span.style) for index, span in enumerated_spans} 

728 style_map[0] = get_style(self.style) 

729 

730 spans = [ 

731 (0, False, 0), 

732 *((span.start, False, index) for index, span in enumerated_spans), 

733 *((span.end, True, index) for index, span in enumerated_spans), 

734 (len(text), True, 0), 

735 ] 

736 spans.sort(key=itemgetter(0, 1)) 

737 

738 stack: list[int] = [] 

739 stack_append = stack.append 

740 stack_pop = stack.remove 

741 

742 style_cache: dict[tuple[Style, ...], Style] = {} 

743 style_cache_get = style_cache.get 

744 combine = Style.combine 

745 

746 def get_current_style() -> Style: 

747 """Construct current style from stack.""" 

748 styles = tuple(style_map[_style_id] for _style_id in sorted(stack)) 

749 cached_style = style_cache_get(styles) 

750 if cached_style is not None: 

751 return cached_style 

752 current_style = combine(styles) 

753 style_cache[styles] = current_style 

754 return current_style 

755 

756 for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]): 

757 if leaving: 

758 stack_pop(style_id) 

759 else: 

760 stack_append(style_id) 

761 if next_offset > offset: 

762 yield _Segment(text[offset:next_offset], get_current_style()) 

763 if end: 

764 yield _Segment(end) 

765 

766 def join(self, lines: Iterable["Text"]) -> "Text": 

767 """Join text together with this instance as the separator. 

768 

769 Args: 

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

771 

772 Returns: 

773 Text: A new text instance containing join text. 

774 """ 

775 

776 new_text = self.blank_copy() 

777 

778 def iter_text() -> Iterable["Text"]: 

779 if self.plain: 

780 for last, line in loop_last(lines): 

781 yield line 

782 if not last: 

783 yield self 

784 else: 

785 yield from lines 

786 

787 extend_text = new_text._text.extend 

788 append_span = new_text._spans.append 

789 extend_spans = new_text._spans.extend 

790 offset = 0 

791 _Span = Span 

792 

793 for text in iter_text(): 

794 extend_text(text._text) 

795 if text.style: 

796 append_span(_Span(offset, offset + len(text), text.style)) 

797 extend_spans( 

798 _Span(offset + start, offset + end, style) 

799 for start, end, style in text._spans 

800 ) 

801 offset += len(text) 

802 new_text._length = offset 

803 return new_text 

804 

805 def expand_tabs(self, tab_size: int | None = None) -> None: 

806 """Converts tabs to spaces. 

807 

808 Args: 

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

810 

811 """ 

812 if "\t" not in self.plain: 

813 return 

814 if tab_size is None: 

815 tab_size = self.tab_size 

816 if tab_size is None: 

817 tab_size = 8 

818 

819 new_text: list[Text] = [] 

820 append = new_text.append 

821 

822 for line in self.split("\n", include_separator=True): 

823 if "\t" not in line.plain: 

824 append(line) 

825 else: 

826 cell_position = 0 

827 parts = line.split("\t", include_separator=True) 

828 for part in parts: 

829 if part.plain.endswith("\t"): 

830 part._text[-1] = part._text[-1][:-1] + " " 

831 cell_position += part.cell_len 

832 tab_remainder = cell_position % tab_size 

833 if tab_remainder: 

834 spaces = tab_size - tab_remainder 

835 part.extend_style(spaces) 

836 cell_position += spaces 

837 else: 

838 cell_position += part.cell_len 

839 append(part) 

840 

841 result = Text("").join(new_text) 

842 

843 self._text = [result.plain] 

844 self._length = len(self.plain) 

845 self._spans[:] = result._spans 

846 

847 def truncate( 

848 self, 

849 max_width: int, 

850 *, 

851 overflow: "OverflowMethod | None" = None, 

852 pad: bool = False, 

853 ) -> None: 

854 """Truncate text if it is longer that a given width. 

855 

856 Args: 

857 max_width (int): Maximum number of characters in text. 

858 overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None, to use self.overflow. 

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

860 """ 

861 _overflow = overflow or self.overflow or DEFAULT_OVERFLOW 

862 if _overflow != "ignore": 

863 length = cell_len(self.plain) 

864 if length > max_width: 

865 if _overflow == "ellipsis": 

866 self.plain = set_cell_size(self.plain, max_width - 1) + "…" 

867 else: 

868 self.plain = set_cell_size(self.plain, max_width) 

869 if pad and length < max_width: 

870 spaces = max_width - length 

871 self._text = [f"{self.plain}{' ' * spaces}"] 

872 self._length = len(self.plain) 

873 

874 def _trim_spans(self) -> None: 

875 """Remove or modify any spans that are over the end of the text.""" 

876 max_offset = len(self.plain) 

877 _Span = Span 

878 self._spans[:] = [ 

879 ( 

880 span 

881 if span.end < max_offset 

882 else _Span(span.start, min(max_offset, span.end), span.style) 

883 ) 

884 for span in self._spans 

885 if span.start < max_offset 

886 ] 

887 

888 def pad(self, count: int, character: str = " ") -> None: 

889 """Pad left and right with a given number of characters. 

890 

891 Args: 

892 count (int): Width of padding. 

893 character (str): The character to pad with. Must be a string of length 1. 

894 """ 

895 assert len(character) == 1, "Character must be a string of length 1" 

896 if count: 

897 pad_characters = character * count 

898 self.plain = f"{pad_characters}{self.plain}{pad_characters}" 

899 _Span = Span 

900 self._spans[:] = [ 

901 _Span(start + count, end + count, style) 

902 for start, end, style in self._spans 

903 ] 

904 

905 def pad_left(self, count: int, character: str = " ") -> None: 

906 """Pad the left with a given character. 

907 

908 Args: 

909 count (int): Number of characters to pad. 

910 character (str, optional): Character to pad with. Defaults to " ". 

911 """ 

912 assert len(character) == 1, "Character must be a string of length 1" 

913 if count: 

914 self.plain = f"{character * count}{self.plain}" 

915 _Span = Span 

916 self._spans[:] = [ 

917 _Span(start + count, end + count, style) 

918 for start, end, style in self._spans 

919 ] 

920 

921 def pad_right(self, count: int, character: str = " ") -> None: 

922 """Pad the right with a given character. 

923 

924 Args: 

925 count (int): Number of characters to pad. 

926 character (str, optional): Character to pad with. Defaults to " ". 

927 """ 

928 assert len(character) == 1, "Character must be a string of length 1" 

929 if count: 

930 self.plain = f"{self.plain}{character * count}" 

931 

932 def align(self, align: AlignMethod, width: int, character: str = " ") -> None: 

933 """Align text to a given width. 

934 

935 Args: 

936 align (AlignMethod): One of "left", "center", or "right". 

937 width (int): Desired width. 

938 character (str, optional): Character to pad with. Defaults to " ". 

939 """ 

940 self.truncate(width) 

941 excess_space = width - cell_len(self.plain) 

942 if excess_space: 

943 if align == "left": 

944 self.pad_right(excess_space, character) 

945 elif align == "center": 

946 left = excess_space // 2 

947 self.pad_left(left, character) 

948 self.pad_right(excess_space - left, character) 

949 else: 

950 self.pad_left(excess_space, character) 

951 

952 def append(self, text: "Text | str", style: "str | Style | None" = None) -> "Text": 

953 """Add text with an optional style. 

954 

955 Args: 

956 text (Text | str): A str or Text to append. 

957 style (str, optional): A style name. Defaults to None. 

958 

959 Returns: 

960 Text: Returns self for chaining. 

961 """ 

962 

963 if not isinstance(text, (str, Text)): 

964 raise TypeError("Only str or Text can be appended to Text") 

965 

966 if len(text): 

967 if isinstance(text, str): 

968 sanitized_text = strip_control_codes(text) 

969 self._text.append(sanitized_text) 

970 offset = len(self) 

971 text_length = len(sanitized_text) 

972 if style: 

973 self._spans.append(Span(offset, offset + text_length, style)) 

974 self._length += text_length 

975 elif isinstance(text, Text): 

976 _Span = Span 

977 if style is not None: 

978 raise ValueError( 

979 "style must not be set when appending Text instance" 

980 ) 

981 text_length = self._length 

982 if text.style: 

983 self._spans.append( 

984 _Span(text_length, text_length + len(text), text.style) 

985 ) 

986 self._text.append(text.plain) 

987 self._spans.extend( 

988 _Span(start + text_length, end + text_length, style) 

989 for start, end, style in text._spans.copy() 

990 ) 

991 self._length += len(text) 

992 return self 

993 

994 def append_text(self, text: "Text") -> "Text": 

995 """Append another Text instance. This method is more performant than Text.append, but 

996 only works for Text. 

997 

998 Args: 

999 text (Text): The Text instance to append to this instance. 

1000 

1001 Returns: 

1002 Text: Returns self for chaining. 

1003 """ 

1004 _Span = Span 

1005 text_length = self._length 

1006 if text.style: 

1007 self._spans.append(_Span(text_length, text_length + len(text), text.style)) 

1008 self._text.append(text.plain) 

1009 self._spans.extend( 

1010 _Span(start + text_length, end + text_length, style) 

1011 for start, end, style in text._spans.copy() 

1012 ) 

1013 self._length += len(text) 

1014 return self 

1015 

1016 def append_tokens(self, tokens: Iterable[tuple[str, StyleType | None]]) -> "Text": 

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

1018 

1019 Args: 

1020 tokens (Iterable[tuple[str, StyleType | None]]): An iterable of tuples containing str content and style. 

1021 

1022 Returns: 

1023 Text: Returns self for chaining. 

1024 """ 

1025 append_text = self._text.append 

1026 append_span = self._spans.append 

1027 _Span = Span 

1028 offset = len(self) 

1029 for content, style in tokens: 

1030 content = strip_control_codes(content) 

1031 append_text(content) 

1032 if style: 

1033 append_span(_Span(offset, offset + len(content), style)) 

1034 offset += len(content) 

1035 self._length = offset 

1036 return self 

1037 

1038 def copy_styles(self, text: "Text") -> None: 

1039 """Copy styles from another Text instance. 

1040 

1041 Args: 

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

1043 """ 

1044 self._spans.extend(text._spans) 

1045 

1046 def split( 

1047 self, 

1048 separator: str = "\n", 

1049 *, 

1050 include_separator: bool = False, 

1051 allow_blank: bool = False, 

1052 ) -> Lines: 

1053 """Split rich text in to lines, preserving styles. 

1054 

1055 Args: 

1056 separator (str, optional): String to split on. Defaults to "\\\\n". 

1057 include_separator (bool, optional): Include the separator in the lines. Defaults to False. 

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

1059 

1060 Returns: 

1061 list[RichText]: A list of rich text, one per line of the original. 

1062 """ 

1063 assert separator, "separator must not be empty" 

1064 

1065 text = self.plain 

1066 if separator not in text: 

1067 return Lines([self.copy()]) 

1068 

1069 if include_separator: 

1070 lines = self.divide( 

1071 match.end() for match in re.finditer(re.escape(separator), text) 

1072 ) 

1073 else: 

1074 

1075 def flatten_spans() -> Iterable[int]: 

1076 for match in re.finditer(re.escape(separator), text): 

1077 start, end = match.span() 

1078 yield start 

1079 yield end 

1080 

1081 lines = Lines( 

1082 line for line in self.divide(flatten_spans()) if line.plain != separator 

1083 ) 

1084 

1085 if not allow_blank and text.endswith(separator): 

1086 lines.pop() 

1087 

1088 return lines 

1089 

1090 def divide(self, offsets: Iterable[int]) -> Lines: 

1091 """Divide text into a number of lines at given offsets. 

1092 

1093 Args: 

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

1095 

1096 Returns: 

1097 Lines: New RichText instances between offsets. 

1098 """ 

1099 _offsets = list(offsets) 

1100 

1101 if not _offsets: 

1102 return Lines([self.copy()]) 

1103 

1104 text = self.plain 

1105 text_length = len(text) 

1106 divide_offsets = [0, *_offsets, text_length] 

1107 line_ranges = list(zip(divide_offsets, divide_offsets[1:])) 

1108 

1109 style = self.style 

1110 justify = self.justify 

1111 overflow = self.overflow 

1112 _Text = Text 

1113 new_lines = Lines( 

1114 _Text( 

1115 text[start:end], 

1116 style=style, 

1117 justify=justify, 

1118 overflow=overflow, 

1119 ) 

1120 for start, end in line_ranges 

1121 ) 

1122 if not self._spans: 

1123 return new_lines 

1124 

1125 _line_appends = [line._spans.append for line in new_lines._lines] 

1126 line_count = len(line_ranges) 

1127 _Span = Span 

1128 

1129 for span_start, span_end, style in self._spans: 

1130 lower_bound = 0 

1131 upper_bound = line_count 

1132 start_line_no = (lower_bound + upper_bound) // 2 

1133 

1134 while True: 

1135 line_start, line_end = line_ranges[start_line_no] 

1136 if span_start < line_start: 

1137 upper_bound = start_line_no - 1 

1138 elif span_start > line_end: 

1139 lower_bound = start_line_no + 1 

1140 else: 

1141 break 

1142 start_line_no = (lower_bound + upper_bound) // 2 

1143 

1144 if span_end < line_end: 

1145 end_line_no = start_line_no 

1146 else: 

1147 end_line_no = lower_bound = start_line_no 

1148 upper_bound = line_count 

1149 

1150 while True: 

1151 line_start, line_end = line_ranges[end_line_no] 

1152 if span_end < line_start: 

1153 upper_bound = end_line_no - 1 

1154 elif span_end > line_end: 

1155 lower_bound = end_line_no + 1 

1156 else: 

1157 break 

1158 end_line_no = (lower_bound + upper_bound) // 2 

1159 

1160 for line_no in range(start_line_no, end_line_no + 1): 

1161 line_start, line_end = line_ranges[line_no] 

1162 new_start = max(0, span_start - line_start) 

1163 new_end = min(span_end - line_start, line_end - line_start) 

1164 if new_end > new_start: 

1165 _line_appends[line_no](_Span(new_start, new_end, style)) 

1166 

1167 return new_lines 

1168 

1169 def right_crop(self, amount: int = 1) -> None: 

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

1171 max_offset = len(self.plain) - amount 

1172 _Span = Span 

1173 self._spans[:] = [ 

1174 ( 

1175 span 

1176 if span.end < max_offset 

1177 else _Span(span.start, min(max_offset, span.end), span.style) 

1178 ) 

1179 for span in self._spans 

1180 if span.start < max_offset 

1181 ] 

1182 self._text = [self.plain[:-amount]] 

1183 self._length -= amount 

1184 

1185 def wrap( 

1186 self, 

1187 console: "Console", 

1188 width: int, 

1189 *, 

1190 justify: "JustifyMethod | None" = None, 

1191 overflow: "OverflowMethod | None" = None, 

1192 tab_size: int = 8, 

1193 no_wrap: bool | None = None, 

1194 ) -> Lines: 

1195 """Word wrap the text. 

1196 

1197 Args: 

1198 console (Console): Console instance. 

1199 width (int): Number of cells available per line. 

1200 justify (str, optional): Justify method: "default", "left", "center", "full", "right". Defaults to "default". 

1201 overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None. 

1202 tab_size (int, optional): Default tab size. Defaults to 8. 

1203 no_wrap (bool, optional): Disable wrapping, Defaults to False. 

1204 

1205 Returns: 

1206 Lines: Number of lines. 

1207 """ 

1208 wrap_justify = justify or self.justify or DEFAULT_JUSTIFY 

1209 wrap_overflow = overflow or self.overflow or DEFAULT_OVERFLOW 

1210 

1211 no_wrap = pick_bool(no_wrap, self.no_wrap, False) or overflow == "ignore" 

1212 

1213 lines = Lines() 

1214 for line in self.split(allow_blank=True): 

1215 if "\t" in line: 

1216 line.expand_tabs(tab_size) 

1217 if no_wrap: 

1218 if overflow == "ignore": 

1219 lines.append(line) 

1220 continue 

1221 new_lines = Lines([line]) 

1222 else: 

1223 offsets = divide_line(str(line), width, fold=wrap_overflow == "fold") 

1224 new_lines = line.divide(offsets) 

1225 for line in new_lines: 

1226 line.rstrip_end(width) 

1227 if wrap_justify: 

1228 new_lines.justify( 

1229 console, width, justify=wrap_justify, overflow=wrap_overflow 

1230 ) 

1231 for line in new_lines: 

1232 line.truncate(width, overflow=wrap_overflow) 

1233 lines.extend(new_lines) 

1234 return lines 

1235 

1236 def fit(self, width: int) -> Lines: 

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

1238 

1239 Args: 

1240 width (int): Maximum characters in a line. 

1241 

1242 Returns: 

1243 Lines: Lines container. 

1244 """ 

1245 lines: Lines = Lines() 

1246 append = lines.append 

1247 for line in self.split(): 

1248 line.set_length(width) 

1249 append(line) 

1250 return lines 

1251 

1252 def detect_indentation(self) -> int: 

1253 """Auto-detect indentation of code. 

1254 

1255 Returns: 

1256 int: Number of spaces used to indent code. 

1257 """ 

1258 

1259 _indentations = { 

1260 len(match.group(1)) 

1261 for match in re.finditer(r"^( *)(.*)$", self.plain, flags=re.MULTILINE) 

1262 } 

1263 

1264 try: 

1265 indentation = ( 

1266 reduce(gcd, [indent for indent in _indentations if not indent % 2]) or 1 

1267 ) 

1268 except TypeError: 

1269 indentation = 1 

1270 

1271 return indentation 

1272 

1273 def with_indent_guides( 

1274 self, 

1275 indent_size: int | None = None, 

1276 *, 

1277 character: str = "│", 

1278 style: StyleType = "dim green", 

1279 ) -> "Text": 

1280 """Adds indent guide lines to text. 

1281 

1282 Args: 

1283 indent_size (int | None): Size of indentation, or None to auto detect. Defaults to None. 

1284 character (str, optional): Character to use for indentation. Defaults to "│". 

1285 style (Style | str, optional): Style of indent guides. 

1286 

1287 Returns: 

1288 Text: New text with indentation guides. 

1289 """ 

1290 

1291 _indent_size = self.detect_indentation() if indent_size is None else indent_size 

1292 

1293 text = self.copy() 

1294 text.expand_tabs() 

1295 indent_line = f"{character}{' ' * (_indent_size - 1)}" 

1296 

1297 re_indent = re.compile(r"^( *)(.*)$") 

1298 new_lines: list[Text] = [] 

1299 add_line = new_lines.append 

1300 blank_lines = 0 

1301 for line in text.split(allow_blank=True): 

1302 match = re_indent.match(line.plain) 

1303 if not match or not match.group(2): 

1304 blank_lines += 1 

1305 continue 

1306 indent = match.group(1) 

1307 full_indents, remaining_space = divmod(len(indent), _indent_size) 

1308 new_indent = f"{indent_line * full_indents}{' ' * remaining_space}" 

1309 line.plain = new_indent + line.plain[len(new_indent) :] 

1310 line.stylize(style, 0, len(new_indent)) 

1311 if blank_lines: 

1312 new_lines.extend([Text(new_indent, style=style)] * blank_lines) 

1313 blank_lines = 0 

1314 add_line(line) 

1315 if blank_lines: 

1316 new_lines.extend([Text("", style=style)] * blank_lines) 

1317 

1318 new_text = text.blank_copy("\n").join(new_lines) 

1319 return new_text 

1320 

1321 

1322if __name__ == "__main__": # pragma: no cover 

1323 from rich.console import Console 

1324 

1325 text = Text( 

1326 """\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n""" 

1327 ) 

1328 text.highlight_words(["Lorem"], "bold") 

1329 text.highlight_words(["ipsum"], "italic") 

1330 

1331 console = Console() 

1332 

1333 console.rule("justify='left'") 

1334 console.print(text, style="red") 

1335 console.print() 

1336 

1337 console.rule("justify='center'") 

1338 console.print(text, style="green", justify="center") 

1339 console.print() 

1340 

1341 console.rule("justify='right'") 

1342 console.print(text, style="blue", justify="right") 

1343 console.print() 

1344 

1345 console.rule("justify='full'") 

1346 console.print(text, style="magenta", justify="full") 

1347 console.print()