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

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

331 statements  

1from enum import IntEnum 

2from functools import lru_cache 

3from itertools import filterfalse 

4from operator import attrgetter 

5from typing import TYPE_CHECKING, Iterable, NamedTuple, Sequence 

6 

7from .cells import ( 

8 _is_single_cell_widths, 

9 cached_cell_len, 

10 cell_len, 

11 get_character_cell_size, 

12 set_cell_size, 

13) 

14from .repr import Result, rich_repr 

15from .style import Style 

16 

17if TYPE_CHECKING: 

18 from .console import Console, ConsoleOptions, RenderResult 

19 

20 

21class ControlType(IntEnum): 

22 """Non-printable control codes which typically translate to ANSI codes.""" 

23 

24 BELL = 1 

25 CARRIAGE_RETURN = 2 

26 HOME = 3 

27 CLEAR = 4 

28 SHOW_CURSOR = 5 

29 HIDE_CURSOR = 6 

30 ENABLE_ALT_SCREEN = 7 

31 DISABLE_ALT_SCREEN = 8 

32 CURSOR_UP = 9 

33 CURSOR_DOWN = 10 

34 CURSOR_FORWARD = 11 

35 CURSOR_BACKWARD = 12 

36 CURSOR_MOVE_TO_COLUMN = 13 

37 CURSOR_MOVE_TO = 14 

38 ERASE_IN_LINE = 15 

39 SET_WINDOW_TITLE = 16 

40 

41 

42ControlCode = ( 

43 tuple[ControlType] | tuple[ControlType, int | str] | tuple[ControlType, int, int] 

44) 

45 

46 

47@rich_repr() 

48class Segment(NamedTuple): 

49 """A piece of text with associated style. Segments are produced by the Console render process and 

50 are ultimately converted in to strings to be written to the terminal. 

51 

52 Args: 

53 text (str): A piece of text. 

54 style (:class:`~rich.style.Style`, optional): An optional style to apply to the text. 

55 control (tuple[ControlCode], optional): Optional sequence of control codes. 

56 

57 Attributes: 

58 cell_length (int): The cell length of this Segment. 

59 """ 

60 

61 text: str 

62 style: Style | None = None 

63 control: Sequence[ControlCode] | None = None 

64 

65 @property 

66 def cell_length(self) -> int: 

67 """The number of terminal cells required to display self.text. 

68 

69 Returns: 

70 int: A number of cells. 

71 """ 

72 text, _style, control = self 

73 return 0 if control else cell_len(text) 

74 

75 def __rich_repr__(self) -> Result: 

76 yield self.text 

77 if self.control is None: 

78 if self.style is not None: 

79 yield self.style 

80 else: 

81 yield self.style 

82 yield self.control 

83 

84 def __bool__(self) -> bool: 

85 """Check if the segment contains text.""" 

86 return bool(self.text) 

87 

88 @property 

89 def is_control(self) -> bool: 

90 """Check if the segment contains control codes.""" 

91 return self.control is not None 

92 

93 @classmethod 

94 @lru_cache(1024 * 16) 

95 def _split_cells(cls, segment: "Segment", cut: int) -> tuple["Segment", "Segment"]: 

96 """Split a segment in to two at a given cell position. 

97 

98 Note that splitting a double-width character, may result in that character turning 

99 into two spaces. 

100 

101 Args: 

102 segment (Segment): A segment to split. 

103 cut (int): A cell position to cut on. 

104 

105 Returns: 

106 A tuple of two segments. 

107 """ 

108 text, style, control = segment 

109 _Segment = Segment 

110 cell_length = segment.cell_length 

111 if cut >= cell_length: 

112 return segment, _Segment("", style, control) 

113 

114 cell_size = get_character_cell_size 

115 

116 pos = int((cut / cell_length) * len(text)) 

117 

118 while True: 

119 before = text[:pos] 

120 cell_pos = cell_len(before) 

121 out_by = cell_pos - cut 

122 if not out_by: 

123 return ( 

124 _Segment(before, style, control), 

125 _Segment(text[pos:], style, control), 

126 ) 

127 if out_by == -1 and cell_size(text[pos]) == 2: 

