style.py 26 KB

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