text.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. import re
  2. from functools import partial, reduce
  3. from math import gcd
  4. from operator import itemgetter
  5. from typing import (
  6. TYPE_CHECKING,
  7. Any,
  8. Callable,
  9. Dict,
  10. Iterable,
  11. List,
  12. NamedTuple,
  13. Optional,
  14. Tuple,
  15. Union,
  16. )
  17. from ._loop import loop_last
  18. from ._pick import pick_bool
  19. from ._wrap import divide_line
  20. from .align import AlignMethod
  21. from .cells import cell_len, set_cell_size
  22. from .containers import Lines
  23. from .control import strip_control_codes
  24. from .emoji import EmojiVariant
  25. from .jupyter import JupyterMixin
  26. from .measure import Measurement
  27. from .segment import Segment
  28. from .style import Style, StyleType
  29. if TYPE_CHECKING: # pragma: no cover
  30. from .console import Console, ConsoleOptions, JustifyMethod, OverflowMethod
  31. DEFAULT_JUSTIFY: "JustifyMethod" = "default"
  32. DEFAULT_OVERFLOW: "OverflowMethod" = "fold"
  33. _re_whitespace = re.compile(r"\s+$")
  34. TextType = Union[str, "Text"]
  35. """A plain string or a :class:`Text` instance."""
  36. GetStyleCallable = Callable[[str], Optional[StyleType]]
  37. class Span(NamedTuple):
  38. """A marked up region in some text."""
  39. start: int
  40. """Span start index."""
  41. end: int
  42. """Span end index."""
  43. style: Union[str, Style]
  44. """Style associated with the span."""
  45. def __repr__(self) -> str:
  46. return f"Span({self.start}, {self.end}, {self.style!r})"
  47. def __bool__(self) -> bool:
  48. return self.end > self.start
  49. def split(self, offset: int) -> Tuple["Span", Optional["Span"]]:
  50. """Split a span in to 2 from a given offset."""
  51. if offset < self.start:
  52. return self, None
  53. if offset >= self.end:
  54. return self, None
  55. start, end, style = self
  56. span1 = Span(start, min(end, offset), style)
  57. span2 = Span(span1.end, end, style)
  58. return span1, span2
  59. def move(self, offset: int) -> "Span":
  60. """Move start and end by a given offset.
  61. Args:
  62. offset (int): Number of characters to add to start and end.
  63. Returns:
  64. TextSpan: A new TextSpan with adjusted position.
  65. """
  66. start, end, style = self
  67. return Span(start + offset, end + offset, style)
  68. def right_crop(self, offset: int) -> "Span":
  69. """Crop the span at the given offset.
  70. Args:
  71. offset (int): A value between start and end.
  72. Returns:
  73. Span: A new (possibly smaller) span.
  74. """
  75. start, end, style = self
  76. if offset >= end:
  77. return self
  78. return Span(start, min(offset, end), style)
  79. def extend(self, cells: int) -> "Span":
  80. """Extend the span by the given number of cells.
  81. Args:
  82. cells (int): Additional space to add to end of span.
  83. Returns:
  84. Span: A span.
  85. """
  86. if cells:
  87. start, end, style = self
  88. return Span(start, end + cells, style)
  89. else:
  90. return self
  91. class Text(JupyterMixin):
  92. """Text with color / style.
  93. Args:
  94. text (str, optional): Default unstyled text. Defaults to "".
  95. style (Union[str, Style], optional): Base style for text. Defaults to "".
  96. justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
  97. overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
  98. no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
  99. end (str, optional): Character to end text with. Defaults to "\\\\n".
  100. tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.
  101. spans (List[Span], optional). A list of predefined style spans. Defaults to None.
  102. """
  103. __slots__ = [
  104. "_text",
  105. "style",
  106. "justify",
  107. "overflow",
  108. "no_wrap",
  109. "end",
  110. "tab_size",
  111. "_spans",
  112. "_length",
  113. ]
  114. def __init__(
  115. self,
  116. text: str = "",
  117. style: Union[str, Style] = "",
  118. *,
  119. justify: Optional["JustifyMethod"] = None,
  120. overflow: Optional["OverflowMethod"] = None,
  121. no_wrap: Optional[bool] = None,
  122. end: str = "\n",
  123. tab_size: Optional[int] = None,
  124. spans: Optional[List[Span]] = None,
  125. ) -> None:
  126. sanitized_text = strip_control_codes(text)
  127. self._text = [sanitized_text]
  128. self.style = style
  129. self.justify: Optional["JustifyMethod"] = justify
  130. self.overflow: Optional["OverflowMethod"] = overflow
  131. self.no_wrap = no_wrap
  132. self.end = end
  133. self.tab_size = tab_size
  134. self._spans: List[Span] = spans or []
  135. self._length: int = len(sanitized_text)
  136. def __len__(self) -> int:
  137. return self._length
  138. def __bool__(self) -> bool:
  139. return bool(self._length)
  140. def __str__(self) -> str:
  141. return self.plain
  142. def __repr__(self) -> str:
  143. return f"<text {self.plain!r} {self._spans!r}>"
  144. def __add__(self, other: Any) -> "Text":
  145. if isinstance(other, (str, Text)):
  146. result = self.copy()
  147. result.append(other)
  148. return result
  149. return NotImplemented
  150. def __eq__(self, other: object) -> bool:
  151. if not isinstance(other, Text):
  152. return NotImplemented
  153. return self.plain == other.plain and self._spans == other._spans
  154. def __contains__(self, other: object) -> bool:
  155. if isinstance(other, str):
  156. return other in self.plain
  157. elif isinstance(other, Text):
  158. return other.plain in self.plain
  159. return False
  160. def __getitem__(self, slice: Union[int, slice]) -> "Text":
  161. def get_text_at(offset: int) -> "Text":
  162. _Span = Span
  163. text = Text(
  164. self.plain[offset],
  165. spans=[
  166. _Span(0, 1, style)
  167. for start, end, style in self._spans
  168. if end > offset >= start
  169. ],
  170. end="",
  171. )
  172. return text
  173. if isinstance(slice, int):
  174. return get_text_at(slice)
  175. else:
  176. start, stop, step = slice.indices(len(self.plain))
  177. if step == 1:
  178. lines = self.divide([start, stop])
  179. return lines[1]
  180. else:
  181. # This would be a bit of work to implement efficiently
  182. # For now, its not required
  183. raise TypeError("slices with step!=1 are not supported")
  184. @property
  185. def cell_len(self) -> int:
  186. """Get the number of cells required to render this text."""
  187. return cell_len(self.plain)
  188. @property
  189. def markup(self) -> str:
  190. """Get console markup to render this Text.
  191. Returns:
  192. str: A string potentially creating markup tags.
  193. """
  194. from .markup import escape
  195. output: List[str] = []
  196. plain = self.plain
  197. markup_spans = [
  198. (0, False, self.style),
  199. *((span.start, False, span.style) for span in self._spans),
  200. *((span.end, True, span.style) for span in self._spans),
  201. (len(plain), True, self.style),
  202. ]
  203. markup_spans.sort(key=itemgetter(0, 1))
  204. position = 0
  205. append = output.append
  206. for offset, closing, style in markup_spans:
  207. if offset > position:
  208. append(escape(plain[position:offset]))
  209. position = offset
  210. if style:
  211. append(f"[/{style}]" if closing else f"[{style}]")
  212. markup = "".join(output)
  213. return markup
  214. @classmethod
  215. def from_markup(
  216. cls,
  217. text: str,
  218. *,
  219. style: Union[str, Style] = "",
  220. emoji: bool = True,
  221. emoji_variant: Optional[EmojiVariant] = None,
  222. justify: Optional["JustifyMethod"] = None,
  223. overflow: Optional["OverflowMethod"] = None,
  224. end: str = "\n",
  225. ) -> "Text":
  226. """Create Text instance from markup.
  227. Args:
  228. text (str): A string containing console markup.
  229. style (Union[str, Style], optional): Base style for text. Defaults to "".
  230. emoji (bool, optional): Also render emoji code. Defaults to True.
  231. emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None.
  232. justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
  233. overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
  234. end (str, optional): Character to end text with. Defaults to "\\\\n".
  235. Returns:
  236. Text: A Text instance with markup rendered.
  237. """
  238. from .markup import render
  239. rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant)
  240. rendered_text.justify = justify
  241. rendered_text.overflow = overflow
  242. rendered_text.end = end
  243. return rendered_text
  244. @classmethod
  245. def from_ansi(
  246. cls,
  247. text: str,
  248. *,
  249. style: Union[str, Style] = "",
  250. justify: Optional["JustifyMethod"] = None,
  251. overflow: Optional["OverflowMethod"] = None,
  252. no_wrap: Optional[bool] = None,
  253. end: str = "\n",
  254. tab_size: Optional[int] = 8,
  255. ) -> "Text":
  256. """Create a Text object from a string containing ANSI escape codes.
  257. Args:
  258. text (str): A string containing escape codes.
  259. style (Union[str, Style], optional): Base style for text. Defaults to "".
  260. justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
  261. overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
  262. no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
  263. end (str, optional): Character to end text with. Defaults to "\\\\n".
  264. tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.
  265. """
  266. from .ansi import AnsiDecoder
  267. joiner = Text(
  268. "\n",
  269. justify=justify,
  270. overflow=overflow,
  271. no_wrap=no_wrap,
  272. end=end,
  273. tab_size=tab_size,
  274. style=style,
  275. )
  276. decoder = AnsiDecoder()
  277. result = joiner.join(line for line in decoder.decode(text))
  278. return result
  279. @classmethod
  280. def styled(
  281. cls,
  282. text: str,
  283. style: StyleType = "",
  284. *,
  285. justify: Optional["JustifyMethod"] = None,
  286. overflow: Optional["OverflowMethod"] = None,
  287. ) -> "Text":
  288. """Construct a Text instance with a pre-applied styled. A style applied in this way won't be used
  289. to pad the text when it is justified.
  290. Args:
  291. text (str): A string containing console markup.
  292. style (Union[str, Style]): Style to apply to the text. Defaults to "".
  293. justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
  294. overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
  295. Returns:
  296. Text: A text instance with a style applied to the entire string.
  297. """
  298. styled_text = cls(text, justify=justify, overflow=overflow)
  299. styled_text.stylize(style)
  300. return styled_text
  301. @classmethod
  302. def assemble(
  303. cls,
  304. *parts: Union[str, "Text", Tuple[str, StyleType]],
  305. style: Union[str, Style] = "",
  306. justify: Optional["JustifyMethod"] = None,
  307. overflow: Optional["OverflowMethod"] = None,
  308. no_wrap: Optional[bool] = None,
  309. end: str = "\n",
  310. tab_size: int = 8,
  311. meta: Optional[Dict[str, Any]] = None,
  312. ) -> "Text":
  313. """Construct a text instance by combining a sequence of strings with optional styles.
  314. The positional arguments should be either strings, or a tuple of string + style.
  315. Args:
  316. style (Union[str, Style], optional): Base style for text. Defaults to "".
  317. justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
  318. overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
  319. no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
  320. end (str, optional): Character to end text with. Defaults to "\\\\n".
  321. tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.
  322. meta (Dict[str, Any], optional). Meta data to apply to text, or None for no meta data. Default to None
  323. Returns:
  324. Text: A new text instance.
  325. """
  326. text = cls(
  327. style=style,
  328. justify=justify,
  329. overflow=overflow,
  330. no_wrap=no_wrap,
  331. end=end,
  332. tab_size=tab_size,
  333. )
  334. append = text.append
  335. _Text = Text
  336. for part in parts:
  337. if isinstance(part, (_Text, str)):
  338. append(part)
  339. else:
  340. append(*part)
  341. if meta:
  342. text.apply_meta(meta)
  343. return text
  344. @property
  345. def plain(self) -> str:
  346. """Get the text as a single string."""
  347. if len(self._text) != 1:
  348. self._text[:] = ["".join(self._text)]
  349. return self._text[0]
  350. @plain.setter
  351. def plain(self, new_text: str) -> None:
  352. """Set the text to a new value."""
  353. if new_text != self.plain:
  354. sanitized_text = strip_control_codes(new_text)
  355. self._text[:] = [sanitized_text]
  356. old_length = self._length
  357. self._length = len(sanitized_text)
  358. if old_length > self._length:
  359. self._trim_spans()
  360. @property
  361. def spans(self) -> List[Span]:
  362. """Get a reference to the internal list of spans."""
  363. return self._spans
  364. @spans.setter
  365. def spans(self, spans: List[Span]) -> None:
  366. """Set spans."""
  367. self._spans = spans[:]
  368. def blank_copy(self, plain: str = "") -> "Text":
  369. """Return a new Text instance with copied metadata (but not the string or spans)."""
  370. copy_self = Text(
  371. plain,
  372. style=self.style,
  373. justify=self.justify,
  374. overflow=self.overflow,
  375. no_wrap=self.no_wrap,
  376. end=self.end,
  377. tab_size=self.tab_size,
  378. )
  379. return copy_self
  380. def copy(self) -> "Text":
  381. """Return a copy of this instance."""
  382. copy_self = Text(
  383. self.plain,
  384. style=self.style,
  385. justify=self.justify,
  386. overflow=self.overflow,
  387. no_wrap=self.no_wrap,
  388. end=self.end,
  389. tab_size=self.tab_size,
  390. )
  391. copy_self._spans[:] = self._spans
  392. return copy_self
  393. def stylize(
  394. self,
  395. style: Union[str, Style],
  396. start: int = 0,
  397. end: Optional[int] = None,
  398. ) -> None:
  399. """Apply a style to the text, or a portion of the text.
  400. Args:
  401. style (Union[str, Style]): Style instance or style definition to apply.
  402. start (int): Start offset (negative indexing is supported). Defaults to 0.
  403. end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.
  404. """
  405. if style:
  406. length = len(self)
  407. if start < 0:
  408. start = length + start
  409. if end is None:
  410. end = length
  411. if end < 0:
  412. end = length + end
  413. if start >= length or end <= start:
  414. # Span not in text or not valid
  415. return
  416. self._spans.append(Span(start, min(length, end), style))
  417. def stylize_before(
  418. self,
  419. style: Union[str, Style],
  420. start: int = 0,
  421. end: Optional[int] = None,
  422. ) -> None:
  423. """Apply a style to the text, or a portion of the text. Styles will be applied before other styles already present.
  424. Args:
  425. style (Union[str, Style]): Style instance or style definition to apply.
  426. start (int): Start offset (negative indexing is supported). Defaults to 0.
  427. end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.
  428. """
  429. if style:
  430. length = len(self)
  431. if start < 0:
  432. start = length + start
  433. if end is None:
  434. end = length
  435. if end < 0:
  436. end = length + end
  437. if start >= length or end <= start:
  438. # Span not in text or not valid
  439. return
  440. self._spans.insert(0, Span(start, min(length, end), style))
  441. def apply_meta(
  442. self, meta: Dict[str, Any], start: int = 0, end: Optional[int] = None
  443. ) -> None:
  444. """Apply metadata to the text, or a portion of the text.
  445. Args:
  446. meta (Dict[str, Any]): A dict of meta information.
  447. start (int): Start offset (negative indexing is supported). Defaults to 0.
  448. end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.
  449. """
  450. style = Style.from_meta(meta)
  451. self.stylize(style, start=start, end=end)
  452. def on(self, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Text":
  453. """Apply event handlers (used by Textual project).
  454. Example:
  455. >>> from rich.text import Text
  456. >>> text = Text("hello world")
  457. >>> text.on(click="view.toggle('world')")
  458. Args:
  459. meta (Dict[str, Any]): Mapping of meta information.
  460. **handlers: Keyword args are prefixed with "@" to defined handlers.
  461. Returns:
  462. Text: Self is returned to method may be chained.
  463. """
  464. meta = {} if meta is None else meta
  465. meta.update({f"@{key}": value for key, value in handlers.items()})
  466. self.stylize(Style.from_meta(meta))
  467. return self
  468. def remove_suffix(self, suffix: str) -> None:
  469. """Remove a suffix if it exists.
  470. Args:
  471. suffix (str): Suffix to remove.
  472. """
  473. if self.plain.endswith(suffix):
  474. self.right_crop(len(suffix))
  475. def get_style_at_offset(self, console: "Console", offset: int) -> Style:
  476. """Get the style of a character at give offset.
  477. Args:
  478. console (~Console): Console where text will be rendered.
  479. offset (int): Offset in to text (negative indexing supported)
  480. Returns:
  481. Style: A Style instance.
  482. """
  483. # TODO: This is a little inefficient, it is only used by full justify
  484. if offset < 0:
  485. offset = len(self) + offset
  486. get_style = console.get_style
  487. style = get_style(self.style).copy()
  488. for start, end, span_style in self._spans:
  489. if end > offset >= start:
  490. style += get_style(span_style, default="")
  491. return style
  492. def extend_style(self, spaces: int) -> None:
  493. """Extend the Text given number of spaces where the spaces have the same style as the last character.
  494. Args:
  495. spaces (int): Number of spaces to add to the Text.
  496. """
  497. if spaces <= 0:
  498. return
  499. spans = self.spans
  500. new_spaces = " " * spaces
  501. if spans:
  502. end_offset = len(self)
  503. self._spans[:] = [
  504. span.extend(spaces) if span.end >= end_offset else span
  505. for span in spans
  506. ]
  507. self._text.append(new_spaces)
  508. self._length += spaces
  509. else:
  510. self.plain += new_spaces
  511. def highlight_regex(
  512. self,
  513. re_highlight: str,
  514. style: Optional[Union[GetStyleCallable, StyleType]] = None,
  515. *,
  516. style_prefix: str = "",
  517. ) -> int:
  518. """Highlight text with a regular expression, where group names are
  519. translated to styles.
  520. Args:
  521. re_highlight (str): A regular expression.
  522. style (Union[GetStyleCallable, StyleType]): Optional style to apply to whole match, or a callable
  523. which accepts the matched text and returns a style. Defaults to None.
  524. style_prefix (str, optional): Optional prefix to add to style group names.
  525. Returns:
  526. int: Number of regex matches
  527. """
  528. count = 0
  529. append_span = self._spans.append
  530. _Span = Span
  531. plain = self.plain
  532. for match in re.finditer(re_highlight, plain):
  533. get_span = match.span
  534. if style:
  535. start, end = get_span()
  536. match_style = style(plain[start:end]) if callable(style) else style
  537. if match_style is not None and end > start:
  538. append_span(_Span(start, end, match_style))
  539. count += 1
  540. for name in match.groupdict().keys():
  541. start, end = get_span(name)
  542. if start != -1 and end > start:
  543. append_span(_Span(start, end, f"{style_prefix}{name}"))
  544. return count
  545. def highlight_words(
  546. self,
  547. words: Iterable[str],
  548. style: Union[str, Style],
  549. *,
  550. case_sensitive: bool = True,
  551. ) -> int:
  552. """Highlight words with a style.
  553. Args:
  554. words (Iterable[str]): Words to highlight.
  555. style (Union[str, Style]): Style to apply.
  556. case_sensitive (bool, optional): Enable case sensitive matching. Defaults to True.
  557. Returns:
  558. int: Number of words highlighted.
  559. """
  560. re_words = "|".join(re.escape(word) for word in words)
  561. add_span = self._spans.append
  562. count = 0
  563. _Span = Span
  564. for match in re.finditer(
  565. re_words, self.plain, flags=0 if case_sensitive else re.IGNORECASE
  566. ):
  567. start, end = match.span(0)
  568. add_span(_Span(start, end, style))
  569. count += 1
  570. return count
  571. def rstrip(self) -> None:
  572. """Strip whitespace from end of text."""
  573. self.plain = self.plain.rstrip()
  574. def rstrip_end(self, size: int) -> None:
  575. """Remove whitespace beyond a certain width at the end of the text.
  576. Args:
  577. size (int): The desired size of the text.
  578. """
  579. text_length = len(self)
  580. if text_length > size:
  581. excess = text_length - size
  582. whitespace_match = _re_whitespace.search(self.plain)
  583. if whitespace_match is not None:
  584. whitespace_count = len(whitespace_match.group(0))
  585. self.right_crop(min(whitespace_count, excess))
  586. def set_length(self, new_length: int) -> None:
  587. """Set new length of the text, clipping or padding is required."""
  588. length = len(self)
  589. if length != new_length:
  590. if length < new_length:
  591. self.pad_right(new_length - length)
  592. else:
  593. self.right_crop(length - new_length)
  594. def __rich_console__(
  595. self, console: "Console", options: "ConsoleOptions"
  596. ) -> Iterable[Segment]:
  597. tab_size: int = console.tab_size if self.tab_size is None else self.tab_size
  598. justify = self.justify or options.justify or DEFAULT_JUSTIFY
  599. overflow = self.overflow or options.overflow or DEFAULT_OVERFLOW
  600. lines = self.wrap(
  601. console,
  602. options.max_width,
  603. justify=justify,
  604. overflow=overflow,
  605. tab_size=tab_size or 8,
  606. no_wrap=pick_bool(self.no_wrap, options.no_wrap, False),
  607. )
  608. all_lines = Text("\n").join(lines)
  609. yield from all_lines.render(console, end=self.end)
  610. def __rich_measure__(
  611. self, console: "Console", options: "ConsoleOptions"
  612. ) -> Measurement:
  613. text = self.plain
  614. lines = text.splitlines()
  615. max_text_width = max(cell_len(line) for line in lines) if lines else 0
  616. words = text.split()
  617. min_text_width = (
  618. max(cell_len(word) for word in words) if words else max_text_width
  619. )
  620. return Measurement(min_text_width, max_text_width)
  621. def render(self, console: "Console", end: str = "") -> Iterable["Segment"]:
  622. """Render the text as Segments.
  623. Args:
  624. console (Console): Console instance.
  625. end (Optional[str], optional): Optional end character.
  626. Returns:
  627. Iterable[Segment]: Result of render that may be written to the console.
  628. """
  629. _Segment = Segment
  630. text = self.plain
  631. if not self._spans:
  632. yield Segment(text)
  633. if end:
  634. yield _Segment(end)
  635. return
  636. get_style = partial(console.get_style, default=Style.null())
  637. enumerated_spans = list(enumerate(self._spans, 1))
  638. style_map = {index: get_style(span.style) for index, span in enumerated_spans}
  639. style_map[0] = get_style(self.style)
  640. spans = [
  641. (0, False, 0),
  642. *((span.start, False, index) for index, span in enumerated_spans),
  643. *((span.end, True, index) for index, span in enumerated_spans),
  644. (len(text), True, 0),
  645. ]
  646. spans.sort(key=itemgetter(0, 1))
  647. stack: List[int] = []
  648. stack_append = stack.append
  649. stack_pop = stack.remove
  650. style_cache: Dict[Tuple[Style, ...], Style] = {}
  651. style_cache_get = style_cache.get
  652. combine = Style.combine
  653. def get_current_style() -> Style:
  654. """Construct current style from stack."""
  655. styles = tuple(style_map[_style_id] for _style_id in sorted(stack))
  656. cached_style = style_cache_get(styles)
  657. if cached_style is not None:
  658. return cached_style
  659. current_style = combine(styles)
  660. style_cache[styles] = current_style
  661. return current_style
  662. for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]):
  663. if leaving:
  664. stack_pop(style_id)
  665. else:
  666. stack_append(style_id)
  667. if next_offset > offset:
  668. yield _Segment(text[offset:next_offset], get_current_style())
  669. if end:
  670. yield _Segment(end)
  671. def join(self, lines: Iterable["Text"]) -> "Text":
  672. """Join text together with this instance as the separator.
  673. Args:
  674. lines (Iterable[Text]): An iterable of Text instances to join.
  675. Returns:
  676. Text: A new text instance containing join text.
  677. """
  678. new_text = self.blank_copy()
  679. def iter_text() -> Iterable["Text"]:
  680. if self.plain:
  681. for last, line in loop_last(lines):
  682. yield line
  683. if not last:
  684. yield self
  685. else:
  686. yield from lines
  687. extend_text = new_text._text.extend
  688. append_span = new_text._spans.append
  689. extend_spans = new_text._spans.extend
  690. offset = 0
  691. _Span = Span
  692. for text in iter_text():
  693. extend_text(text._text)
  694. if text.style:
  695. append_span(_Span(offset, offset + len(text), text.style))
  696. extend_spans(
  697. _Span(offset + start, offset + end, style)
  698. for start, end, style in text._spans
  699. )
  700. offset += len(text)
  701. new_text._length = offset
  702. return new_text
  703. def expand_tabs(self, tab_size: Optional[int] = None) -> None:
  704. """Converts tabs to spaces.
  705. Args:
  706. tab_size (int, optional): Size of tabs. Defaults to 8.
  707. """
  708. if "\t" not in self.plain:
  709. return
  710. if tab_size is None:
  711. tab_size = self.tab_size
  712. if tab_size is None:
  713. tab_size = 8
  714. new_text: List[Text] = []
  715. append = new_text.append
  716. for line in self.split("\n", include_separator=True):
  717. if "\t" not in line.plain:
  718. append(line)
  719. else:
  720. cell_position = 0
  721. parts = line.split("\t", include_separator=True)
  722. for part in parts:
  723. if part.plain.endswith("\t"):
  724. part._text[-1] = part._text[-1][:-1] + " "
  725. cell_position += part.cell_len
  726. tab_remainder = cell_position % tab_size
  727. if tab_remainder:
  728. spaces = tab_size - tab_remainder
  729. part.extend_style(spaces)
  730. cell_position += spaces
  731. else:
  732. cell_position += part.cell_len
  733. append(part)
  734. result = Text("").join(new_text)
  735. self._text = [result.plain]
  736. self._length = len(self.plain)
  737. self._spans[:] = result._spans
  738. def truncate(
  739. self,
  740. max_width: int,
  741. *,
  742. overflow: Optional["OverflowMethod"] = None,
  743. pad: bool = False,
  744. ) -> None:
  745. """Truncate text if it is longer that a given width.
  746. Args:
  747. max_width (int): Maximum number of characters in text.
  748. overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None, to use self.overflow.
  749. pad (bool, optional): Pad with spaces if the length is less than max_width. Defaults to False.
  750. """
  751. _overflow = overflow or self.overflow or DEFAULT_OVERFLOW
  752. if _overflow != "ignore":
  753. length = cell_len(self.plain)
  754. if length > max_width:
  755. if _overflow == "ellipsis":
  756. self.plain = set_cell_size(self.plain, max_width - 1) + "…"
  757. else:
  758. self.plain = set_cell_size(self.plain, max_width)
  759. if pad and length < max_width:
  760. spaces = max_width - length
  761. self._text = [f"{self.plain}{' ' * spaces}"]
  762. self._length = len(self.plain)
  763. def _trim_spans(self) -> None:
  764. """Remove or modify any spans that are over the end of the text."""
  765. max_offset = len(self.plain)
  766. _Span = Span
  767. self._spans[:] = [
  768. (
  769. span
  770. if span.end < max_offset
  771. else _Span(span.start, min(max_offset, span.end), span.style)
  772. )
  773. for span in self._spans
  774. if span.start < max_offset
  775. ]
  776. def pad(self, count: int, character: str = " ") -> None:
  777. """Pad left and right with a given number of characters.
  778. Args:
  779. count (int): Width of padding.
  780. character (str): The character to pad with. Must be a string of length 1.
  781. """
  782. assert len(character) == 1, "Character must be a string of length 1"
  783. if count:
  784. pad_characters = character * count
  785. self.plain = f"{pad_characters}{self.plain}{pad_characters}"
  786. _Span = Span
  787. self._spans[:] = [
  788. _Span(start + count, end + count, style)
  789. for start, end, style in self._spans
  790. ]
  791. def pad_left(self, count: int, character: str = " ") -> None:
  792. """Pad the left with a given character.
  793. Args:
  794. count (int): Number of characters to pad.
  795. character (str, optional): Character to pad with. Defaults to " ".
  796. """
  797. assert len(character) == 1, "Character must be a string of length 1"
  798. if count:
  799. self.plain = f"{character * count}{self.plain}"
  800. _Span = Span
  801. self._spans[:] = [
  802. _Span(start + count, end + count, style)
  803. for start, end, style in self._spans
  804. ]
  805. def pad_right(self, count: int, character: str = " ") -> None:
  806. """Pad the right with a given character.
  807. Args:
  808. count (int): Number of characters to pad.
  809. character (str, optional): Character to pad with. Defaults to " ".
  810. """
  811. assert len(character) == 1, "Character must be a string of length 1"
  812. if count:
  813. self.plain = f"{self.plain}{character * count}"
  814. def align(self, align: AlignMethod, width: int, character: str = " ") -> None:
  815. """Align text to a given width.
  816. Args:
  817. align (AlignMethod): One of "left", "center", or "right".
  818. width (int): Desired width.
  819. character (str, optional): Character to pad with. Defaults to " ".
  820. """
  821. self.truncate(width)
  822. excess_space = width - cell_len(self.plain)
  823. if excess_space:
  824. if align == "left":
  825. self.pad_right(excess_space, character)
  826. elif align == "center":
  827. left = excess_space // 2
  828. self.pad_left(left, character)
  829. self.pad_right(excess_space - left, character)
  830. else:
  831. self.pad_left(excess_space, character)
  832. def append(
  833. self, text: Union["Text", str], style: Optional[Union[str, "Style"]] = None
  834. ) -> "Text":
  835. """Add text with an optional style.
  836. Args:
  837. text (Union[Text, str]): A str or Text to append.
  838. style (str, optional): A style name. Defaults to None.
  839. Returns:
  840. Text: Returns self for chaining.
  841. """
  842. if not isinstance(text, (str, Text)):
  843. raise TypeError("Only str or Text can be appended to Text")
  844. if len(text):
  845. if isinstance(text, str):
  846. sanitized_text = strip_control_codes(text)
  847. self._text.append(sanitized_text)
  848. offset = len(self)
  849. text_length = len(sanitized_text)
  850. if style:
  851. self._spans.append(Span(offset, offset + text_length, style))
  852. self._length += text_length
  853. elif isinstance(text, Text):
  854. _Span = Span
  855. if style is not None:
  856. raise ValueError(
  857. "style must not be set when appending Text instance"
  858. )
  859. text_length = self._length
  860. if text.style:
  861. self._spans.append(
  862. _Span(text_length, text_length + len(text), text.style)
  863. )
  864. self._text.append(text.plain)
  865. self._spans.extend(
  866. _Span(start + text_length, end + text_length, style)
  867. for start, end, style in text._spans
  868. )
  869. self._length += len(text)
  870. return self
  871. def append_text(self, text: "Text") -> "Text":
  872. """Append another Text instance. This method is more performant that Text.append, but
  873. only works for Text.
  874. Args:
  875. text (Text): The Text instance to append to this instance.
  876. Returns:
  877. Text: Returns self for chaining.
  878. """
  879. _Span = Span
  880. text_length = self._length
  881. if text.style:
  882. self._spans.append(_Span(text_length, text_length + len(text), text.style))
  883. self._text.append(text.plain)
  884. self._spans.extend(
  885. _Span(start + text_length, end + text_length, style)
  886. for start, end, style in text._spans
  887. )
  888. self._length += len(text)
  889. return self
  890. def append_tokens(
  891. self, tokens: Iterable[Tuple[str, Optional[StyleType]]]
  892. ) -> "Text":
  893. """Append iterable of str and style. Style may be a Style instance or a str style definition.
  894. Args:
  895. tokens (Iterable[Tuple[str, Optional[StyleType]]]): An iterable of tuples containing str content and style.
  896. Returns:
  897. Text: Returns self for chaining.
  898. """
  899. append_text = self._text.append
  900. append_span = self._spans.append
  901. _Span = Span
  902. offset = len(self)
  903. for content, style in tokens:
  904. append_text(content)
  905. if style:
  906. append_span(_Span(offset, offset + len(content), style))
  907. offset += len(content)
  908. self._length = offset
  909. return self
  910. def copy_styles(self, text: "Text") -> None:
  911. """Copy styles from another Text instance.
  912. Args:
  913. text (Text): A Text instance to copy styles from, must be the same length.
  914. """
  915. self._spans.extend(text._spans)
  916. def split(
  917. self,
  918. separator: str = "\n",
  919. *,
  920. include_separator: bool = False,
  921. allow_blank: bool = False,
  922. ) -> Lines:
  923. """Split rich text in to lines, preserving styles.
  924. Args:
  925. separator (str, optional): String to split on. Defaults to "\\\\n".
  926. include_separator (bool, optional): Include the separator in the lines. Defaults to False.
  927. allow_blank (bool, optional): Return a blank line if the text ends with a separator. Defaults to False.
  928. Returns:
  929. List[RichText]: A list of rich text, one per line of the original.
  930. """
  931. assert separator, "separator must not be empty"
  932. text = self.plain
  933. if separator not in text:
  934. return Lines([self.copy()])
  935. if include_separator:
  936. lines = self.divide(
  937. match.end() for match in re.finditer(re.escape(separator), text)
  938. )
  939. else:
  940. def flatten_spans() -> Iterable[int]:
  941. for match in re.finditer(re.escape(separator), text):
  942. start, end = match.span()
  943. yield start
  944. yield end
  945. lines = Lines(
  946. line for line in self.divide(flatten_spans()) if line.plain != separator
  947. )
  948. if not allow_blank and text.endswith(separator):
  949. lines.pop()
  950. return lines
  951. def divide(self, offsets: Iterable[int]) -> Lines:
  952. """Divide text in to a number of lines at given offsets.
  953. Args:
  954. offsets (Iterable[int]): Offsets used to divide text.
  955. Returns:
  956. Lines: New RichText instances between offsets.
  957. """
  958. _offsets = list(offsets)
  959. if not _offsets:
  960. return Lines([self.copy()])
  961. text = self.plain
  962. text_length = len(text)
  963. divide_offsets = [0, *_offsets, text_length]
  964. line_ranges = list(zip(divide_offsets, divide_offsets[1:]))
  965. style = self.style
  966. justify = self.justify
  967. overflow = self.overflow
  968. _Text = Text
  969. new_lines = Lines(
  970. _Text(
  971. text[start:end],
  972. style=style,
  973. justify=justify,
  974. overflow=overflow,
  975. )
  976. for start, end in line_ranges
  977. )
  978. if not self._spans:
  979. return new_lines
  980. _line_appends = [line._spans.append for line in new_lines._lines]
  981. line_count = len(line_ranges)
  982. _Span = Span
  983. for span_start, span_end, style in self._spans:
  984. lower_bound = 0
  985. upper_bound = line_count
  986. start_line_no = (lower_bound + upper_bound) // 2
  987. while True:
  988. line_start, line_end = line_ranges[start_line_no]
  989. if span_start < line_start:
  990. upper_bound = start_line_no - 1
  991. elif span_start > line_end:
  992. lower_bound = start_line_no + 1
  993. else:
  994. break
  995. start_line_no = (lower_bound + upper_bound) // 2
  996. if span_end < line_end:
  997. end_line_no = start_line_no
  998. else:
  999. end_line_no = lower_bound = start_line_no
  1000. upper_bound = line_count
  1001. while True:
  1002. line_start, line_end = line_ranges[end_line_no]
  1003. if span_end < line_start:
  1004. upper_bound = end_line_no - 1
  1005. elif span_end > line_end:
  1006. lower_bound = end_line_no + 1
  1007. else:
  1008. break
  1009. end_line_no = (lower_bound + upper_bound) // 2
  1010. for line_no in range(start_line_no, end_line_no + 1):
  1011. line_start, line_end = line_ranges[line_no]
  1012. new_start = max(0, span_start - line_start)
  1013. new_end = min(span_end - line_start, line_end - line_start)
  1014. if new_end > new_start:
  1015. _line_appends[line_no](_Span(new_start, new_end, style))
  1016. return new_lines
  1017. def right_crop(self, amount: int = 1) -> None:
  1018. """Remove a number of characters from the end of the text."""
  1019. max_offset = len(self.plain) - amount
  1020. _Span = Span
  1021. self._spans[:] = [
  1022. (
  1023. span
  1024. if span.end < max_offset
  1025. else _Span(span.start, min(max_offset, span.end), span.style)
  1026. )
  1027. for span in self._spans
  1028. if span.start < max_offset
  1029. ]
  1030. self._text = [self.plain[:-amount]]
  1031. self._length -= amount
  1032. def wrap(
  1033. self,
  1034. console: "Console",
  1035. width: int,
  1036. *,
  1037. justify: Optional["JustifyMethod"] = None,
  1038. overflow: Optional["OverflowMethod"] = None,
  1039. tab_size: int = 8,
  1040. no_wrap: Optional[bool] = None,
  1041. ) -> Lines:
  1042. """Word wrap the text.
  1043. Args:
  1044. console (Console): Console instance.
  1045. width (int): Number of cells available per line.
  1046. justify (str, optional): Justify method: "default", "left", "center", "full", "right". Defaults to "default".
  1047. overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None.
  1048. tab_size (int, optional): Default tab size. Defaults to 8.
  1049. no_wrap (bool, optional): Disable wrapping, Defaults to False.
  1050. Returns:
  1051. Lines: Number of lines.
  1052. """
  1053. wrap_justify = justify or self.justify or DEFAULT_JUSTIFY
  1054. wrap_overflow = overflow or self.overflow or DEFAULT_OVERFLOW
  1055. no_wrap = pick_bool(no_wrap, self.no_wrap, False) or overflow == "ignore"
  1056. lines = Lines()
  1057. for line in self.split(allow_blank=True):
  1058. if "\t" in line:
  1059. line.expand_tabs(tab_size)
  1060. if no_wrap:
  1061. new_lines = Lines([line])
  1062. else:
  1063. offsets = divide_line(str(line), width, fold=wrap_overflow == "fold")
  1064. new_lines = line.divide(offsets)
  1065. for line in new_lines:
  1066. line.rstrip_end(width)
  1067. if wrap_justify:
  1068. new_lines.justify(
  1069. console, width, justify=wrap_justify, overflow=wrap_overflow
  1070. )
  1071. for line in new_lines:
  1072. line.truncate(width, overflow=wrap_overflow)
  1073. lines.extend(new_lines)
  1074. return lines
  1075. def fit(self, width: int) -> Lines:
  1076. """Fit the text in to given width by chopping in to lines.
  1077. Args:
  1078. width (int): Maximum characters in a line.
  1079. Returns:
  1080. Lines: Lines container.
  1081. """
  1082. lines: Lines = Lines()
  1083. append = lines.append
  1084. for line in self.split():
  1085. line.set_length(width)
  1086. append(line)
  1087. return lines
  1088. def detect_indentation(self) -> int:
  1089. """Auto-detect indentation of code.
  1090. Returns:
  1091. int: Number of spaces used to indent code.
  1092. """
  1093. _indentations = {
  1094. len(match.group(1))
  1095. for match in re.finditer(r"^( *)(.*)$", self.plain, flags=re.MULTILINE)
  1096. }
  1097. try:
  1098. indentation = (
  1099. reduce(gcd, [indent for indent in _indentations if not indent % 2]) or 1
  1100. )
  1101. except TypeError:
  1102. indentation = 1
  1103. return indentation
  1104. def with_indent_guides(
  1105. self,
  1106. indent_size: Optional[int] = None,
  1107. *,
  1108. character: str = "│",
  1109. style: StyleType = "dim green",
  1110. ) -> "Text":
  1111. """Adds indent guide lines to text.
  1112. Args:
  1113. indent_size (Optional[int]): Size of indentation, or None to auto detect. Defaults to None.
  1114. character (str, optional): Character to use for indentation. Defaults to "│".
  1115. style (Union[Style, str], optional): Style of indent guides.
  1116. Returns:
  1117. Text: New text with indentation guides.
  1118. """
  1119. _indent_size = self.detect_indentation() if indent_size is None else indent_size
  1120. text = self.copy()
  1121. text.expand_tabs()
  1122. indent_line = f"{character}{' ' * (_indent_size - 1)}"
  1123. re_indent = re.compile(r"^( *)(.*)$")
  1124. new_lines: List[Text] = []
  1125. add_line = new_lines.append
  1126. blank_lines = 0
  1127. for line in text.split(allow_blank=True):
  1128. match = re_indent.match(line.plain)
  1129. if not match or not match.group(2):
  1130. blank_lines += 1
  1131. continue
  1132. indent = match.group(1)
  1133. full_indents, remaining_space = divmod(len(indent), _indent_size)
  1134. new_indent = f"{indent_line * full_indents}{' ' * remaining_space}"
  1135. line.plain = new_indent + line.plain[len(new_indent) :]
  1136. line.stylize(style, 0, len(new_indent))
  1137. if blank_lines:
  1138. new_lines.extend([Text(new_indent, style=style)] * blank_lines)
  1139. blank_lines = 0
  1140. add_line(line)
  1141. if blank_lines:
  1142. new_lines.extend([Text("", style=style)] * blank_lines)
  1143. new_text = text.blank_copy("\n").join(new_lines)
  1144. return new_text
  1145. if __name__ == "__main__": # pragma: no cover
  1146. from pip._vendor.rich.console import Console
  1147. text = Text(
  1148. """\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"""
  1149. )
  1150. text.highlight_words(["Lorem"], "bold")
  1151. text.highlight_words(["ipsum"], "italic")
  1152. console = Console()
  1153. console.rule("justify='left'")
  1154. console.print(text, style="red")
  1155. console.print()
  1156. console.rule("justify='center'")
  1157. console.print(text, style="green", justify="center")
  1158. console.print()
  1159. console.rule("justify='right'")
  1160. console.print(text, style="blue", justify="right")
  1161. console.print()
  1162. console.rule("justify='full'")
  1163. console.print(text, style="magenta", justify="full")
  1164. console.print()