128 return ( 

129 _Segment(text[:pos] + " ", style, control), 

130 _Segment(" " + text[pos + 1 :], style, control), 

131 ) 

132 if out_by == +1 and cell_size(text[pos - 1]) == 2: 

133 return ( 

134 _Segment(text[: pos - 1] + " ", style, control), 

135 _Segment(" " + text[pos:], style, control), 

136 ) 

137 if cell_pos < cut: 

138 pos += 1 

139 else: 

140 pos -= 1 

141 

142 def split_cells(self, cut: int) -> tuple["Segment", "Segment"]: 

143 """Split segment in to two segments at the specified column. 

144 

145 If the cut point falls in the middle of a 2-cell wide character then it is replaced 

146 by two spaces, to preserve the display width of the parent segment. 

147 

148 Args: 

149 cut (int): Offset within the segment to cut. 

150 

151 Returns: 

152 tuple[Segment, Segment]: Two segments. 

153 """ 

154 text, style, control = self 

155 assert cut >= 0 

156 

157 if _is_single_cell_widths(text): 

158 # Fast path with all 1 cell characters 

159 if cut >= len(text): 

160 return self, Segment("", style, control) 

161 return ( 

162 Segment(text[:cut], style, control), 

163 Segment(text[cut:], style, control), 

164 ) 

165 

166 return self._split_cells(self, cut) 

167 

168 @classmethod 

169 def line(cls) -> "Segment": 

170 """Make a new line segment.""" 

171 return cls("\n") 

172 

173 @classmethod 

174 def apply_style( 

175 cls, 

176 segments: Iterable["Segment"], 

177 style: Style | None = None, 

178 post_style: Style | None = None, 

179 ) -> Iterable["Segment"]: 

180 """Apply style(s) to an iterable of segments. 

181 

182 Returns an iterable of segments where the style is replaced by ``style + segment.style + post_style``. 

183 

184 Args: 

185 segments (Iterable[Segment]): Segments to process. 

186 style (Style, optional): Base style. Defaults to None. 

187 post_style (Style, optional): Style to apply on top of segment style. Defaults to None. 

188 

189 Returns: 

190 Iterable[Segments]: A new iterable of segments (possibly the same iterable). 

191 """ 

192 result_segments = segments 

193 if style: 

194 apply = style.__add__ 

195 result_segments = ( 

196 cls(text, None if control else apply(_style), control) 

197 for text, _style, control in result_segments 

198 ) 

199 if post_style: 

200 result_segments = ( 

201 cls( 

202 text, 

203 ( 

204 None 

205 if control 

206 else (_style + post_style if _style else post_style) 

207 ), 

208 control, 

209 ) 

210 for text, _style, control in result_segments 

211 ) 

212 return result_segments 

213 

214 @classmethod 

215 def filter_control( 

216 cls, segments: Iterable["Segment"], is_control: bool = False 

217 ) -> Iterable["Segment"]: 

218 """Filter segments by ``is_control`` attribute. 

219 

220 Args: 

221 segments (Iterable[Segment]): An iterable of Segment instances. 

222 is_control (bool, optional): is_control flag to match in search. 

223 

224 Returns: 

225 Iterable[Segment]: And iterable of Segment instances. 

226 

227 """ 

228 if is_control: 

229 return filter(attrgetter("control"), segments) 

230 else: 

231 return filterfalse(attrgetter("control"), segments) 

232 

233 @classmethod 

234 def split_lines(cls, segments: Iterable["Segment"]) -> Iterable[list["Segment"]]: 

235 """Split a sequence of segments in to a list of lines. 

236 

237 Args: 

238 segments (Iterable[Segment]): Segments potentially containing line feeds. 

239 

240 Yields: 

241 Iterable[list[Segment]]: Iterable of segment lists, one per line. 

242 """ 

243 line: list[Segment] = [] 

244 append = line.append 

245 

246 for segment in segments: 

247 if "\n" in segment.text and not segment.control: 

248 text, style, _ = segment 

249 while text: 

250 _text, new_line, text = text.partition("\n") 

251 if _text: 

