style.py 26 KB

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