style.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. import sys
  2. from functools import lru_cache
  3. from itertools import count
  4. from operator import attrgetter
  5. from pickle import dumps, loads
  6. from random import getrandbits
  7. from typing import Any, Dict, Iterable, List, Optional, Type, Union, cast
  8. from . import errors
  9. from .color import Color, ColorParseError, ColorSystem, blend_rgb
  10. from .repr import Result, rich_repr
  11. from .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme
  12. _hash_getter = attrgetter(
  13. "_color", "_bgcolor", "_attributes", "_set_attributes", "_link", "_meta"
  14. )
  15. # Style instances and style definitions are often interchangeable
  16. StyleType = Union[str, "Style"]
  17. _id_generator = count(getrandbits(24))
  18. class _Bit:
  19. """A descriptor to get/set a style attribute bit."""
  20. __slots__ = ["bit"]
  21. def __init__(self, bit_no: int) -> None:
  22. self.bit = 1 << bit_no
  23. def __get__(self, obj: "Style", objtype: Type["Style"]) -> Optional[bool]:
  24. if obj._set_attributes & self.bit:
  25. return obj._attributes & self.bit != 0
  26. return None
  27. @rich_repr
  28. class Style:
  29. """A terminal style.
  30. A terminal style consists of a color (`color`), a background color (`bgcolor`), and a number of attributes, such
  31. as bold, italic etc. The attributes have 3 states: they can either be on
  32. (``True``), off (``False``), or not set (``None``).
  33. Args:
  34. color (Union[Color, str], optional): Color of terminal text. Defaults to None.
  35. bgcolor (Union[Color, str], optional): Color of terminal background. Defaults to None.
  36. bold (bool, optional): Enable bold text. Defaults to None.
  37. dim (bool, optional): Enable dim text. Defaults to None.
  38. italic (bool, optional): Enable italic text. Defaults to None.
  39. underline (bool, optional): Enable underlined text. Defaults to None.
  40. blink (bool, optional): Enabled blinking text. Defaults to None.
  41. blink2 (bool, optional): Enable fast blinking text. Defaults to None.
  42. reverse (bool, optional): Enabled reverse text. Defaults to None.
  43. conceal (bool, optional): Enable concealed text. Defaults to None.
  44. strike (bool, optional): Enable strikethrough text. Defaults to None.
  45. underline2 (bool, optional): Enable doubly underlined text. Defaults to None.
  46. frame (bool, optional): Enable framed text. Defaults to None.
  47. encircle (bool, optional): Enable encircled text. Defaults to None.
  48. overline (bool, optional): Enable overlined text. Defaults to None.
  49. link (str, link): Link URL. Defaults to None.
  50. """
  51. _color: Optional[Color]
  52. _bgcolor: Optional[Color]
  53. _attributes: int
  54. _set_attributes: int
  55. _hash: Optional[int]
  56. _null: bool
  57. _meta: Optional[bytes]
  58. __slots__ = [
  59. "_color",
  60. "_bgcolor",
  61. "_attributes",
  62. "_set_attributes",
  63. "_link",
  64. "_link_id",
  65. "_ansi",
  66. "_style_definition",
  67. "_hash",
  68. "_null",
  69. "_meta",
  70. ]
  71. # maps bits on to SGR parameter
  72. _style_map = {
  73. 0: "1",
  74. 1: "2",
  75. 2: "3",
  76. 3: "4",
  77. 4: "5",
  78. 5: "6",
  79. 6: "7",
  80. 7: "8",
  81. 8: "9",
  82. 9: "21",
  83. 10: "51",
  84. 11: "52",
  85. 12: "53",
  86. }
  87. STYLE_ATTRIBUTES = {
  88. "dim": "dim",
  89. "d": "dim",
  90. "bold": "bold",
  91. "b": "bold",
  92. "italic": "italic",
  93. "i": "italic",
  94. "underline": "underline",
  95. "u": "underline",
  96. "blink": "blink",
  97. "blink2": "blink2",
  98. "reverse": "reverse",
  99. "r": "reverse",
  100. "conceal": "conceal",
  101. "c": "conceal",
  102. "strike": "strike",
  103. "s": "strike",
  104. "underline2": "underline2",
  105. "uu": "underline2",
  106. "frame": "frame",
  107. "encircle": "encircle",
  108. "overline": "overline",
  109. "o": "overline",
  110. }
  111. def __init__(
  112. self,
  113. *,
  114. color: Optional[Union[Color, str]] = None,
  115. bgcolor: Optional[Union[Color, str]] = None,
  116. bold: Optional[bool] = None,
  117. dim: Optional[bool] = None,
  118. italic: Optional[bool] = None,
  119. underline: Optional[bool] = None,
  120. blink: Optional[bool] = None,
  121. blink2: Optional[bool] = None,
  122. reverse: Optional[bool] = None,
  123. conceal: Optional[bool] = None,
  124. strike: Optional[bool] = None,
  125. underline2: Optional[bool] = None,
  126. frame: Optional[bool] = None,
  127. encircle: Optional[bool] = None,
  128. overline: Optional[bool] = None,
  129. link: Optional[str] = None,
  130. meta: Optional[Dict[str, Any]] = None,
  131. ):
  132. self._ansi: Optional[str] = None
  133. self._style_definition: Optional[str] = None
  134. def _make_color(color: Union[Color, str]) -> Color:
  135. return color if isinstance(color, Color) else Color.parse(color)
  136. self._color = None if color is None else _make_color(color)
  137. self._bgcolor = None if bgcolor is None else _make_color(bgcolor)
  138. self._set_attributes = sum(
  139. (
  140. bold is not None,
  141. dim is not None and 2,
  142. italic is not None and 4,
  143. underline is not None and 8,
  144. blink is not None and 16,
  145. blink2 is not None and 32,
  146. reverse is not None and 64,
  147. conceal is not None and 128,
  148. strike is not None and 256,
  149. underline2 is not None and 512,
  150. frame is not None and 1024,
  151. encircle is not None and 2048,
  152. overline is not None and 4096,
  153. )
  154. )
  155. self._attributes = (
  156. sum(
  157. (
  158. bold and 1 or 0,
  159. dim and 2 or 0,
  160. italic and 4 or 0,
  161. underline and 8 or 0,
  162. blink and 16 or 0,
  163. blink2 and 32 or 0,
  164. reverse and 64 or 0,
  165. conceal and 128 or 0,
  166. strike and 256 or 0,
  167. underline2 and 512 or 0,
  168. frame and 1024 or 0,
  169. encircle and 2048 or 0,
  170. overline and 4096 or 0,
  171. )
  172. )
  173. if self._set_attributes
  174. else 0
  175. )
  176. self._link = link
  177. self._meta = None if meta is None else dumps(meta)
  178. self._link_id = (
  179. f"{next(_id_generator)}{hash(self._meta)}" if (link or meta) else ""
  180. )
  181. self._hash: Optional[int] = None
  182. self._null = not (self._set_attributes or color or bgcolor or link or meta)
  183. @classmethod
  184. def null(cls) -> "Style":
  185. """Create an 'null' style, equivalent to Style(), but more performant."""
  186. return NULL_STYLE
  187. @classmethod
  188. def from_color(
  189. cls, color: Optional[Color] = None, bgcolor: Optional[Color] = None
  190. ) -> "Style":
  191. """Create a new style with colors and no attributes.
  192. Returns:
  193. color (Optional[Color]): A (foreground) color, or None for no color. Defaults to None.
  194. bgcolor (Optional[Color]): A (background) color, or None for no color. Defaults to None.
  195. """
  196. style: Style = cls.__new__(Style)
  197. style._ansi = None
  198. style._style_definition = None
  199. style._color = color
  200. style._bgcolor = bgcolor
  201. style._set_attributes = 0
  202. style._attributes = 0
  203. style._link = None
  204. style._link_id = ""
  205. style._meta = None
  206. style._null = not (color or bgcolor)
  207. style._hash = None
  208. return style
  209. @classmethod
  210. def from_meta(cls, meta: Optional[Dict[str, Any]]) -> "Style":
  211. """Create a new style with meta data.
  212. Returns:
  213. meta (Optional[Dict[str, Any]]): A dictionary of meta data. Defaults to None.
  214. """
  215. style: Style = cls.__new__(Style)
  216. style._ansi = None
  217. style._style_definition = None
  218. style._color = None
  219. style._bgcolor = None
  220. style._set_attributes = 0
  221. style._attributes = 0
  222. style._link = None
  223. style._meta = dumps(meta)
  224. style._link_id = f"{next(_id_generator)}{hash(style._meta)}"
  225. style._hash = None
  226. style._null = not (meta)
  227. return style
  228. @classmethod
  229. def on(cls, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Style":
  230. """Create a blank style with meta information.
  231. Example:
  232. style = Style.on(click=self.on_click)
  233. Args:
  234. meta (Optional[Dict[str, Any]], optional): An optional dict of meta information.
  235. **handlers (Any): Keyword arguments are translated in to handlers.
  236. Returns:
  237. Style: A Style with meta information attached.
  238. """
  239. meta = {} if meta is None else meta
  240. meta.update({f"@{key}": value for key, value in handlers.items()})
  241. return cls.from_meta(meta)
  242. bold = _Bit(0)
  243. dim = _Bit(1)
  244. italic = _Bit(2)
  245. underline = _Bit(3)
  246. blink = _Bit(4)
  247. blink2 = _Bit(5)
  248. reverse = _Bit(6)
  249. conceal = _Bit(7)
  250. strike = _Bit(8)
  251. underline2 = _Bit(9)
  252. frame = _Bit(10)
  253. encircle = _Bit(11)
  254. overline = _Bit(12)
  255. @property
  256. def link_id(self) -> str:
  257. """Get a link id, used in ansi code for links."""
  258. return self._link_id
  259. def __str__(self) -> str:
  260. """Re-generate style definition from attributes."""
  261. if self._style_definition is None:
  262. attributes: List[str] = []
  263. append = attributes.append
  264. bits = self._set_attributes
  265. if bits & 0b0000000001111:
  266. if bits & 1:
  267. append("bold" if self.bold else "not bold")
  268. if bits & (1 << 1):
  269. append("dim" if self.dim else "not dim")
  270. if bits & (1 << 2):
  271. append("italic" if self.italic else "not italic")
  272. if bits & (1 << 3):
  273. append("underline" if self.underline else "not underline")
  274. if bits & 0b0000111110000:
  275. if bits & (1 << 4):
  276. append("blink" if self.blink else "not blink")
  277. if bits & (1 << 5):
  278. append("blink2" if self.blink2 else "not blink2")
  279. if bits & (1 << 6):
  280. append("reverse" if self.reverse else "not reverse")
  281. if bits & (1 << 7):
  282. append("conceal" if self.conceal else "not conceal")
  283. if bits & (1 << 8):
  284. append("strike" if self.strike else "not strike")
  285. if bits & 0b1111000000000:
  286. if bits & (1 << 9):
  287. append("underline2" if self.underline2 else "not underline2")
  288. if bits & (1 << 10):
  289. append("frame" if self.frame else "not frame")
  290. if bits & (1 << 11):
  291. append("encircle" if self.encircle else "not encircle")
  292. if bits & (1 << 12):
  293. append("overline" if self.overline else "not overline")
  294. if self._color is not None:
  295. append(self._color.name)
  296. if self._bgcolor is not None:
  297. append("on")
  298. append(self._bgcolor.name)
  299. if self._link:
  300. append("link")
  301. append(self._link)
  302. self._style_definition = " ".join(attributes) or "none"
  303. return self._style_definition
  304. def __bool__(self) -> bool:
  305. """A Style is false if it has no attributes, colors, or links."""
  306. return not self._null
  307. def _make_ansi_codes(self, color_system: ColorSystem) -> str:
  308. """Generate ANSI codes for this style.
  309. Args:
  310. color_system (ColorSystem): Color system.
  311. Returns:
  312. str: String containing codes.
  313. """
  314. if self._ansi is None:
  315. sgr: List[str] = []
  316. append = sgr.append
  317. _style_map = self._style_map
  318. attributes = self._attributes & self._set_attributes
  319. if attributes:
  320. if attributes & 1:
  321. append(_style_map[0])
  322. if attributes & 2:
  323. append(_style_map[1])
  324. if attributes & 4:
  325. append(_style_map[2])
  326. if attributes & 8:
  327. append(_style_map[3])
  328. if attributes & 0b0000111110000:
  329. for bit in range(4, 9):
  330. if attributes & (1 << bit):
  331. append(_style_map[bit])
  332. if attributes & 0b1111000000000:
  333. for bit in range(9, 13):
  334. if attributes & (1 << bit):
  335. append(_style_map[bit])
  336. if self._color is not None:
  337. sgr.extend(self._color.downgrade(color_system).get_ansi_codes())
  338. if self._bgcolor is not None:
  339. sgr.extend(
  340. self._bgcolor.downgrade(color_system).get_ansi_codes(
  341. foreground=False
  342. )
  343. )
  344. self._ansi = ";".join(sgr)
  345. return self._ansi
  346. @classmethod
  347. @lru_cache(maxsize=1024)
  348. def normalize(cls, style: str) -> str:
  349. """Normalize a style definition so that styles with the same effect have the same string
  350. representation.
  351. Args:
  352. style (str): A style definition.
  353. Returns:
  354. str: Normal form of style definition.
  355. """
  356. try:
  357. return str(cls.parse(style))
  358. except errors.StyleSyntaxError:
  359. return style.strip().lower()
  360. @classmethod
  361. def pick_first(cls, *values: Optional[StyleType]) -> StyleType:
  362. """Pick first non-None style."""
  363. for value in values:
  364. if value is not None:
  365. return value
  366. raise ValueError("expected at least one non-None style")
  367. def __rich_repr__(self) -> Result:
  368. yield "color", self.color, None
  369. yield "bgcolor", self.bgcolor, None
  370. yield "bold", self.bold, None,
  371. yield "dim", self.dim, None,
  372. yield "italic", self.italic, None
  373. yield "underline", self.underline, None,
  374. yield "blink", self.blink, None
  375. yield "blink2", self.blink2, None
  376. yield "reverse", self.reverse, None
  377. yield "conceal", self.conceal, None
  378. yield "strike", self.strike, None
  379. yield "underline2", self.underline2, None
  380. yield "frame", self.frame, None
  381. yield "encircle", self.encircle, None
  382. yield "link", self.link, None
  383. if self._meta:
  384. yield "meta", self.meta
  385. def __eq__(self, other: Any) -> bool:
  386. if not isinstance(other, Style):
  387. return NotImplemented
  388. return self.__hash__() == other.__hash__()
  389. def __ne__(self, other: Any) -> bool:
  390. if not isinstance(other, Style):
  391. return NotImplemented
  392. return self.__hash__() != other.__hash__()
  393. def __hash__(self) -> int:
  394. if self._hash is not None:
  395. return self._hash
  396. self._hash = hash(_hash_getter(self))
  397. return self._hash
  398. @property
  399. def color(self) -> Optional[Color]:
  400. """The foreground color or None if it is not set."""
  401. return self._color
  402. @property
  403. def bgcolor(self) -> Optional[Color]:
  404. """The background color or None if it is not set."""
  405. return self._bgcolor
  406. @property
  407. def link(self) -> Optional[str]:
  408. """Link text, if set."""
  409. return self._link
  410. @property
  411. def transparent_background(self) -> bool:
  412. """Check if the style specified a transparent background."""
  413. return self.bgcolor is None or self.bgcolor.is_default
  414. @property
  415. def background_style(self) -> "Style":
  416. """A Style with background only."""
  417. return Style(bgcolor=self.bgcolor)
  418. @property
  419. def meta(self) -> Dict[str, Any]:
  420. """Get meta information (can not be changed after construction)."""
  421. return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))
  422. @property
  423. def without_color(self) -> "Style":
  424. """Get a copy of the style with color removed."""
  425. if self._null:
  426. return NULL_STYLE
  427. style: Style = self.__new__(Style)
  428. style._ansi = None
  429. style._style_definition = None
  430. style._color = None
  431. style._bgcolor = None
  432. style._attributes = self._attributes
  433. style._set_attributes = self._set_attributes
  434. style._link = self._link
  435. style._link_id = f"{next(_id_generator)}" if self._link else ""
  436. style._null = False
  437. style._meta = None
  438. style._hash = None
  439. return style
  440. @classmethod
  441. @lru_cache(maxsize=4096)
  442. def parse(cls, style_definition: str) -> "Style":
  443. """Parse a style definition.
  444. Args:
  445. style_definition (str): A string containing a style.
  446. Raises:
  447. errors.StyleSyntaxError: If the style definition syntax is invalid.
  448. Returns:
  449. `Style`: A Style instance.
  450. """
  451. if style_definition.strip() == "none" or not style_definition:
  452. return cls.null()
  453. STYLE_ATTRIBUTES = cls.STYLE_ATTRIBUTES
  454. color: Optional[str] = None
  455. bgcolor: Optional[str] = None
  456. attributes: Dict[str, Optional[Any]] = {}
  457. link: Optional[str] = None
  458. words = iter(style_definition.split())
  459. for original_word in words:
  460. word = original_word.lower()
  461. if word == "on":
  462. word = next(words, "")
  463. if not word:
  464. raise errors.StyleSyntaxError("color expected after 'on'")
  465. try:
  466. Color.parse(word)
  467. except ColorParseError as error:
  468. raise errors.StyleSyntaxError(
  469. f"unable to parse {word!r} as background color; {error}"
  470. ) from None
  471. bgcolor = word
  472. elif word == "not":
  473. word = next(words, "")
  474. attribute = STYLE_ATTRIBUTES.get(word)
  475. if attribute is None:
  476. raise errors.StyleSyntaxError(
  477. f"expected style attribute after 'not', found {word!r}"
  478. )
  479. attributes[attribute] = False
  480. elif word == "link":
  481. word = next(words, "")
  482. if not word:
  483. raise errors.StyleSyntaxError("URL expected after 'link'")
  484. link = word
  485. elif word in STYLE_ATTRIBUTES:
  486. attributes[STYLE_ATTRIBUTES[word]] = True
  487. else:
  488. try:
  489. Color.parse(word)
  490. except ColorParseError as error:
  491. raise errors.StyleSyntaxError(
  492. f"unable to parse {word!r} as color; {error}"
  493. ) from None
  494. color = word
  495. style = Style(color=color, bgcolor=bgcolor, link=link, **attributes)
  496. return style
  497. @lru_cache(maxsize=1024)
  498. def get_html_style(self, theme: Optional[TerminalTheme] = None) -> str:
  499. """Get a CSS style rule."""
  500. theme = theme or DEFAULT_TERMINAL_THEME
  501. css: List[str] = []
  502. append = css.append
  503. color = self.color
  504. bgcolor = self.bgcolor
  505. if self.reverse:
  506. color, bgcolor = bgcolor, color
  507. if self.dim:
  508. foreground_color = (
  509. theme.foreground_color if color is None else color.get_truecolor(theme)
  510. )
  511. color = Color.from_triplet(
  512. blend_rgb(foreground_color, theme.background_color, 0.5)
  513. )
  514. if color is not None:
  515. theme_color = color.get_truecolor(theme)
  516. append(f"color: {theme_color.hex}")
  517. append(f"text-decoration-color: {theme_color.hex}")
  518. if bgcolor is not None:
  519. theme_color = bgcolor.get_truecolor(theme, foreground=False)
  520. append(f"background-color: {theme_color.hex}")
  521. if self.bold:
  522. append("font-weight: bold")
  523. if self.italic:
  524. append("font-style: italic")
  525. if self.underline:
  526. append("text-decoration: underline")
  527. if self.strike:
  528. append("text-decoration: line-through")
  529. if self.overline:
  530. append("text-decoration: overline")
  531. return "; ".join(css)
  532. @classmethod
  533. def combine(cls, styles: Iterable["Style"]) -> "Style":
  534. """Combine styles and get result.
  535. Args:
  536. styles (Iterable[Style]): Styles to combine.
  537. Returns:
  538. Style: A new style instance.
  539. """
  540. iter_styles = iter(styles)
  541. return sum(iter_styles, next(iter_styles))
  542. @classmethod
  543. def chain(cls, *styles: "Style") -> "Style":
  544. """Combine styles from positional argument in to a single style.
  545. Args:
  546. *styles (Iterable[Style]): Styles to combine.
  547. Returns:
  548. Style: A new style instance.
  549. """
  550. iter_styles = iter(styles)
  551. return sum(iter_styles, next(iter_styles))
  552. def copy(self) -> "Style":
  553. """Get a copy of this style.
  554. Returns:
  555. Style: A new Style instance with identical attributes.
  556. """
  557. if self._null:
  558. return NULL_STYLE
  559. style: Style = self.__new__(Style)
  560. style._ansi = self._ansi
  561. style._style_definition = self._style_definition
  562. style._color = self._color
  563. style._bgcolor = self._bgcolor
  564. style._attributes = self._attributes
  565. style._set_attributes = self._set_attributes
  566. style._link = self._link
  567. style._link_id = f"{next(_id_generator)}" if self._link else ""
  568. style._hash = self._hash
  569. style._null = False
  570. style._meta = self._meta
  571. return style
  572. @lru_cache(maxsize=128)
  573. def clear_meta_and_links(self) -> "Style":
  574. """Get a copy of this style with link and meta information removed.
  575. Returns:
  576. Style: New style object.
  577. """
  578. if self._null:
  579. return NULL_STYLE
  580. style: Style = self.__new__(Style)
  581. style._ansi = self._ansi
  582. style._style_definition = self._style_definition
  583. style._color = self._color
  584. style._bgcolor = self._bgcolor
  585. style._attributes = self._attributes
  586. style._set_attributes = self._set_attributes
  587. style._link = None
  588. style._link_id = ""
  589. style._hash = None
  590. style._null = False
  591. style._meta = None
  592. return style
  593. def update_link(self, link: Optional[str] = None) -> "Style":
  594. """Get a copy with a different value for link.
  595. Args:
  596. link (str, optional): New value for link. Defaults to None.
  597. Returns:
  598. Style: A new Style instance.
  599. """
  600. style: Style = self.__new__(Style)
  601. style._ansi = self._ansi
  602. style._style_definition = self._style_definition
  603. style._color = self._color
  604. style._bgcolor = self._bgcolor
  605. style._attributes = self._attributes
  606. style._set_attributes = self._set_attributes
  607. style._link = link
  608. style._link_id = f"{next(_id_generator)}" if link else ""
  609. style._hash = None
  610. style._null = False
  611. style._meta = self._meta
  612. return style
  613. def render(
  614. self,
  615. text: str = "",
  616. *,
  617. color_system: Optional[ColorSystem] = ColorSystem.TRUECOLOR,
  618. legacy_windows: bool = False,
  619. ) -> str:
  620. """Render the ANSI codes for the style.
  621. Args:
  622. text (str, optional): A string to style. Defaults to "".
  623. color_system (Optional[ColorSystem], optional): Color system to render to. Defaults to ColorSystem.TRUECOLOR.
  624. Returns:
  625. str: A string containing ANSI style codes.
  626. """
  627. if not text or color_system is None:
  628. return text
  629. attrs = self._ansi or self._make_ansi_codes(color_system)
  630. rendered = f"\x1b[{attrs}m{text}\x1b[0m" if attrs else text
  631. if self._link and not legacy_windows:
  632. rendered = (
  633. f"\x1b]8;id={self._link_id};{self._link}\x1b\\{rendered}\x1b]8;;\x1b\\"
  634. )
  635. return rendered
  636. def test(self, text: Optional[str] = None) -> None:
  637. """Write text with style directly to terminal.
  638. This method is for testing purposes only.
  639. Args:
  640. text (Optional[str], optional): Text to style or None for style name.
  641. """
  642. text = text or str(self)
  643. sys.stdout.write(f"{self.render(text)}\n")
  644. @lru_cache(maxsize=1024)
  645. def _add(self, style: Optional["Style"]) -> "Style":
  646. if style is None or style._null:
  647. return self
  648. if self._null:
  649. return style
  650. new_style: Style = self.__new__(Style)
  651. new_style._ansi = None
  652. new_style._style_definition = None
  653. new_style._color = style._color or self._color
  654. new_style._bgcolor = style._bgcolor or self._bgcolor
  655. new_style._attributes = (self._attributes & ~style._set_attributes) | (
  656. style._attributes & style._set_attributes
  657. )
  658. new_style._set_attributes = self._set_attributes | style._set_attributes
  659. new_style._link = style._link or self._link
  660. new_style._link_id = style._link_id or self._link_id
  661. new_style._null = style._null
  662. if self._meta and style._meta:
  663. new_style._meta = dumps({**self.meta, **style.meta})
  664. else:
  665. new_style._meta = self._meta or style._meta
  666. new_style._hash = None
  667. return new_style
  668. def __add__(self, style: Optional["Style"]) -> "Style":
  669. combined_style = self._add(style)
  670. return combined_style.copy() if combined_style.link else combined_style
  671. NULL_STYLE = Style()
  672. class StyleStack:
  673. """A stack of styles."""
  674. __slots__ = ["_stack"]
  675. def __init__(self, default_style: "Style") -> None:
  676. self._stack: List[Style] = [default_style]
  677. def __repr__(self) -> str:
  678. return f"<stylestack {self._stack!r}>"
  679. @property
  680. def current(self) -> Style:
  681. """Get the Style at the top of the stack."""
  682. return self._stack[-1]
  683. def push(self, style: Style) -> None:
  684. """Push a new style on to the stack.
  685. Args:
  686. style (Style): New style to combine with current style.
  687. """
  688. self._stack.append(self._stack[-1] + style)
  689. def pop(self) -> Style:
  690. """Pop last style and discard.
  691. Returns:
  692. Style: New current style (also available as stack.current)
  693. """
  694. self._stack.pop()
  695. return self._stack[-1]