252 append(cls(_text, style)) 

253 if new_line: 

254 yield line 

255 line = [] 

256 append = line.append 

257 else: 

258 append(segment) 

259 if line: 

260 yield line 

261 

262 @classmethod 

263 def split_lines_terminator( 

264 cls, segments: Iterable["Segment"] 

265 ) -> Iterable[tuple[list["Segment"], bool]]: 

266 """Split a sequence of segments in to a list of lines and a boolean to indicate if there was a new line. 

267 

268 Args: 

269 segments (Iterable[Segment]): Segments potentially containing line feeds. 

270 

271 Yields: 

272 Iterable[list[Segment]]: Iterable of segment lists, one per line. 

273 """ 

274 line: list[Segment] = [] 

275 append = line.append 

276 

277 for segment in segments: 

278 if "\n" in segment.text and not segment.control: 

279 text, style, _ = segment 

280 while text: 

281 _text, new_line, text = text.partition("\n") 

282 if _text: 

283 append(cls(_text, style)) 

284 if new_line: 

285 yield (line, True) 

286 line = [] 

287 append = line.append 

288 else: 

289 append(segment) 

290 if line: 

291 yield (line, False) 

292 

293 @classmethod 

294 def split_and_crop_lines( 

295 cls, 

296 segments: Iterable["Segment"], 

297 length: int, 

298 style: Style | None = None, 

299 pad: bool = True, 

300 include_new_lines: bool = True, 

301 ) -> Iterable[list["Segment"]]: 

302 """Split segments in to lines, and crop lines greater than a given length. 

303 

304 Args: 

305 segments (Iterable[Segment]): An iterable of segments, probably 

306 generated from console.render. 

307 length (int): Desired line length. 

308 style (Style, optional): Style to use for any padding. 

309 pad (bool): Enable padding of lines that are less than `length`. 

310 

311 Returns: 

312 Iterable[list[Segment]]: An iterable of lines of segments. 

313 """ 

314 line: list[Segment] = [] 

315 append = line.append 

316 

317 adjust_line_length = cls.adjust_line_length 

318 new_line_segment = cls("\n") 

319 

320 for segment in segments: 

321 if "\n" in segment.text and not segment.control: 

322 text, segment_style, _ = segment 

323 while text: 

324 _text, new_line, text = text.partition("\n") 

325 if _text: 

326 append(cls(_text, segment_style)) 

327 if new_line: 

328 cropped_line = adjust_line_length( 

329 line, length, style=style, pad=pad 

330 ) 

331 if include_new_lines: 

332 cropped_line.append(new_line_segment) 

333 yield cropped_line 

334 line.clear() 

335 else: 

336 append(segment) 

337 if line: 

338 yield adjust_line_length(line, length, style=style, pad=pad) 

339 

340 @classmethod 

341 def adjust_line_length( 

342 cls, 

343 line: list["Segment"], 

344 length: int, 

345 style: Style | None = None, 

346 pad: bool = True, 

347 ) -> list["Segment"]: 

348 """Adjust a line to a given width (cropping or padding as required). 

349 

350 Args: 

351 segments (Iterable[Segment]): A list of segments in a single line. 

352 length (int): The desired width of the line. 

353 style (Style, optional): The style of padding if used (space on the end). Defaults to None. 

354 pad (bool, optional): Pad lines with spaces if they are shorter than `length`. Defaults to True. 

355 

356 Returns: 

357 list[Segment]: A line of segments with the desired length. 

358 """ 

359 line_length = sum(segment.cell_length for segment in line) 

360 new_line: list[Segment] 

361 

362 if line_length < length: 

363 if pad: 

364 new_line = line + [cls(" " * (length - line_length), style)] 

365 else: 

366 new_line = line[:] 

367 elif line_length > length: 

368 new_line = [] 

369 append = new_line.append 

370 line_length = 0 

371 for segment in line: 

372 segment_length = segment.cell_length 

373 if line_length + segment_length < length or segment.control: 

374 append(segment) 

375 line_length += segment_length 

376 else: 

377 text, segment_style, _ = segment 

378 text = set_cell_size(text, length - line_length) 

379 append(cls(text, segment_style)) 

380 break 

381 else: 

382 new_line = line[:] 

383 return new_line 

384 

385 @classmethod 

386 def get_line_length(cls, line: list["Segment"]) -> int: 

387 """Get the length of list of segments. 

388 

389 Args: 

390 line (list[Segment]): A line encoded as a list of Segments (assumes no '\\\\n' characters), 

391 

392 Returns: 

393 int: The length of the line. 

394 """ 

395 _cell_len = cell_len 

396 return sum(_cell_len(text) for text, style, control in line if not control) 

397 

398 @classmethod 

399 def get_shape(cls, lines: list[list["Segment"]]) -> tuple[int, int]: 

400 """Get the shape (enclosing rectangle) of a list of lines. 

401 

402 Args: 

403 lines (list[list[Segment]]): A list of lines (no '\\\\n' characters). 

404 

405 Returns: 

406 tuple[int, int]: Width and height in characters. 

407 """ 

408 get_line_length = cls.get_line_length 

409 max_width = max(get_line_length(line) for line in lines) if lines else 0 

410 return (max_width, len(lines)) 

411 

412 @classmethod 

413 def set_shape( 

414 cls, 

415 lines: list[list["Segment"]], 

416 width: int, 

417 height: int | None = None, 

418 style: Style | None = None, 

419 new_lines: bool = False, 

420 ) -> list[list["Segment"]]: 

421 """Set the shape of a list of lines (enclosing rectangle). 

422 

423 Args: 

424 lines (list[list[Segment]]): A list of lines. 

425 width (int): Desired width. 

426 height (int, optional): Desired height or None for no change. 

427 style (Style, optional): Style of any padding added. 

428 new_lines (bool, optional): Padded lines should include "\n". Defaults to False. 

429 

430 Returns: 

431 list[list[Segment]]: New list of lines. 

432 """ 

433 _height = height or len(lines) 

434 

435 blank = ( 

436 [cls(" " * width + "\n", style)] if new_lines else [cls(" " * width, style)] 

437 ) 

438 

439 adjust_line_length = cls.adjust_line_length 

440 shaped_lines = lines[:_height] 

441 shaped_lines[:] = [ 

442 adjust_line_length(line, width, style=style) for line in lines 

443 ] 

444 if len(shaped_lines) < _height: 

445 shaped_lines.extend([blank] * (_height - len(shaped_lines))) 

446 return shaped_lines 

447 

448 @classmethod 

449 def align_top( 

450 cls: type["Segment"], 

451 lines: list[list["Segment"]], 

452 width: int, 

453 height: int, 

454 style: Style, 

455 new_lines: bool = False, 

456 ) -> list[list["Segment"]]: 

457 """Aligns lines to top (adds extra lines to bottom as required). 

458 

459 Args: 

460 lines (list[list[Segment]]): A list of lines. 

461 width (int): Desired width. 

462 height (int, optional): Desired height or None for no change. 

463 style (Style): Style of any padding added. 

464 new_lines (bool, optional): Padded lines should include "\n". Defaults to False. 

465 

466 Returns: 

467 list[list[Segment]]: New list of lines. 

468 """ 

469 extra_lines = height - len(lines) 

470 if not extra_lines: 

471 return lines[:] 

472 lines = lines[:height] 

473 blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style) 

474 lines = lines + [[blank]] * extra_lines 

475 return lines 

476 

477 @classmethod 

478 def align_bottom( 

479 cls: type["Segment"], 

480 lines: list[list["Segment"]], 

481 width: int, 

482 height: int, 

483 style: Style, 

484 new_lines: bool = False, 

485 ) -> list[list["Segment"]]: 

486 """Aligns render to bottom (adds extra lines above as required). 

487 

488 Args: 

489 lines (list[list[Segment]]): A list of lines. 

490 width (int): Desired width. 

491 height (int, optional): Desired height or None for no change. 

492 style (Style): Style of any padding added. Defaults to None. 

493 new_lines (bool, optional): Padded lines should include "\n". Defaults to False. 

494 

495 Returns: 

496 list[list[Segment]]: New list of lines. 

497 """ 

498 extra_lines = height - len(lines) 

499 if not extra_lines: 

500 return lines[:] 

501 lines = lines[:height] 

502 blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style) 

503 lines = [[blank]] * extra_lines + lines 

504 return lines 

505 

506 @classmethod 

507 def align_middle( 

508 cls: type["Segment"], 

509 lines: list[list["Segment"]], 

510 width: int, 

511 height: int, 

512 style: Style, 

513 new_lines: bool = False, 

514 ) -> list[list["Segment"]]: 

515 """Aligns lines to middle (adds extra lines to above and below as required). 

516 

517 Args: 

518 lines (list[list[Segment]]): A list of lines. 

519 width (int): Desired width. 

520 height (int, optional): Desired height or None for no change. 

521 style (Style): Style of any padding added. 

522 new_lines (bool, optional): Padded lines should include "\n". Defaults to False. 

523 

524 Returns: 

525 list[list[Segment]]: New list of lines. 

526 """ 

527 extra_lines = height - len(lines) 

528 if not extra_lines: 

529 return lines[:] 

530 lines = lines[:height] 

531 blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style) 

532 top_lines = extra_lines // 2 

533 bottom_lines = extra_lines - top_lines 

534 lines = [[blank]] * top_lines + lines + [[blank]] * bottom_lines 

535 return lines 

536 

537 @classmethod 

538 def simplify(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]: 

539 """Simplify an iterable of segments by combining contiguous segments with the same style. 

540 

541 Args: 

542 segments (Iterable[Segment]): An iterable of segments. 

543 

544 Returns: 

545 Iterable[Segment]: A possibly smaller iterable of segments that will render the same way. 

546 """ 

547 iter_segments = iter(segments) 

548 try: 

549 last_segment = next(iter_segments) 

550 except StopIteration: 

551 return 

552 

553 _Segment = Segment 

554 for segment in iter_segments: 

555 if last_segment.style == segment.style and not segment.control: 

556 last_segment = _Segment( 

557 last_segment.text + segment.text, last_segment.style 

558 ) 

559 else: 

560 yield last_segment 

561 last_segment = segment 

562 yield last_segment 

563 

564 @classmethod 

565 def strip_links(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]: 

566 """Remove all links from an iterable of styles. 

567 

568 Args: 

569 segments (Iterable[Segment]): An iterable segments. 

570 

571 Yields: 

572 Segment: Segments with link removed. 

573 """ 

574 for segment in segments: 

575 if segment.control or segment.style is None: 

576 yield segment 

577 else: 

578 text, style, _control = segment 

579 yield cls(text, style.update_link(None) if style else None) 

580 

581 @classmethod 

582 def strip_styles(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]: 

583 """Remove all styles from an iterable of segments. 

584 

585 Args: 

586 segments (Iterable[Segment]): An iterable segments. 

587 

588 Yields: 

589 Segment: Segments with styles replace with None 

590 """ 

591 for text, _style, control in segments: 

592 yield cls(text, None, control) 

593 

594 @classmethod 

595 def remove_color(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]: 

596 """Remove all color from an iterable of segments. 

597 

598 Args: 

599 segments (Iterable[Segment]): An iterable segments. 

600 

601 Yields: 

602 Segment: Segments with colorless style. 

603 """ 

604 

605 cache: dict[Style, Style] = {} 

606 for text, style, control in segments: 

607 if style: 

608 colorless_style = cache.get(style) 

609 if colorless_style is None: 

610 colorless_style = style.without_color 

611 cache[style] = colorless_style 

612 yield cls(text, colorless_style, control) 

613 else: 

614 yield cls(text, None, control) 

615 

616 @classmethod 

617 def divide( 

618 cls, segments: Iterable["Segment"], cuts: Iterable[int] 

619 ) -> Iterable[list["Segment"]]: 

620 """Divides an iterable of segments in to portions. 

621 

622 Args: 

623 cuts (Iterable[int]): Cell positions where to divide. 

624 

625 Yields: 

626 [Iterable[list[Segment]]]: An iterable of Segments in List. 

627 """ 

628 split_segments: list["Segment"] = [] 

629 add_segment = split_segments.append 

630 

631 iter_cuts = iter(cuts) 

632 

633 while True: 

634 cut = next(iter_cuts, -1) 

635 if cut == -1: 

636 return 

637 if cut != 0: 

638 break 

639 yield [] 

640 pos = 0 

641 

642 segments_clear = split_segments.clear 

643 segments_copy = split_segments.copy 

644 

645 _cell_len = cached_cell_len 

646 for segment in segments: 

647 text, _style, control = segment 

648 while text: 

649 end_pos = pos if control else pos + _cell_len(text) 

650 if end_pos < cut: 

651 add_segment(segment) 

652 pos = end_pos 

653 break 

654 

655 if end_pos == cut: 

656 add_segment(segment) 

657 yield segments_copy() 

658 segments_clear() 

659 pos = end_pos 

660 

661 cut = next(iter_cuts, -1) 

662 if cut == -1: 

663 if split_segments: 

664 yield segments_copy() 

665 return 

666 

667 break 

668 

669 else: 

670 before, segment = segment.split_cells(cut - pos) 

671 text, _style, control = segment 

672 add_segment(before) 

673 yield segments_copy() 

674 segments_clear() 

675 pos = cut 

676 

677 cut = next(iter_cuts, -1) 

678 if cut == -1: 

679 if split_segments: 

680 yield segments_copy() 

681 return 

682 

683 yield segments_copy() 

684 

685 

686class Segments: 

687 """A simple renderable to render an iterable of segments. This class may be useful if 

688 you want to print segments outside of a __rich_console__ method. 

689 

690 Args: 

691 segments (Iterable[Segment]): An iterable of segments. 

692 new_lines (bool, optional): Add new lines between segments. Defaults to False. 

693 """ 

694 

695 def __init__(self, segments: Iterable[Segment], new_lines: bool = False) -> None: 

696 self.segments = list(segments) 

697 self.new_lines = new_lines 

698 

699 def __rich_console__( 

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

701 ) -> "RenderResult": 

702 if self.new_lines: 

703 line = Segment.line() 

704 for segment in self.segments: 

705 yield segment 

706 yield line 

707 else: 

708 yield from self.segments 

709 

710 

711class SegmentLines: 

712 def __init__(self, lines: Iterable[list[Segment]], new_lines: bool = False) -> None: 

713 """A simple renderable containing a number of lines of segments. May be used as an intermediate 

714 in rendering process. 

715 

716 Args: 

717 lines (Iterable[list[Segment]]): Lists of segments forming lines. 

718 new_lines (bool, optional): Insert new lines after each line. Defaults to False. 

719 """ 

720 self.lines = list(lines) 

721 self.new_lines = new_lines 

722 

723 def __rich_console__( 

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

725 ) -> "RenderResult": 

726 if self.new_lines: 

727 new_line = Segment.line() 

728 for line in self.lines: 

729 yield from line 

730 yield new_line 

731 else: 

732 for line in self.lines: 

733 yield from line 

734 

735 

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

737 from rich.console import Console 

738 from rich.syntax import Syntax 

739 from rich.text import Text 

740 

741 code = """from rich.console import Console 

742console = Console() 

743text = Text.from_markup("Hello, [bold magenta]World[/]!") 

744console.print(text)""" 

745 

746 text = Text.from_markup("Hello, [bold magenta]World[/]!") 

747 

748 console = Console() 

749 

750 console.rule("rich.Segment") 

751 console.print( 

752 "A Segment is the last step in the Rich render process before generating text with ANSI codes." 

753 ) 

754 console.print("\nConsider the following code:\n") 

755 console.print(Syntax(code, "python", line_numbers=True)) 

756 console.print() 

757 console.print( 

758 "When you call [b]print()[/b], Rich [i]renders[/i] the object in to the following:\n" 

759 ) 

760 fragments = list(console.render(text)) 

761 console.print(fragments) 

762 console.print() 

763 console.print("The Segments are then processed to produce the following output:\n") 

764 console.print(text) 

765 console.print( 

766 "\nYou will only need to know this if you are implementing your own Rich renderables." 

767 )