console.py 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698
  1. import os
  2. import sys
  3. import threading
  4. from abc import ABC, abstractmethod
  5. from dataclasses import dataclass, field
  6. from datetime import datetime
  7. from functools import wraps
  8. from itertools import islice
  9. from math import ceil
  10. from os import PathLike
  11. from time import monotonic
  12. from types import FrameType, ModuleType, TracebackType
  13. from typing import (
  14. IO,
  15. TYPE_CHECKING,
  16. Any,
  17. Callable,
  18. Dict,
  19. Iterable,
  20. List,
  21. Literal,
  22. Mapping,
  23. NamedTuple,
  24. Optional,
  25. Protocol,
  26. TextIO,
  27. Tuple,
  28. Type,
  29. Union,
  30. cast,
  31. runtime_checkable,
  32. )
  33. from rich._null_file import NULL_FILE
  34. from . import errors, themes
  35. from ._emoji_replace import _emoji_replace
  36. from ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT
  37. from ._fileno import get_fileno
  38. from ._log_render import FormatTimeCallable, LogRender
  39. from .align import Align, AlignMethod
  40. from .color import ColorSystem, blend_rgb
  41. from .control import Control
  42. from .emoji import EmojiVariant
  43. from .highlighter import NullHighlighter, ReprHighlighter
  44. from .markup import render as render_markup
  45. from .measure import Measurement, measure_renderables
  46. from .pager import Pager, SystemPager
  47. from .protocol import rich_cast
  48. from .region import Region
  49. from .screen import Screen
  50. from .segment import Segment
  51. from .style import Style, StyleType
  52. from .styled import Styled
  53. from .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme
  54. from .text import Text, TextType
  55. from .theme import Theme, ThemeStack
  56. if TYPE_CHECKING:
  57. from ._windows import WindowsConsoleFeatures
  58. from .live import Live
  59. from .status import Status
  60. JUPYTER_DEFAULT_COLUMNS = 115
  61. JUPYTER_DEFAULT_LINES = 100
  62. WINDOWS = sys.platform == "win32"
  63. HighlighterType = Callable[[Union[str, "Text"]], "Text"]
  64. JustifyMethod = Literal["default", "left", "center", "right", "full"]
  65. OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"]
  66. class NoChange:
  67. pass
  68. NO_CHANGE = NoChange()
  69. try:
  70. _STDIN_FILENO = sys.__stdin__.fileno() # type: ignore[union-attr]
  71. except Exception:
  72. _STDIN_FILENO = 0
  73. try:
  74. _STDOUT_FILENO = sys.__stdout__.fileno() # type: ignore[union-attr]
  75. except Exception:
  76. _STDOUT_FILENO = 1
  77. try:
  78. _STDERR_FILENO = sys.__stderr__.fileno() # type: ignore[union-attr]
  79. except Exception:
  80. _STDERR_FILENO = 2
  81. _STD_STREAMS = (_STDIN_FILENO, _STDOUT_FILENO, _STDERR_FILENO)
  82. _STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO)
  83. _TERM_COLORS = {
  84. "kitty": ColorSystem.EIGHT_BIT,
  85. "256color": ColorSystem.EIGHT_BIT,
  86. "16color": ColorSystem.STANDARD,
  87. }
  88. class ConsoleDimensions(NamedTuple):
  89. """Size of the terminal."""
  90. width: int
  91. """The width of the console in 'cells'."""
  92. height: int
  93. """The height of the console in lines."""
  94. @dataclass
  95. class ConsoleOptions:
  96. """Options for __rich_console__ method."""
  97. size: ConsoleDimensions
  98. """Size of console."""
  99. legacy_windows: bool
  100. """legacy_windows: flag for legacy windows."""
  101. min_width: int
  102. """Minimum width of renderable."""
  103. max_width: int
  104. """Maximum width of renderable."""
  105. is_terminal: bool
  106. """True if the target is a terminal, otherwise False."""
  107. encoding: str
  108. """Encoding of terminal."""
  109. max_height: int
  110. """Height of container (starts as terminal)"""
  111. justify: Optional[JustifyMethod] = None
  112. """Justify value override for renderable."""
  113. overflow: Optional[OverflowMethod] = None
  114. """Overflow value override for renderable."""
  115. no_wrap: Optional[bool] = False
  116. """Disable wrapping for text."""
  117. highlight: Optional[bool] = None
  118. """Highlight override for render_str."""
  119. markup: Optional[bool] = None
  120. """Enable markup when rendering strings."""
  121. height: Optional[int] = None
  122. @property
  123. def ascii_only(self) -> bool:
  124. """Check if renderables should use ascii only."""
  125. return not self.encoding.startswith("utf")
  126. def copy(self) -> "ConsoleOptions":
  127. """Return a copy of the options.
  128. Returns:
  129. ConsoleOptions: a copy of self.
  130. """
  131. options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions)
  132. options.__dict__ = self.__dict__.copy()
  133. return options
  134. def update(
  135. self,
  136. *,
  137. width: Union[int, NoChange] = NO_CHANGE,
  138. min_width: Union[int, NoChange] = NO_CHANGE,
  139. max_width: Union[int, NoChange] = NO_CHANGE,
  140. justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE,
  141. overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE,
  142. no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE,
  143. highlight: Union[Optional[bool], NoChange] = NO_CHANGE,
  144. markup: Union[Optional[bool], NoChange] = NO_CHANGE,
  145. height: Union[Optional[int], NoChange] = NO_CHANGE,
  146. ) -> "ConsoleOptions":
  147. """Update values, return a copy."""
  148. options = self.copy()
  149. if not isinstance(width, NoChange):
  150. options.min_width = options.max_width = max(0, width)
  151. if not isinstance(min_width, NoChange):
  152. options.min_width = min_width
  153. if not isinstance(max_width, NoChange):
  154. options.max_width = max_width
  155. if not isinstance(justify, NoChange):
  156. options.justify = justify
  157. if not isinstance(overflow, NoChange):
  158. options.overflow = overflow
  159. if not isinstance(no_wrap, NoChange):
  160. options.no_wrap = no_wrap
  161. if not isinstance(highlight, NoChange):
  162. options.highlight = highlight
  163. if not isinstance(markup, NoChange):
  164. options.markup = markup
  165. if not isinstance(height, NoChange):
  166. if height is not None:
  167. options.max_height = height
  168. options.height = None if height is None else max(0, height)
  169. return options
  170. def update_width(self, width: int) -> "ConsoleOptions":
  171. """Update just the width, return a copy.
  172. Args:
  173. width (int): New width (sets both min_width and max_width)
  174. Returns:
  175. ~ConsoleOptions: New console options instance.
  176. """
  177. options = self.copy()
  178. options.min_width = options.max_width = max(0, width)
  179. return options
  180. def update_height(self, height: int) -> "ConsoleOptions":
  181. """Update the height, and return a copy.
  182. Args:
  183. height (int): New height
  184. Returns:
  185. ~ConsoleOptions: New Console options instance.
  186. """
  187. options = self.copy()
  188. options.max_height = options.height = height
  189. return options
  190. def reset_height(self) -> "ConsoleOptions":
  191. """Return a copy of the options with height set to ``None``.
  192. Returns:
  193. ~ConsoleOptions: New console options instance.
  194. """
  195. options = self.copy()
  196. options.height = None
  197. return options
  198. def update_dimensions(self, width: int, height: int) -> "ConsoleOptions":
  199. """Update the width and height, and return a copy.
  200. Args:
  201. width (int): New width (sets both min_width and max_width).
  202. height (int): New height.
  203. Returns:
  204. ~ConsoleOptions: New console options instance.
  205. """
  206. options = self.copy()
  207. options.min_width = options.max_width = max(0, width)
  208. options.height = options.max_height = height
  209. return options
  210. @runtime_checkable
  211. class RichCast(Protocol):
  212. """An object that may be 'cast' to a console renderable."""
  213. def __rich__(
  214. self,
  215. ) -> Union["ConsoleRenderable", "RichCast", str]: # pragma: no cover
  216. ...
  217. @runtime_checkable
  218. class ConsoleRenderable(Protocol):
  219. """An object that supports the console protocol."""
  220. def __rich_console__(
  221. self, console: "Console", options: "ConsoleOptions"
  222. ) -> "RenderResult": # pragma: no cover
  223. ...
  224. # A type that may be rendered by Console.
  225. RenderableType = Union[ConsoleRenderable, RichCast, str]
  226. """A string or any object that may be rendered by Rich."""
  227. # The result of calling a __rich_console__ method.
  228. RenderResult = Iterable[Union[RenderableType, Segment]]
  229. _null_highlighter = NullHighlighter()
  230. class CaptureError(Exception):
  231. """An error in the Capture context manager."""
  232. class NewLine:
  233. """A renderable to generate new line(s)"""
  234. def __init__(self, count: int = 1) -> None:
  235. self.count = count
  236. def __rich_console__(
  237. self, console: "Console", options: "ConsoleOptions"
  238. ) -> Iterable[Segment]:
  239. yield Segment("\n" * self.count)
  240. class ScreenUpdate:
  241. """Render a list of lines at a given offset."""
  242. def __init__(self, lines: List[List[Segment]], x: int, y: int) -> None:
  243. self._lines = lines
  244. self.x = x
  245. self.y = y
  246. def __rich_console__(
  247. self, console: "Console", options: ConsoleOptions
  248. ) -> RenderResult:
  249. x = self.x
  250. move_to = Control.move_to
  251. for offset, line in enumerate(self._lines, self.y):
  252. yield move_to(x, offset)
  253. yield from line
  254. class Capture:
  255. """Context manager to capture the result of printing to the console.
  256. See :meth:`~rich.console.Console.capture` for how to use.
  257. Args:
  258. console (Console): A console instance to capture output.
  259. """
  260. def __init__(self, console: "Console") -> None:
  261. self._console = console
  262. self._result: Optional[str] = None
  263. def __enter__(self) -> "Capture":
  264. self._console.begin_capture()
  265. return self
  266. def __exit__(
  267. self,
  268. exc_type: Optional[Type[BaseException]],
  269. exc_val: Optional[BaseException],
  270. exc_tb: Optional[TracebackType],
  271. ) -> None:
  272. self._result = self._console.end_capture()
  273. def get(self) -> str:
  274. """Get the result of the capture."""
  275. if self._result is None:
  276. raise CaptureError(
  277. "Capture result is not available until context manager exits."
  278. )
  279. return self._result
  280. class ThemeContext:
  281. """A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage."""
  282. def __init__(self, console: "Console", theme: Theme, inherit: bool = True) -> None:
  283. self.console = console
  284. self.theme = theme
  285. self.inherit = inherit
  286. def __enter__(self) -> "ThemeContext":
  287. self.console.push_theme(self.theme)
  288. return self
  289. def __exit__(
  290. self,
  291. exc_type: Optional[Type[BaseException]],
  292. exc_val: Optional[BaseException],
  293. exc_tb: Optional[TracebackType],
  294. ) -> None:
  295. self.console.pop_theme()
  296. class PagerContext:
  297. """A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage."""
  298. def __init__(
  299. self,
  300. console: "Console",
  301. pager: Optional[Pager] = None,
  302. styles: bool = False,
  303. links: bool = False,
  304. ) -> None:
  305. self._console = console
  306. self.pager = SystemPager() if pager is None else pager
  307. self.styles = styles
  308. self.links = links
  309. def __enter__(self) -> "PagerContext":
  310. self._console._enter_buffer()
  311. return self
  312. def __exit__(
  313. self,
  314. exc_type: Optional[Type[BaseException]],
  315. exc_val: Optional[BaseException],
  316. exc_tb: Optional[TracebackType],
  317. ) -> None:
  318. if exc_type is None:
  319. with self._console._lock:
  320. buffer: List[Segment] = self._console._buffer[:]
  321. del self._console._buffer[:]
  322. segments: Iterable[Segment] = buffer
  323. if not self.styles:
  324. segments = Segment.strip_styles(segments)
  325. elif not self.links:
  326. segments = Segment.strip_links(segments)
  327. content = self._console._render_buffer(segments)
  328. self.pager.show(content)
  329. self._console._exit_buffer()
  330. class ScreenContext:
  331. """A context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage."""
  332. def __init__(
  333. self, console: "Console", hide_cursor: bool, style: StyleType = ""
  334. ) -> None:
  335. self.console = console
  336. self.hide_cursor = hide_cursor
  337. self.screen = Screen(style=style)
  338. self._changed = False
  339. def update(
  340. self, *renderables: RenderableType, style: Optional[StyleType] = None
  341. ) -> None:
  342. """Update the screen.
  343. Args:
  344. renderable (RenderableType, optional): Optional renderable to replace current renderable,
  345. or None for no change. Defaults to None.
  346. style: (Style, optional): Replacement style, or None for no change. Defaults to None.
  347. """
  348. if renderables:
  349. self.screen.renderable = (
  350. Group(*renderables) if len(renderables) > 1 else renderables[0]
  351. )
  352. if style is not None:
  353. self.screen.style = style
  354. self.console.print(self.screen, end="")
  355. def __enter__(self) -> "ScreenContext":
  356. self._changed = self.console.set_alt_screen(True)
  357. if self._changed and self.hide_cursor:
  358. self.console.show_cursor(False)
  359. return self
  360. def __exit__(
  361. self,
  362. exc_type: Optional[Type[BaseException]],
  363. exc_val: Optional[BaseException],
  364. exc_tb: Optional[TracebackType],
  365. ) -> None:
  366. if self._changed:
  367. self.console.set_alt_screen(False)
  368. if self.hide_cursor:
  369. self.console.show_cursor(True)
  370. class Group:
  371. """Takes a group of renderables and returns a renderable object that renders the group.
  372. Args:
  373. renderables (Iterable[RenderableType]): An iterable of renderable objects.
  374. fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
  375. """
  376. def __init__(self, *renderables: "RenderableType", fit: bool = True) -> None:
  377. self._renderables = renderables
  378. self.fit = fit
  379. self._render: Optional[List[RenderableType]] = None
  380. @property
  381. def renderables(self) -> List["RenderableType"]:
  382. if self._render is None:
  383. self._render = list(self._renderables)
  384. return self._render
  385. def __rich_measure__(
  386. self, console: "Console", options: "ConsoleOptions"
  387. ) -> "Measurement":
  388. if self.fit:
  389. return measure_renderables(console, options, self.renderables)
  390. else:
  391. return Measurement(options.max_width, options.max_width)
  392. def __rich_console__(
  393. self, console: "Console", options: "ConsoleOptions"
  394. ) -> RenderResult:
  395. yield from self.renderables
  396. def group(fit: bool = True) -> Callable[..., Callable[..., Group]]:
  397. """A decorator that turns an iterable of renderables in to a group.
  398. Args:
  399. fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
  400. """
  401. def decorator(
  402. method: Callable[..., Iterable[RenderableType]],
  403. ) -> Callable[..., Group]:
  404. """Convert a method that returns an iterable of renderables in to a Group."""
  405. @wraps(method)
  406. def _replace(*args: Any, **kwargs: Any) -> Group:
  407. renderables = method(*args, **kwargs)
  408. return Group(*renderables, fit=fit)
  409. return _replace
  410. return decorator
  411. def _is_jupyter() -> bool: # pragma: no cover
  412. """Check if we're running in a Jupyter notebook."""
  413. try:
  414. get_ipython # type: ignore[name-defined]
  415. except NameError:
  416. return False
  417. ipython = get_ipython() # type: ignore[name-defined]
  418. shell = ipython.__class__.__name__
  419. if (
  420. "google.colab" in str(ipython.__class__)
  421. or os.getenv("DATABRICKS_RUNTIME_VERSION")
  422. or shell == "ZMQInteractiveShell"
  423. ):
  424. return True # Jupyter notebook or qtconsole
  425. elif shell == "TerminalInteractiveShell":
  426. return False # Terminal running IPython
  427. else:
  428. return False # Other type (?)
  429. COLOR_SYSTEMS = {
  430. "standard": ColorSystem.STANDARD,
  431. "256": ColorSystem.EIGHT_BIT,
  432. "truecolor": ColorSystem.TRUECOLOR,
  433. "windows": ColorSystem.WINDOWS,
  434. }
  435. _COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()}
  436. @dataclass
  437. class ConsoleThreadLocals(threading.local):
  438. """Thread local values for Console context."""
  439. theme_stack: ThemeStack
  440. buffer: List[Segment] = field(default_factory=list)
  441. buffer_index: int = 0
  442. class RenderHook(ABC):
  443. """Provides hooks in to the render process."""
  444. @abstractmethod
  445. def process_renderables(
  446. self, renderables: List[ConsoleRenderable]
  447. ) -> List[ConsoleRenderable]:
  448. """Called with a list of objects to render.
  449. This method can return a new list of renderables, or modify and return the same list.
  450. Args:
  451. renderables (List[ConsoleRenderable]): A number of renderable objects.
  452. Returns:
  453. List[ConsoleRenderable]: A replacement list of renderables.
  454. """
  455. _windows_console_features: Optional["WindowsConsoleFeatures"] = None
  456. def get_windows_console_features() -> "WindowsConsoleFeatures": # pragma: no cover
  457. global _windows_console_features
  458. if _windows_console_features is not None:
  459. return _windows_console_features
  460. from ._windows import get_windows_console_features
  461. _windows_console_features = get_windows_console_features()
  462. return _windows_console_features
  463. def detect_legacy_windows() -> bool:
  464. """Detect legacy Windows."""
  465. return WINDOWS and not get_windows_console_features().vt
  466. class Console:
  467. """A high level console interface.
  468. Args:
  469. color_system (str, optional): The color system supported by your terminal,
  470. either ``"standard"``, ``"256"`` or ``"truecolor"``. Leave as ``"auto"`` to autodetect.
  471. force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.
  472. force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.
  473. force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None.
  474. soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False.
  475. theme (Theme, optional): An optional style theme object, or ``None`` for default theme.
  476. stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False.
  477. file (IO, optional): A file object where the console should write to. Defaults to stdout.
  478. quiet (bool, Optional): Boolean to suppress all output. Defaults to False.
  479. width (int, optional): The width of the terminal. Leave as default to auto-detect width.
  480. height (int, optional): The height of the terminal. Leave as default to auto-detect height.
  481. style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None.
  482. no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None.
  483. tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8.
  484. record (bool, optional): Boolean to enable recording of terminal output,
  485. required to call :meth:`export_html`, :meth:`export_svg`, and :meth:`export_text`. Defaults to False.
  486. markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.
  487. emoji (bool, optional): Enable emoji code. Defaults to True.
  488. emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None.
  489. highlight (bool, optional): Enable automatic highlighting. Defaults to True.
  490. log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True.
  491. log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True.
  492. log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%X] ".
  493. highlighter (HighlighterType, optional): Default highlighter.
  494. legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``.
  495. safe_box (bool, optional): Restrict box options that don't render on legacy Windows.
  496. get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log),
  497. or None for datetime.now.
  498. get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic.
  499. """
  500. _environ: Mapping[str, str] = os.environ
  501. def __init__(
  502. self,
  503. *,
  504. color_system: Optional[
  505. Literal["auto", "standard", "256", "truecolor", "windows"]
  506. ] = "auto",
  507. force_terminal: Optional[bool] = None,
  508. force_jupyter: Optional[bool] = None,
  509. force_interactive: Optional[bool] = None,
  510. soft_wrap: bool = False,
  511. theme: Optional[Theme] = None,
  512. stderr: bool = False,
  513. file: Optional[IO[str]] = None,
  514. quiet: bool = False,
  515. width: Optional[int] = None,
  516. height: Optional[int] = None,
  517. style: Optional[StyleType] = None,
  518. no_color: Optional[bool] = None,
  519. tab_size: int = 8,
  520. record: bool = False,
  521. markup: bool = True,
  522. emoji: bool = True,
  523. emoji_variant: Optional[EmojiVariant] = None,
  524. highlight: bool = True,
  525. log_time: bool = True,
  526. log_path: bool = True,
  527. log_time_format: Union[str, FormatTimeCallable] = "[%X]",
  528. highlighter: Optional["HighlighterType"] = ReprHighlighter(),
  529. legacy_windows: Optional[bool] = None,
  530. safe_box: bool = True,
  531. get_datetime: Optional[Callable[[], datetime]] = None,
  532. get_time: Optional[Callable[[], float]] = None,
  533. _environ: Optional[Mapping[str, str]] = None,
  534. ):
  535. # Copy of os.environ allows us to replace it for testing
  536. if _environ is not None:
  537. self._environ = _environ
  538. self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter
  539. if self.is_jupyter:
  540. if width is None:
  541. jupyter_columns = self._environ.get("JUPYTER_COLUMNS")
  542. if jupyter_columns is not None and jupyter_columns.isdigit():
  543. width = int(jupyter_columns)
  544. else:
  545. width = JUPYTER_DEFAULT_COLUMNS
  546. if height is None:
  547. jupyter_lines = self._environ.get("JUPYTER_LINES")
  548. if jupyter_lines is not None and jupyter_lines.isdigit():
  549. height = int(jupyter_lines)
  550. else:
  551. height = JUPYTER_DEFAULT_LINES
  552. self.tab_size = tab_size
  553. self.record = record
  554. self._markup = markup
  555. self._emoji = emoji
  556. self._emoji_variant: Optional[EmojiVariant] = emoji_variant
  557. self._highlight = highlight
  558. self.legacy_windows: bool = (
  559. (detect_legacy_windows() and not self.is_jupyter)
  560. if legacy_windows is None
  561. else legacy_windows
  562. )
  563. if width is None:
  564. columns = self._environ.get("COLUMNS")
  565. if columns is not None and columns.isdigit():
  566. width = int(columns) - self.legacy_windows
  567. if height is None:
  568. lines = self._environ.get("LINES")
  569. if lines is not None and lines.isdigit():
  570. height = int(lines)
  571. self.soft_wrap = soft_wrap
  572. self._width = width
  573. self._height = height
  574. self._color_system: Optional[ColorSystem]
  575. self._force_terminal = None
  576. if force_terminal is not None:
  577. self._force_terminal = force_terminal
  578. self._file = file
  579. self.quiet = quiet
  580. self.stderr = stderr
  581. if color_system is None:
  582. self._color_system = None
  583. elif color_system == "auto":
  584. self._color_system = self._detect_color_system()
  585. else:
  586. self._color_system = COLOR_SYSTEMS[color_system]
  587. self._lock = threading.RLock()
  588. self._log_render = LogRender(
  589. show_time=log_time,
  590. show_path=log_path,
  591. time_format=log_time_format,
  592. )
  593. self.highlighter: HighlighterType = highlighter or _null_highlighter
  594. self.safe_box = safe_box
  595. self.get_datetime = get_datetime or datetime.now
  596. self.get_time = get_time or monotonic
  597. self.style = style
  598. self.no_color = (
  599. no_color
  600. if no_color is not None
  601. else self._environ.get("NO_COLOR", "") != ""
  602. )
  603. if force_interactive is None:
  604. tty_interactive = self._environ.get("TTY_INTERACTIVE", None)
  605. if tty_interactive is not None:
  606. if tty_interactive == "0":
  607. force_interactive = False
  608. elif tty_interactive == "1":
  609. force_interactive = True
  610. self.is_interactive = (
  611. (self.is_terminal and not self.is_dumb_terminal)
  612. if force_interactive is None
  613. else force_interactive
  614. )
  615. self._record_buffer_lock = threading.RLock()
  616. self._thread_locals = ConsoleThreadLocals(
  617. theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme)
  618. )
  619. self._record_buffer: List[Segment] = []
  620. self._render_hooks: List[RenderHook] = []
  621. self._live_stack: List[Live] = []
  622. self._is_alt_screen = False
  623. def __repr__(self) -> str:
  624. return f"<console width={self.width} {self._color_system!s}>"
  625. @property
  626. def file(self) -> IO[str]:
  627. """Get the file object to write to."""
  628. file = self._file or (sys.stderr if self.stderr else sys.stdout)
  629. file = getattr(file, "rich_proxied_file", file)
  630. if file is None:
  631. file = NULL_FILE
  632. return file
  633. @file.setter
  634. def file(self, new_file: IO[str]) -> None:
  635. """Set a new file object."""
  636. self._file = new_file
  637. @property
  638. def _buffer(self) -> List[Segment]:
  639. """Get a thread local buffer."""
  640. return self._thread_locals.buffer
  641. @property
  642. def _buffer_index(self) -> int:
  643. """Get a thread local buffer."""
  644. return self._thread_locals.buffer_index
  645. @_buffer_index.setter
  646. def _buffer_index(self, value: int) -> None:
  647. self._thread_locals.buffer_index = value
  648. @property
  649. def _theme_stack(self) -> ThemeStack:
  650. """Get the thread local theme stack."""
  651. return self._thread_locals.theme_stack
  652. def _detect_color_system(self) -> Optional[ColorSystem]:
  653. """Detect color system from env vars."""
  654. if self.is_jupyter:
  655. return ColorSystem.TRUECOLOR
  656. if not self.is_terminal or self.is_dumb_terminal:
  657. return None
  658. if WINDOWS: # pragma: no cover
  659. if self.legacy_windows: # pragma: no cover
  660. return ColorSystem.WINDOWS
  661. windows_console_features = get_windows_console_features()
  662. return (
  663. ColorSystem.TRUECOLOR
  664. if windows_console_features.truecolor
  665. else ColorSystem.EIGHT_BIT
  666. )
  667. else:
  668. color_term = self._environ.get("COLORTERM", "").strip().lower()
  669. if color_term in ("truecolor", "24bit"):
  670. return ColorSystem.TRUECOLOR
  671. term = self._environ.get("TERM", "").strip().lower()
  672. _term_name, _hyphen, colors = term.rpartition("-")
  673. color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD)
  674. return color_system
  675. def _enter_buffer(self) -> None:
  676. """Enter in to a buffer context, and buffer all output."""
  677. self._buffer_index += 1
  678. def _exit_buffer(self) -> None:
  679. """Leave buffer context, and render content if required."""
  680. self._buffer_index -= 1
  681. self._check_buffer()
  682. def set_live(self, live: "Live") -> bool:
  683. """Set Live instance. Used by Live context manager (no need to call directly).
  684. Args:
  685. live (Live): Live instance using this Console.
  686. Returns:
  687. Boolean that indicates if the live is the topmost of the stack.
  688. Raises:
  689. errors.LiveError: If this Console has a Live context currently active.
  690. """
  691. with self._lock:
  692. self._live_stack.append(live)
  693. return len(self._live_stack) == 1
  694. def clear_live(self) -> None:
  695. """Clear the Live instance. Used by the Live context manager (no need to call directly)."""
  696. with self._lock:
  697. self._live_stack.pop()
  698. def push_render_hook(self, hook: RenderHook) -> None:
  699. """Add a new render hook to the stack.
  700. Args:
  701. hook (RenderHook): Render hook instance.
  702. """
  703. with self._lock:
  704. self._render_hooks.append(hook)
  705. def pop_render_hook(self) -> None:
  706. """Pop the last renderhook from the stack."""
  707. with self._lock:
  708. self._render_hooks.pop()
  709. def __enter__(self) -> "Console":
  710. """Own context manager to enter buffer context."""
  711. self._enter_buffer()
  712. return self
  713. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
  714. """Exit buffer context."""
  715. self._exit_buffer()
  716. def begin_capture(self) -> None:
  717. """Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output."""
  718. self._enter_buffer()
  719. def end_capture(self) -> str:
  720. """End capture mode and return captured string.
  721. Returns:
  722. str: Console output.
  723. """
  724. render_result = self._render_buffer(self._buffer)
  725. del self._buffer[:]
  726. self._exit_buffer()
  727. return render_result
  728. def push_theme(self, theme: Theme, *, inherit: bool = True) -> None:
  729. """Push a new theme on to the top of the stack, replacing the styles from the previous theme.
  730. Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather
  731. than calling this method directly.
  732. Args:
  733. theme (Theme): A theme instance.
  734. inherit (bool, optional): Inherit existing styles. Defaults to True.
  735. """
  736. self._theme_stack.push_theme(theme, inherit=inherit)
  737. def pop_theme(self) -> None:
  738. """Remove theme from top of stack, restoring previous theme."""
  739. self._theme_stack.pop_theme()
  740. def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext:
  741. """Use a different theme for the duration of the context manager.
  742. Args:
  743. theme (Theme): Theme instance to user.
  744. inherit (bool, optional): Inherit existing console styles. Defaults to True.
  745. Returns:
  746. ThemeContext: [description]
  747. """
  748. return ThemeContext(self, theme, inherit)
  749. @property
  750. def color_system(self) -> Optional[str]:
  751. """Get color system string.
  752. Returns:
  753. Optional[str]: "standard", "256" or "truecolor".
  754. """
  755. if self._color_system is not None:
  756. return _COLOR_SYSTEMS_NAMES[self._color_system]
  757. else:
  758. return None
  759. @property
  760. def encoding(self) -> str:
  761. """Get the encoding of the console file, e.g. ``"utf-8"``.
  762. Returns:
  763. str: A standard encoding string.
  764. """
  765. return (getattr(self.file, "encoding", "utf-8") or "utf-8").lower()
  766. @property
  767. def is_terminal(self) -> bool:
  768. """Check if the console is writing to a terminal.
  769. Returns:
  770. bool: True if the console writing to a device capable of
  771. understanding escape sequences, otherwise False.
  772. """
  773. # If dev has explicitly set this value, return it
  774. if self._force_terminal is not None:
  775. return self._force_terminal
  776. # Fudge for Idle
  777. if hasattr(sys.stdin, "__module__") and sys.stdin.__module__.startswith(
  778. "idlelib"
  779. ):
  780. # Return False for Idle which claims to be a tty but can't handle ansi codes
  781. return False
  782. if self.is_jupyter:
  783. # return False for Jupyter, which may have FORCE_COLOR set
  784. return False
  785. environ = self._environ
  786. tty_compatible = environ.get("TTY_COMPATIBLE", "")
  787. # 0 indicates device is not tty compatible
  788. if tty_compatible == "0":
  789. return False
  790. # 1 indicates device is tty compatible
  791. if tty_compatible == "1":
  792. return True
  793. # https://force-color.org/
  794. force_color = environ.get("FORCE_COLOR")
  795. if force_color is not None:
  796. return force_color != ""
  797. # Any other value defaults to auto detect
  798. isatty: Optional[Callable[[], bool]] = getattr(self.file, "isatty", None)
  799. try:
  800. return False if isatty is None else isatty()
  801. except ValueError:
  802. # in some situation (at the end of a pytest run for example) isatty() can raise
  803. # ValueError: I/O operation on closed file
  804. # return False because we aren't in a terminal anymore
  805. return False
  806. @property
  807. def is_dumb_terminal(self) -> bool:
  808. """Detect dumb terminal.
  809. Returns:
  810. bool: True if writing to a dumb terminal, otherwise False.
  811. """
  812. _term = self._environ.get("TERM", "")
  813. is_dumb = _term.lower() in ("dumb", "unknown")
  814. return self.is_terminal and is_dumb
  815. @property
  816. def options(self) -> ConsoleOptions:
  817. """Get default console options."""
  818. size = self.size
  819. return ConsoleOptions(
  820. max_height=size.height,
  821. size=size,
  822. legacy_windows=self.legacy_windows,
  823. min_width=1,
  824. max_width=size.width,
  825. encoding=self.encoding,
  826. is_terminal=self.is_terminal,
  827. )
  828. @property
  829. def size(self) -> ConsoleDimensions:
  830. """Get the size of the console.
  831. Returns:
  832. ConsoleDimensions: A named tuple containing the dimensions.
  833. """
  834. if self._width is not None and self._height is not None:
  835. return ConsoleDimensions(self._width - self.legacy_windows, self._height)
  836. if self.is_dumb_terminal:
  837. return ConsoleDimensions(80, 25)
  838. width: Optional[int] = None
  839. height: Optional[int] = None
  840. streams = _STD_STREAMS_OUTPUT if WINDOWS else _STD_STREAMS
  841. for file_descriptor in streams:
  842. try:
  843. width, height = os.get_terminal_size(file_descriptor)
  844. except (AttributeError, ValueError, OSError): # Probably not a terminal
  845. pass
  846. else:
  847. break
  848. columns = self._environ.get("COLUMNS")
  849. if columns is not None and columns.isdigit():
  850. width = int(columns)
  851. lines = self._environ.get("LINES")
  852. if lines is not None and lines.isdigit():
  853. height = int(lines)
  854. # get_terminal_size can report 0, 0 if run from pseudo-terminal
  855. width = width or 80
  856. height = height or 25
  857. return ConsoleDimensions(
  858. width - self.legacy_windows if self._width is None else self._width,
  859. height if self._height is None else self._height,
  860. )
  861. @size.setter
  862. def size(self, new_size: Tuple[int, int]) -> None:
  863. """Set a new size for the terminal.
  864. Args:
  865. new_size (Tuple[int, int]): New width and height.
  866. """
  867. width, height = new_size
  868. self._width = width
  869. self._height = height
  870. @property
  871. def width(self) -> int:
  872. """Get the width of the console.
  873. Returns:
  874. int: The width (in characters) of the console.
  875. """
  876. return self.size.width
  877. @width.setter
  878. def width(self, width: int) -> None:
  879. """Set width.
  880. Args:
  881. width (int): New width.
  882. """
  883. self._width = width
  884. @property
  885. def height(self) -> int:
  886. """Get the height of the console.
  887. Returns:
  888. int: The height (in lines) of the console.
  889. """
  890. return self.size.height
  891. @height.setter
  892. def height(self, height: int) -> None:
  893. """Set height.
  894. Args:
  895. height (int): new height.
  896. """
  897. self._height = height
  898. def bell(self) -> None:
  899. """Play a 'bell' sound (if supported by the terminal)."""
  900. self.control(Control.bell())
  901. def capture(self) -> Capture:
  902. """A context manager to *capture* the result of print() or log() in a string,
  903. rather than writing it to the console.
  904. Example:
  905. >>> from rich.console import Console
  906. >>> console = Console()
  907. >>> with console.capture() as capture:
  908. ... console.print("[bold magenta]Hello World[/]")
  909. >>> print(capture.get())
  910. Returns:
  911. Capture: Context manager with disables writing to the terminal.
  912. """
  913. capture = Capture(self)
  914. return capture
  915. def pager(
  916. self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False
  917. ) -> PagerContext:
  918. """A context manager to display anything printed within a "pager". The pager application
  919. is defined by the system and will typically support at least pressing a key to scroll.
  920. Args:
  921. pager (Pager, optional): A pager object, or None to use :class:`~rich.pager.SystemPager`. Defaults to None.
  922. styles (bool, optional): Show styles in pager. Defaults to False.
  923. links (bool, optional): Show links in pager. Defaults to False.
  924. Example:
  925. >>> from rich.console import Console
  926. >>> from rich.__main__ import make_test_card
  927. >>> console = Console()
  928. >>> with console.pager():
  929. console.print(make_test_card())
  930. Returns:
  931. PagerContext: A context manager.
  932. """
  933. return PagerContext(self, pager=pager, styles=styles, links=links)
  934. def line(self, count: int = 1) -> None:
  935. """Write new line(s).
  936. Args:
  937. count (int, optional): Number of new lines. Defaults to 1.
  938. """
  939. assert count >= 0, "count must be >= 0"
  940. self.print(NewLine(count))
  941. def clear(self, home: bool = True) -> None:
  942. """Clear the screen.
  943. Args:
  944. home (bool, optional): Also move the cursor to 'home' position. Defaults to True.
  945. """
  946. if home:
  947. self.control(Control.clear(), Control.home())
  948. else:
  949. self.control(Control.clear())
  950. def status(
  951. self,
  952. status: RenderableType,
  953. *,
  954. spinner: str = "dots",
  955. spinner_style: StyleType = "status.spinner",
  956. speed: float = 1.0,
  957. refresh_per_second: float = 12.5,
  958. ) -> "Status":
  959. """Display a status and spinner.
  960. Args:
  961. status (RenderableType): A status renderable (str or Text typically).
  962. spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots".
  963. spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner".
  964. speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.
  965. refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.
  966. Returns:
  967. Status: A Status object that may be used as a context manager.
  968. """
  969. from .status import Status
  970. status_renderable = Status(
  971. status,
  972. console=self,
  973. spinner=spinner,
  974. spinner_style=spinner_style,
  975. speed=speed,
  976. refresh_per_second=refresh_per_second,
  977. )
  978. return status_renderable
  979. def show_cursor(self, show: bool = True) -> bool:
  980. """Show or hide the cursor.
  981. Args:
  982. show (bool, optional): Set visibility of the cursor.
  983. """
  984. if self.is_terminal:
  985. self.control(Control.show_cursor(show))
  986. return True
  987. return False
  988. def set_alt_screen(self, enable: bool = True) -> bool:
  989. """Enables alternative screen mode.
  990. Note, if you enable this mode, you should ensure that is disabled before
  991. the application exits. See :meth:`~rich.Console.screen` for a context manager
  992. that handles this for you.
  993. Args:
  994. enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True.
  995. Returns:
  996. bool: True if the control codes were written.
  997. """
  998. changed = False
  999. if self.is_terminal and not self.legacy_windows:
  1000. self.control(Control.alt_screen(enable))
  1001. changed = True
  1002. self._is_alt_screen = enable
  1003. return changed
  1004. @property
  1005. def is_alt_screen(self) -> bool:
  1006. """Check if the alt screen was enabled.
  1007. Returns:
  1008. bool: True if the alt screen was enabled, otherwise False.
  1009. """
  1010. return self._is_alt_screen
  1011. def set_window_title(self, title: str) -> bool:
  1012. """Set the title of the console terminal window.
  1013. Warning: There is no means within Rich of "resetting" the window title to its
  1014. previous value, meaning the title you set will persist even after your application
  1015. exits.
  1016. ``fish`` shell resets the window title before and after each command by default,
  1017. negating this issue. Windows Terminal and command prompt will also reset the title for you.
  1018. Most other shells and terminals, however, do not do this.
  1019. Some terminals may require configuration changes before you can set the title.
  1020. Some terminals may not support setting the title at all.
  1021. Other software (including the terminal itself, the shell, custom prompts, plugins, etc.)
  1022. may also set the terminal window title. This could result in whatever value you write
  1023. using this method being overwritten.
  1024. Args:
  1025. title (str): The new title of the terminal window.
  1026. Returns:
  1027. bool: True if the control code to change the terminal title was
  1028. written, otherwise False. Note that a return value of True
  1029. does not guarantee that the window title has actually changed,
  1030. since the feature may be unsupported/disabled in some terminals.
  1031. """
  1032. if self.is_terminal:
  1033. self.control(Control.title(title))
  1034. return True
  1035. return False
  1036. def screen(
  1037. self, hide_cursor: bool = True, style: Optional[StyleType] = None
  1038. ) -> "ScreenContext":
  1039. """Context manager to enable and disable 'alternative screen' mode.
  1040. Args:
  1041. hide_cursor (bool, optional): Also hide the cursor. Defaults to False.
  1042. style (Style, optional): Optional style for screen. Defaults to None.
  1043. Returns:
  1044. ~ScreenContext: Context which enables alternate screen on enter, and disables it on exit.
  1045. """
  1046. return ScreenContext(self, hide_cursor=hide_cursor, style=style or "")
  1047. def measure(
  1048. self, renderable: RenderableType, *, options: Optional[ConsoleOptions] = None
  1049. ) -> Measurement:
  1050. """Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains
  1051. information regarding the number of characters required to print the renderable.
  1052. Args:
  1053. renderable (RenderableType): Any renderable or string.
  1054. options (Optional[ConsoleOptions], optional): Options to use when measuring, or None
  1055. to use default options. Defaults to None.
  1056. Returns:
  1057. Measurement: A measurement of the renderable.
  1058. """
  1059. measurement = Measurement.get(self, options or self.options, renderable)
  1060. return measurement
  1061. def render(
  1062. self, renderable: RenderableType, options: Optional[ConsoleOptions] = None
  1063. ) -> Iterable[Segment]:
  1064. """Render an object in to an iterable of `Segment` instances.
  1065. This method contains the logic for rendering objects with the console protocol.
  1066. You are unlikely to need to use it directly, unless you are extending the library.
  1067. Args:
  1068. renderable (RenderableType): An object supporting the console protocol, or
  1069. an object that may be converted to a string.
  1070. options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None.
  1071. Returns:
  1072. Iterable[Segment]: An iterable of segments that may be rendered.
  1073. """
  1074. _options = options or self.options
  1075. if _options.max_width < 1:
  1076. # No space to render anything. This prevents potential recursion errors.
  1077. return
  1078. render_iterable: RenderResult
  1079. renderable = rich_cast(renderable)
  1080. if hasattr(renderable, "__rich_console__") and not isinstance(renderable, type):
  1081. render_iterable = renderable.__rich_console__(self, _options)
  1082. elif isinstance(renderable, str):
  1083. text_renderable = self.render_str(
  1084. renderable, highlight=_options.highlight, markup=_options.markup
  1085. )
  1086. render_iterable = text_renderable.__rich_console__(self, _options)
  1087. else:
  1088. raise errors.NotRenderableError(
  1089. f"Unable to render {renderable!r}; "
  1090. "A str, Segment or object with __rich_console__ method is required"
  1091. )
  1092. try:
  1093. iter_render = iter(render_iterable)
  1094. except TypeError:
  1095. raise errors.NotRenderableError(
  1096. f"object {render_iterable!r} is not renderable"
  1097. )
  1098. _Segment = Segment
  1099. _options = _options.reset_height()
  1100. for render_output in iter_render:
  1101. if isinstance(render_output, _Segment):
  1102. yield render_output
  1103. else:
  1104. yield from self.render(render_output, _options)
  1105. def render_lines(
  1106. self,
  1107. renderable: RenderableType,
  1108. options: Optional[ConsoleOptions] = None,
  1109. *,
  1110. style: Optional[Style] = None,
  1111. pad: bool = True,
  1112. new_lines: bool = False,
  1113. ) -> List[List[Segment]]:
  1114. """Render objects in to a list of lines.
  1115. The output of render_lines is useful when further formatting of rendered console text
  1116. is required, such as the Panel class which draws a border around any renderable object.
  1117. Args:
  1118. renderable (RenderableType): Any object renderable in the console.
  1119. options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``.
  1120. style (Style, optional): Optional style to apply to renderables. Defaults to ``None``.
  1121. pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``.
  1122. new_lines (bool, optional): Include "\n" characters at end of lines.
  1123. Returns:
  1124. List[List[Segment]]: A list of lines, where a line is a list of Segment objects.
  1125. """
  1126. with self._lock:
  1127. render_options = options or self.options
  1128. _rendered = self.render(renderable, render_options)
  1129. if style:
  1130. _rendered = Segment.apply_style(_rendered, style)
  1131. render_height = render_options.height
  1132. if render_height is not None:
  1133. render_height = max(0, render_height)
  1134. lines = list(
  1135. islice(
  1136. Segment.split_and_crop_lines(
  1137. _rendered,
  1138. render_options.max_width,
  1139. include_new_lines=new_lines,
  1140. pad=pad,
  1141. style=style,
  1142. ),
  1143. None,
  1144. render_height,
  1145. )
  1146. )
  1147. if render_options.height is not None:
  1148. extra_lines = render_options.height - len(lines)
  1149. if extra_lines > 0:
  1150. pad_line = [
  1151. (
  1152. [
  1153. Segment(" " * render_options.max_width, style),
  1154. Segment("\n"),
  1155. ]
  1156. if new_lines
  1157. else [Segment(" " * render_options.max_width, style)]
  1158. )
  1159. ]
  1160. lines.extend(pad_line * extra_lines)
  1161. return lines
  1162. def render_str(
  1163. self,
  1164. text: str,
  1165. *,
  1166. style: Union[str, Style] = "",
  1167. justify: Optional[JustifyMethod] = None,
  1168. overflow: Optional[OverflowMethod] = None,
  1169. emoji: Optional[bool] = None,
  1170. markup: Optional[bool] = None,
  1171. highlight: Optional[bool] = None,
  1172. highlighter: Optional[HighlighterType] = None,
  1173. ) -> "Text":
  1174. """Convert a string to a Text instance. This is called automatically if
  1175. you print or log a string.
  1176. Args:
  1177. text (str): Text to render.
  1178. style (Union[str, Style], optional): Style to apply to rendered text.
  1179. justify (str, optional): Justify method: "default", "left", "center", "full", or "right". Defaults to ``None``.
  1180. overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to ``None``.
  1181. emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default.
  1182. markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default.
  1183. highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default.
  1184. highlighter (HighlighterType, optional): Optional highlighter to apply.
  1185. Returns:
  1186. ConsoleRenderable: Renderable object.
  1187. """
  1188. emoji_enabled = emoji or (emoji is None and self._emoji)
  1189. markup_enabled = markup or (markup is None and self._markup)
  1190. highlight_enabled = highlight or (highlight is None and self._highlight)
  1191. if markup_enabled:
  1192. rich_text = render_markup(
  1193. text,
  1194. style=style,
  1195. emoji=emoji_enabled,
  1196. emoji_variant=self._emoji_variant,
  1197. )
  1198. rich_text.justify = justify
  1199. rich_text.overflow = overflow
  1200. else:
  1201. rich_text = Text(
  1202. (
  1203. _emoji_replace(text, default_variant=self._emoji_variant)
  1204. if emoji_enabled
  1205. else text
  1206. ),
  1207. justify=justify,
  1208. overflow=overflow,
  1209. style=style,
  1210. )
  1211. _highlighter = (highlighter or self.highlighter) if highlight_enabled else None
  1212. if _highlighter is not None:
  1213. highlight_text = _highlighter(str(rich_text))
  1214. highlight_text.copy_styles(rich_text)
  1215. return highlight_text
  1216. return rich_text
  1217. def get_style(
  1218. self, name: Union[str, Style], *, default: Optional[Union[Style, str]] = None
  1219. ) -> Style:
  1220. """Get a Style instance by its theme name or parse a definition.
  1221. Args:
  1222. name (str): The name of a style or a style definition.
  1223. Returns:
  1224. Style: A Style object.
  1225. Raises:
  1226. MissingStyle: If no style could be parsed from name.
  1227. """
  1228. if isinstance(name, Style):
  1229. return name
  1230. try:
  1231. style = self._theme_stack.get(name)
  1232. if style is None:
  1233. style = Style.parse(name)
  1234. return style.copy() if style.link else style
  1235. except errors.StyleSyntaxError as error:
  1236. if default is not None:
  1237. return self.get_style(default)
  1238. raise errors.MissingStyle(
  1239. f"Failed to get style {name!r}; {error}"
  1240. ) from None
  1241. def _collect_renderables(
  1242. self,
  1243. objects: Iterable[Any],
  1244. sep: str,
  1245. end: str,
  1246. *,
  1247. justify: Optional[JustifyMethod] = None,
  1248. emoji: Optional[bool] = None,
  1249. markup: Optional[bool] = None,
  1250. highlight: Optional[bool] = None,
  1251. ) -> List[ConsoleRenderable]:
  1252. """Combine a number of renderables and text into one renderable.
  1253. Args:
  1254. objects (Iterable[Any]): Anything that Rich can render.
  1255. sep (str): String to write between print data.
  1256. end (str): String to write at end of print data.
  1257. justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
  1258. emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default.
  1259. markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.
  1260. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.
  1261. Returns:
  1262. List[ConsoleRenderable]: A list of things to render.
  1263. """
  1264. def is_expandable(obj: object) -> bool:
  1265. """Check if an object is expandable by pretty printer."""
  1266. # Permit lazy loading
  1267. from .pretty import is_expandable as _is_expandable
  1268. return _is_expandable(obj)
  1269. renderables: List[ConsoleRenderable] = []
  1270. _append = renderables.append
  1271. text: List[Text] = []
  1272. append_text = text.append
  1273. append = _append
  1274. if justify in ("left", "center", "right"):
  1275. def align_append(renderable: RenderableType) -> None:
  1276. _append(Align(renderable, cast(AlignMethod, justify)))
  1277. append = align_append
  1278. _highlighter: HighlighterType = _null_highlighter
  1279. if highlight or (highlight is None and self._highlight):
  1280. _highlighter = self.highlighter
  1281. def check_text() -> None:
  1282. if text:
  1283. sep_text = Text(sep, justify=justify, end=end)
  1284. append(sep_text.join(text))
  1285. text.clear()
  1286. for renderable in objects:
  1287. renderable = rich_cast(renderable)
  1288. if isinstance(renderable, str):
  1289. append_text(
  1290. self.render_str(
  1291. renderable,
  1292. emoji=emoji,
  1293. markup=markup,
  1294. highlight=highlight,
  1295. highlighter=_highlighter,
  1296. )
  1297. )
  1298. elif isinstance(renderable, Text):
  1299. append_text(renderable)
  1300. elif isinstance(renderable, ConsoleRenderable):
  1301. check_text()
  1302. append(renderable)
  1303. elif is_expandable(renderable):
  1304. check_text()
  1305. from .pretty import Pretty
  1306. append(Pretty(renderable, highlighter=_highlighter))
  1307. else:
  1308. append_text(_highlighter(str(renderable)))
  1309. check_text()
  1310. if self.style is not None:
  1311. style = self.get_style(self.style)
  1312. renderables = [Styled(renderable, style) for renderable in renderables]
  1313. return renderables
  1314. def rule(
  1315. self,
  1316. title: TextType = "",
  1317. *,
  1318. characters: str = "─",
  1319. style: Union[str, Style] = "rule.line",
  1320. align: AlignMethod = "center",
  1321. ) -> None:
  1322. """Draw a line with optional centered title.
  1323. Args:
  1324. title (str, optional): Text to render over the rule. Defaults to "".
  1325. characters (str, optional): Character(s) to form the line. Defaults to "─".
  1326. style (str, optional): Style of line. Defaults to "rule.line".
  1327. align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center".
  1328. """
  1329. from .rule import Rule
  1330. rule = Rule(title=title, characters=characters, style=style, align=align)
  1331. self.print(rule)
  1332. def control(self, *control: Control) -> None:
  1333. """Insert non-printing control codes.
  1334. Args:
  1335. control_codes (str): Control codes, such as those that may move the cursor.
  1336. """
  1337. if not self.is_dumb_terminal:
  1338. with self:
  1339. self._buffer.extend(_control.segment for _control in control)
  1340. def out(
  1341. self,
  1342. *objects: Any,
  1343. sep: str = " ",
  1344. end: str = "\n",
  1345. style: Optional[Union[str, Style]] = None,
  1346. highlight: Optional[bool] = None,
  1347. ) -> None:
  1348. """Output to the terminal. This is a low-level way of writing to the terminal which unlike
  1349. :meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will
  1350. optionally apply highlighting and a basic style.
  1351. Args:
  1352. sep (str, optional): String to write between print data. Defaults to " ".
  1353. end (str, optional): String to write at end of print data. Defaults to "\\\\n".
  1354. style (Union[str, Style], optional): A style to apply to output. Defaults to None.
  1355. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use
  1356. console default. Defaults to ``None``.
  1357. """
  1358. raw_output: str = sep.join(str(_object) for _object in objects)
  1359. self.print(
  1360. raw_output,
  1361. style=style,
  1362. highlight=highlight,
  1363. emoji=False,
  1364. markup=False,
  1365. no_wrap=True,
  1366. overflow="ignore",
  1367. crop=False,
  1368. end=end,
  1369. )
  1370. def print(
  1371. self,
  1372. *objects: Any,
  1373. sep: str = " ",
  1374. end: str = "\n",
  1375. style: Optional[Union[str, Style]] = None,
  1376. justify: Optional[JustifyMethod] = None,
  1377. overflow: Optional[OverflowMethod] = None,
  1378. no_wrap: Optional[bool] = None,
  1379. emoji: Optional[bool] = None,
  1380. markup: Optional[bool] = None,
  1381. highlight: Optional[bool] = None,
  1382. width: Optional[int] = None,
  1383. height: Optional[int] = None,
  1384. crop: bool = True,
  1385. soft_wrap: Optional[bool] = None,
  1386. new_line_start: bool = False,
  1387. ) -> None:
  1388. """Print to the console.
  1389. Args:
  1390. objects (positional args): Objects to log to the terminal.
  1391. sep (str, optional): String to write between print data. Defaults to " ".
  1392. end (str, optional): String to write at end of print data. Defaults to "\\\\n".
  1393. style (Union[str, Style], optional): A style to apply to output. Defaults to None.
  1394. justify (str, optional): Justify method: "default", "left", "right", "center", or "full". Defaults to ``None``.
  1395. overflow (str, optional): Overflow method: "ignore", "crop", "fold", or "ellipsis". Defaults to None.
  1396. no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.
  1397. emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.
  1398. markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.
  1399. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.
  1400. width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.
  1401. crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.
  1402. soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for
  1403. Console default. Defaults to ``None``.
  1404. new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``.
  1405. """
  1406. if not objects:
  1407. if end == "\n":
  1408. objects = (NewLine(),)
  1409. else:
  1410. objects = ("",)
  1411. if soft_wrap is None:
  1412. soft_wrap = self.soft_wrap
  1413. if soft_wrap:
  1414. if no_wrap is None:
  1415. no_wrap = True
  1416. if overflow is None:
  1417. overflow = "ignore"
  1418. crop = False
  1419. render_hooks = self._render_hooks[:]
  1420. with self:
  1421. renderables = self._collect_renderables(
  1422. objects,
  1423. sep,
  1424. end,
  1425. justify=justify,
  1426. emoji=emoji,
  1427. markup=markup,
  1428. highlight=highlight,
  1429. )
  1430. for hook in render_hooks:
  1431. renderables = hook.process_renderables(renderables)
  1432. render_options = self.options.update(
  1433. justify=justify,
  1434. overflow=overflow,
  1435. width=min(width, self.width) if width is not None else NO_CHANGE,
  1436. height=height,
  1437. no_wrap=no_wrap,
  1438. markup=markup,
  1439. highlight=highlight,
  1440. )
  1441. new_segments: List[Segment] = []
  1442. extend = new_segments.extend
  1443. render = self.render
  1444. if style is None:
  1445. for renderable in renderables:
  1446. extend(render(renderable, render_options))
  1447. else:
  1448. render_style = self.get_style(style)
  1449. new_line = Segment.line()
  1450. for renderable in renderables:
  1451. for line, add_new_line in Segment.split_lines_terminator(
  1452. render(renderable, render_options)
  1453. ):
  1454. extend(Segment.apply_style(line, render_style))
  1455. if add_new_line:
  1456. new_segments.append(new_line)
  1457. if new_line_start:
  1458. if (
  1459. len("".join(segment.text for segment in new_segments).splitlines())
  1460. > 1
  1461. ):
  1462. new_segments.insert(0, Segment.line())
  1463. if crop:
  1464. buffer_extend = self._buffer.extend
  1465. for line in Segment.split_and_crop_lines(
  1466. new_segments, self.width, pad=False
  1467. ):
  1468. buffer_extend(line)
  1469. else:
  1470. self._buffer.extend(new_segments)
  1471. def print_json(
  1472. self,
  1473. json: Optional[str] = None,
  1474. *,
  1475. data: Any = None,
  1476. indent: Union[None, int, str] = 2,
  1477. highlight: bool = True,
  1478. skip_keys: bool = False,
  1479. ensure_ascii: bool = False,
  1480. check_circular: bool = True,
  1481. allow_nan: bool = True,
  1482. default: Optional[Callable[[Any], Any]] = None,
  1483. sort_keys: bool = False,
  1484. ) -> None:
  1485. """Pretty prints JSON. Output will be valid JSON.
  1486. Args:
  1487. json (Optional[str]): A string containing JSON.
  1488. data (Any): If json is not supplied, then encode this data.
  1489. indent (Union[None, int, str], optional): Number of spaces to indent. Defaults to 2.
  1490. highlight (bool, optional): Enable highlighting of output: Defaults to True.
  1491. skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
  1492. ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
  1493. check_circular (bool, optional): Check for circular references. Defaults to True.
  1494. allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
  1495. default (Callable, optional): A callable that converts values that can not be encoded
  1496. in to something that can be JSON encoded. Defaults to None.
  1497. sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
  1498. """
  1499. from rich.json import JSON
  1500. if json is None:
  1501. json_renderable = JSON.from_data(
  1502. data,
  1503. indent=indent,
  1504. highlight=highlight,
  1505. skip_keys=skip_keys,
  1506. ensure_ascii=ensure_ascii,
  1507. check_circular=check_circular,
  1508. allow_nan=allow_nan,
  1509. default=default,
  1510. sort_keys=sort_keys,
  1511. )
  1512. else:
  1513. if not isinstance(json, str):
  1514. raise TypeError(
  1515. f"json must be str. Did you mean print_json(data={json!r}) ?"
  1516. )
  1517. json_renderable = JSON(
  1518. json,
  1519. indent=indent,
  1520. highlight=highlight,
  1521. skip_keys=skip_keys,
  1522. ensure_ascii=ensure_ascii,
  1523. check_circular=check_circular,
  1524. allow_nan=allow_nan,
  1525. default=default,
  1526. sort_keys=sort_keys,
  1527. )
  1528. self.print(json_renderable, soft_wrap=True)
  1529. def update_screen(
  1530. self,
  1531. renderable: RenderableType,
  1532. *,
  1533. region: Optional[Region] = None,
  1534. options: Optional[ConsoleOptions] = None,
  1535. ) -> None:
  1536. """Update the screen at a given offset.
  1537. Args:
  1538. renderable (RenderableType): A Rich renderable.
  1539. region (Region, optional): Region of screen to update, or None for entire screen. Defaults to None.
  1540. x (int, optional): x offset. Defaults to 0.
  1541. y (int, optional): y offset. Defaults to 0.
  1542. Raises:
  1543. errors.NoAltScreen: If the Console isn't in alt screen mode.
  1544. """
  1545. if not self.is_alt_screen:
  1546. raise errors.NoAltScreen("Alt screen must be enabled to call update_screen")
  1547. render_options = options or self.options
  1548. if region is None:
  1549. x = y = 0
  1550. render_options = render_options.update_dimensions(
  1551. render_options.max_width, render_options.height or self.height
  1552. )
  1553. else:
  1554. x, y, width, height = region
  1555. render_options = render_options.update_dimensions(width, height)
  1556. lines = self.render_lines(renderable, options=render_options)
  1557. self.update_screen_lines(lines, x, y)
  1558. def update_screen_lines(
  1559. self, lines: List[List[Segment]], x: int = 0, y: int = 0
  1560. ) -> None:
  1561. """Update lines of the screen at a given offset.
  1562. Args:
  1563. lines (List[List[Segment]]): Rendered lines (as produced by :meth:`~rich.Console.render_lines`).
  1564. x (int, optional): x offset (column no). Defaults to 0.
  1565. y (int, optional): y offset (column no). Defaults to 0.
  1566. Raises:
  1567. errors.NoAltScreen: If the Console isn't in alt screen mode.
  1568. """
  1569. if not self.is_alt_screen:
  1570. raise errors.NoAltScreen("Alt screen must be enabled to call update_screen")
  1571. screen_update = ScreenUpdate(lines, x, y)
  1572. segments = self.render(screen_update)
  1573. self._buffer.extend(segments)
  1574. self._check_buffer()
  1575. def print_exception(
  1576. self,
  1577. *,
  1578. width: Optional[int] = 100,
  1579. extra_lines: int = 3,
  1580. theme: Optional[str] = None,
  1581. word_wrap: bool = False,
  1582. show_locals: bool = False,
  1583. suppress: Iterable[Union[str, ModuleType]] = (),
  1584. max_frames: int = 100,
  1585. ) -> None:
  1586. """Prints a rich render of the last exception and traceback.
  1587. Args:
  1588. width (Optional[int], optional): Number of characters used to render code. Defaults to 100.
  1589. extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
  1590. theme (str, optional): Override pygments theme used in traceback
  1591. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
  1592. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  1593. suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
  1594. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
  1595. """
  1596. from .traceback import Traceback
  1597. traceback = Traceback(
  1598. width=width,
  1599. extra_lines=extra_lines,
  1600. theme=theme,
  1601. word_wrap=word_wrap,
  1602. show_locals=show_locals,
  1603. suppress=suppress,
  1604. max_frames=max_frames,
  1605. )
  1606. self.print(traceback)
  1607. @staticmethod
  1608. def _caller_frame_info(
  1609. offset: int, currentframe: Optional[Callable[[], Optional[FrameType]]] = None
  1610. ) -> Tuple[str, int, Dict[str, Any]]:
  1611. """Get caller frame information.
  1612. Args:
  1613. offset (int): the caller offset within the current frame stack.
  1614. currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to
  1615. retrieve the current frame. Defaults to None, which will use ``inspect.currentframe()``.
  1616. Returns:
  1617. Tuple[str, int, Dict[str, Any]]: A tuple containing the filename, the line number and
  1618. the dictionary of local variables associated with the caller frame.
  1619. Raises:
  1620. RuntimeError: If the stack offset is invalid.
  1621. """
  1622. # Ignore the frame of this local helper
  1623. offset += 1
  1624. if currentframe is None:
  1625. import inspect
  1626. frame = inspect.currentframe()
  1627. else:
  1628. frame = currentframe()
  1629. if frame is not None:
  1630. while offset and frame is not None:
  1631. frame = frame.f_back
  1632. offset -= 1
  1633. assert frame is not None
  1634. return frame.f_code.co_filename, frame.f_lineno, frame.f_locals
  1635. else:
  1636. from inspect import stack
  1637. frame_info = stack()[offset]
  1638. return frame_info.filename, frame_info.lineno, frame_info.frame.f_locals
  1639. def log(
  1640. self,
  1641. *objects: Any,
  1642. sep: str = " ",
  1643. end: str = "\n",
  1644. style: Optional[Union[str, Style]] = None,
  1645. justify: Optional[JustifyMethod] = None,
  1646. emoji: Optional[bool] = None,
  1647. markup: Optional[bool] = None,
  1648. highlight: Optional[bool] = None,
  1649. log_locals: bool = False,
  1650. _stack_offset: int = 1,
  1651. ) -> None:
  1652. """Log rich content to the terminal.
  1653. Args:
  1654. objects (positional args): Objects to log to the terminal.
  1655. sep (str, optional): String to write between print data. Defaults to " ".
  1656. end (str, optional): String to write at end of print data. Defaults to "\\\\n".
  1657. style (Union[str, Style], optional): A style to apply to output. Defaults to None.
  1658. justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
  1659. emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None.
  1660. markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None.
  1661. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None.
  1662. log_locals (bool, optional): Boolean to enable logging of locals where ``log()``
  1663. was called. Defaults to False.
  1664. _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.
  1665. """
  1666. if not objects:
  1667. objects = (NewLine(),)
  1668. render_hooks = self._render_hooks[:]
  1669. with self:
  1670. renderables = self._collect_renderables(
  1671. objects,
  1672. sep,
  1673. end,
  1674. justify=justify,
  1675. emoji=emoji,
  1676. markup=markup,
  1677. highlight=highlight,
  1678. )
  1679. if style is not None:
  1680. renderables = [Styled(renderable, style) for renderable in renderables]
  1681. filename, line_no, locals = self._caller_frame_info(_stack_offset)
  1682. link_path = None if filename.startswith("<") else os.path.abspath(filename)
  1683. path = filename.rpartition(os.sep)[-1]
  1684. if log_locals:
  1685. from .scope import render_scope
  1686. locals_map = {
  1687. key: value
  1688. for key, value in locals.items()
  1689. if not key.startswith("__")
  1690. }
  1691. renderables.append(render_scope(locals_map, title="[i]locals"))
  1692. renderables = [
  1693. self._log_render(
  1694. self,
  1695. renderables,
  1696. log_time=self.get_datetime(),
  1697. path=path,
  1698. line_no=line_no,
  1699. link_path=link_path,
  1700. )
  1701. ]
  1702. for hook in render_hooks:
  1703. renderables = hook.process_renderables(renderables)
  1704. new_segments: List[Segment] = []
  1705. extend = new_segments.extend
  1706. render = self.render
  1707. render_options = self.options
  1708. for renderable in renderables:
  1709. extend(render(renderable, render_options))
  1710. buffer_extend = self._buffer.extend
  1711. for line in Segment.split_and_crop_lines(
  1712. new_segments, self.width, pad=False
  1713. ):
  1714. buffer_extend(line)
  1715. def on_broken_pipe(self) -> None:
  1716. """This function is called when a `BrokenPipeError` is raised.
  1717. This can occur when piping Textual output in Linux and macOS.
  1718. The default implementation is to exit the app, but you could implement
  1719. this method in a subclass to change the behavior.
  1720. See https://docs.python.org/3/library/signal.html#note-on-sigpipe for details.
  1721. """
  1722. self.quiet = True
  1723. devnull = os.open(os.devnull, os.O_WRONLY)
  1724. os.dup2(devnull, sys.stdout.fileno())
  1725. raise SystemExit(1)
  1726. def _check_buffer(self) -> None:
  1727. """Check if the buffer may be rendered. Render it if it can (e.g. Console.quiet is False)
  1728. Rendering is supported on Windows, Unix and Jupyter environments. For
  1729. legacy Windows consoles, the win32 API is called directly.
  1730. This method will also record what it renders if recording is enabled via Console.record.
  1731. """
  1732. if self.quiet:
  1733. del self._buffer[:]
  1734. return
  1735. try:
  1736. self._write_buffer()
  1737. except BrokenPipeError:
  1738. self.on_broken_pipe()
  1739. def _write_buffer(self) -> None:
  1740. """Write the buffer to the output file."""
  1741. with self._lock:
  1742. if self.record and not self._buffer_index:
  1743. with self._record_buffer_lock:
  1744. self._record_buffer.extend(self._buffer[:])
  1745. if self._buffer_index == 0:
  1746. if self.is_jupyter: # pragma: no cover
  1747. from .jupyter import display
  1748. display(self._buffer, self._render_buffer(self._buffer[:]))
  1749. del self._buffer[:]
  1750. else:
  1751. if WINDOWS:
  1752. use_legacy_windows_render = False
  1753. if self.legacy_windows:
  1754. fileno = get_fileno(self.file)
  1755. if fileno is not None:
  1756. use_legacy_windows_render = (
  1757. fileno in _STD_STREAMS_OUTPUT
  1758. )
  1759. if use_legacy_windows_render:
  1760. from rich._win32_console import LegacyWindowsTerm
  1761. from rich._windows_renderer import legacy_windows_render
  1762. buffer = self._buffer[:]
  1763. if self.no_color and self._color_system:
  1764. buffer = list(Segment.remove_color(buffer))
  1765. legacy_windows_render(buffer, LegacyWindowsTerm(self.file))
  1766. else:
  1767. # Either a non-std stream on legacy Windows, or modern Windows.
  1768. text = self._render_buffer(self._buffer[:])
  1769. # https://bugs.python.org/issue37871
  1770. # https://github.com/python/cpython/issues/82052
  1771. # We need to avoid writing more than 32Kb in a single write, due to the above bug
  1772. write = self.file.write
  1773. # Worse case scenario, every character is 4 bytes of utf-8
  1774. MAX_WRITE = 32 * 1024 // 4
  1775. try:
  1776. if len(text) <= MAX_WRITE:
  1777. write(text)
  1778. else:
  1779. batch: List[str] = []
  1780. batch_append = batch.append
  1781. size = 0
  1782. for line in text.splitlines(True):
  1783. if size + len(line) > MAX_WRITE and batch:
  1784. write("".join(batch))
  1785. batch.clear()
  1786. size = 0
  1787. batch_append(line)
  1788. size += len(line)
  1789. if batch:
  1790. write("".join(batch))
  1791. batch.clear()
  1792. except UnicodeEncodeError as error:
  1793. error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***"
  1794. raise
  1795. else:
  1796. text = self._render_buffer(self._buffer[:])
  1797. try:
  1798. self.file.write(text)
  1799. except UnicodeEncodeError as error:
  1800. error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***"
  1801. raise
  1802. self.file.flush()
  1803. del self._buffer[:]
  1804. def _render_buffer(self, buffer: Iterable[Segment]) -> str:
  1805. """Render buffered output, and clear buffer."""
  1806. output: List[str] = []
  1807. append = output.append
  1808. color_system = self._color_system
  1809. legacy_windows = self.legacy_windows
  1810. not_terminal = not self.is_terminal
  1811. if self.no_color and color_system:
  1812. buffer = Segment.remove_color(buffer)
  1813. for text, style, control in buffer:
  1814. if style:
  1815. append(
  1816. style.render(
  1817. text,
  1818. color_system=color_system,
  1819. legacy_windows=legacy_windows,
  1820. )
  1821. )
  1822. elif not (not_terminal and control):
  1823. append(text)
  1824. rendered = "".join(output)
  1825. return rendered
  1826. def input(
  1827. self,
  1828. prompt: TextType = "",
  1829. *,
  1830. markup: bool = True,
  1831. emoji: bool = True,
  1832. password: bool = False,
  1833. stream: Optional[TextIO] = None,
  1834. ) -> str:
  1835. """Displays a prompt and waits for input from the user. The prompt may contain color / style.
  1836. It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded.
  1837. Args:
  1838. prompt (Union[str, Text]): Text to render in the prompt.
  1839. markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.
  1840. emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.
  1841. password: (bool, optional): Hide typed text. Defaults to False.
  1842. stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.
  1843. Returns:
  1844. str: Text read from stdin.
  1845. """
  1846. if prompt:
  1847. self.print(prompt, markup=markup, emoji=emoji, end="")
  1848. if password:
  1849. import getpass as _getpass_mod
  1850. result = _getpass_mod.getpass("", stream=stream)
  1851. else:
  1852. if stream:
  1853. result = stream.readline()
  1854. else:
  1855. result = input()
  1856. return result
  1857. def export_text(self, *, clear: bool = True, styles: bool = False) -> str:
  1858. """Generate text from console contents (requires record=True argument in constructor).
  1859. Args:
  1860. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1861. styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.
  1862. Defaults to ``False``.
  1863. Returns:
  1864. str: String containing console contents.
  1865. """
  1866. assert (
  1867. self.record
  1868. ), "To export console contents set record=True in the constructor or instance"
  1869. with self._record_buffer_lock:
  1870. if styles:
  1871. text = "".join(
  1872. (style.render(text) if style else text)
  1873. for text, style, _ in self._record_buffer
  1874. )
  1875. else:
  1876. text = "".join(
  1877. segment.text
  1878. for segment in self._record_buffer
  1879. if not segment.control
  1880. )
  1881. if clear:
  1882. del self._record_buffer[:]
  1883. return text
  1884. def save_text(
  1885. self,
  1886. path: Union[str, PathLike[str]],
  1887. *,
  1888. clear: bool = True,
  1889. styles: bool = False,
  1890. ) -> None:
  1891. """Generate text from console and save to a given location (requires record=True argument in constructor).
  1892. Args:
  1893. path (Union[str, PathLike[str]]): Path to write text files.
  1894. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1895. styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.
  1896. Defaults to ``False``.
  1897. """
  1898. text = self.export_text(clear=clear, styles=styles)
  1899. with open(path, "w", encoding="utf-8") as write_file:
  1900. write_file.write(text)
  1901. def export_html(
  1902. self,
  1903. *,
  1904. theme: Optional[TerminalTheme] = None,
  1905. clear: bool = True,
  1906. code_format: Optional[str] = None,
  1907. inline_styles: bool = False,
  1908. ) -> str:
  1909. """Generate HTML from console contents (requires record=True argument in constructor).
  1910. Args:
  1911. theme (TerminalTheme, optional): TerminalTheme object containing console colors.
  1912. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1913. code_format (str, optional): Format string to render HTML. In addition to '{foreground}',
  1914. '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``.
  1915. inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
  1916. larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
  1917. Defaults to False.
  1918. Returns:
  1919. str: String containing console contents as HTML.
  1920. """
  1921. from html import escape
  1922. assert (
  1923. self.record
  1924. ), "To export console contents set record=True in the constructor or instance"
  1925. fragments: List[str] = []
  1926. append = fragments.append
  1927. _theme = theme or DEFAULT_TERMINAL_THEME
  1928. stylesheet = ""
  1929. render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format
  1930. with self._record_buffer_lock:
  1931. if inline_styles:
  1932. for text, style, _ in Segment.filter_control(
  1933. Segment.simplify(self._record_buffer)
  1934. ):
  1935. text = escape(text)
  1936. if style:
  1937. rule = style.get_html_style(_theme)
  1938. if style.link:
  1939. text = f'<a href="{style.link}">{text}</a>'
  1940. text = f'<span style="{rule}">{text}</span>' if rule else text
  1941. append(text)
  1942. else:
  1943. styles: Dict[str, int] = {}
  1944. for text, style, _ in Segment.filter_control(
  1945. Segment.simplify(self._record_buffer)
  1946. ):
  1947. text = escape(text)
  1948. if style:
  1949. rule = style.get_html_style(_theme)
  1950. style_number = styles.setdefault(rule, len(styles) + 1)
  1951. if style.link:
  1952. text = f'<a class="r{style_number}" href="{style.link}">{text}</a>'
  1953. else:
  1954. text = f'<span class="r{style_number}">{text}</span>'
  1955. append(text)
  1956. stylesheet_rules: List[str] = []
  1957. stylesheet_append = stylesheet_rules.append
  1958. for style_rule, style_number in styles.items():
  1959. if style_rule:
  1960. stylesheet_append(f".r{style_number} {{{style_rule}}}")
  1961. stylesheet = "\n".join(stylesheet_rules)
  1962. rendered_code = render_code_format.format(
  1963. code="".join(fragments),
  1964. stylesheet=stylesheet,
  1965. foreground=_theme.foreground_color.hex,
  1966. background=_theme.background_color.hex,
  1967. )
  1968. if clear:
  1969. del self._record_buffer[:]
  1970. return rendered_code
  1971. def save_html(
  1972. self,
  1973. path: Union[str, PathLike[str]],
  1974. *,
  1975. theme: Optional[TerminalTheme] = None,
  1976. clear: bool = True,
  1977. code_format: str = CONSOLE_HTML_FORMAT,
  1978. inline_styles: bool = False,
  1979. ) -> None:
  1980. """Generate HTML from console contents and write to a file (requires record=True argument in constructor).
  1981. Args:
  1982. path (Union[str, PathLike[str]]): Path to write html file.
  1983. theme (TerminalTheme, optional): TerminalTheme object containing console colors.
  1984. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1985. code_format (str, optional): Format string to render HTML. In addition to '{foreground}',
  1986. '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``.
  1987. inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
  1988. larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
  1989. Defaults to False.
  1990. """
  1991. html = self.export_html(
  1992. theme=theme,
  1993. clear=clear,
  1994. code_format=code_format,
  1995. inline_styles=inline_styles,
  1996. )
  1997. with open(path, "w", encoding="utf-8") as write_file:
  1998. write_file.write(html)
  1999. def export_svg(
  2000. self,
  2001. *,
  2002. title: str = "Rich",
  2003. theme: Optional[TerminalTheme] = None,
  2004. clear: bool = True,
  2005. code_format: str = CONSOLE_SVG_FORMAT,
  2006. font_aspect_ratio: float = 0.61,
  2007. unique_id: Optional[str] = None,
  2008. ) -> str:
  2009. """
  2010. Generate an SVG from the console contents (requires record=True in Console constructor).
  2011. Args:
  2012. title (str, optional): The title of the tab in the output image
  2013. theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal
  2014. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``
  2015. code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables
  2016. into the string in order to form the final SVG output. The default template used and the variables
  2017. injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.
  2018. font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format``
  2019. string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font).
  2020. If you aren't specifying a different font inside ``code_format``, you probably don't need this.
  2021. unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node
  2022. ids). If not set, this defaults to a computed value based on the recorded content.
  2023. """
  2024. import zlib
  2025. from html import escape
  2026. from rich.cells import cell_len
  2027. style_cache: Dict[Style, str] = {}
  2028. def get_svg_style(style: Style) -> str:
  2029. """Convert a Style to CSS rules for SVG."""
  2030. if style in style_cache:
  2031. return style_cache[style]
  2032. css_rules = []
  2033. color = (
  2034. _theme.foreground_color
  2035. if (style.color is None or style.color.is_default)
  2036. else style.color.get_truecolor(_theme)
  2037. )
  2038. bgcolor = (
  2039. _theme.background_color
  2040. if (style.bgcolor is None or style.bgcolor.is_default)
  2041. else style.bgcolor.get_truecolor(_theme)
  2042. )
  2043. if style.reverse:
  2044. color, bgcolor = bgcolor, color
  2045. if style.dim:
  2046. color = blend_rgb(color, bgcolor, 0.4)
  2047. css_rules.append(f"fill: {color.hex}")
  2048. if style.bold:
  2049. css_rules.append("font-weight: bold")
  2050. if style.italic:
  2051. css_rules.append("font-style: italic;")
  2052. if style.underline:
  2053. css_rules.append("text-decoration: underline;")
  2054. if style.strike:
  2055. css_rules.append("text-decoration: line-through;")
  2056. css = ";".join(css_rules)
  2057. style_cache[style] = css
  2058. return css
  2059. _theme = theme or SVG_EXPORT_THEME
  2060. width = self.width
  2061. char_height = 20
  2062. char_width = char_height * font_aspect_ratio
  2063. line_height = char_height * 1.22
  2064. margin_top = 1
  2065. margin_right = 1
  2066. margin_bottom = 1
  2067. margin_left = 1
  2068. padding_top = 40
  2069. padding_right = 8
  2070. padding_bottom = 8
  2071. padding_left = 8
  2072. padding_width = padding_left + padding_right
  2073. padding_height = padding_top + padding_bottom
  2074. margin_width = margin_left + margin_right
  2075. margin_height = margin_top + margin_bottom
  2076. text_backgrounds: List[str] = []
  2077. text_group: List[str] = []
  2078. classes: Dict[str, int] = {}
  2079. style_no = 1
  2080. def escape_text(text: str) -> str:
  2081. """HTML escape text and replace spaces with nbsp."""
  2082. return escape(text).replace(" ", "&#160;")
  2083. def make_tag(
  2084. name: str, content: Optional[str] = None, **attribs: object
  2085. ) -> str:
  2086. """Make a tag from name, content, and attributes."""
  2087. def stringify(value: object) -> str:
  2088. if isinstance(value, (float)):
  2089. return format(value, "g")
  2090. return str(value)
  2091. tag_attribs = " ".join(
  2092. f'{k.lstrip("_").replace("_", "-")}="{stringify(v)}"'
  2093. for k, v in attribs.items()
  2094. )
  2095. return (
  2096. f"<{name} {tag_attribs}>{content}</{name}>"
  2097. if content
  2098. else f"<{name} {tag_attribs}/>"
  2099. )
  2100. with self._record_buffer_lock:
  2101. segments = list(Segment.filter_control(self._record_buffer))
  2102. if clear:
  2103. self._record_buffer.clear()
  2104. if unique_id is None:
  2105. unique_id = "terminal-" + str(
  2106. zlib.adler32(
  2107. ("".join(repr(segment) for segment in segments)).encode(
  2108. "utf-8",
  2109. "ignore",
  2110. )
  2111. + title.encode("utf-8", "ignore")
  2112. )
  2113. )
  2114. y = 0
  2115. for y, line in enumerate(Segment.split_and_crop_lines(segments, length=width)):
  2116. x = 0
  2117. for text, style, _control in line:
  2118. style = style or Style()
  2119. rules = get_svg_style(style)
  2120. if rules not in classes:
  2121. classes[rules] = style_no
  2122. style_no += 1
  2123. class_name = f"r{classes[rules]}"
  2124. if style.reverse:
  2125. has_background = True
  2126. background = (
  2127. _theme.foreground_color.hex
  2128. if style.color is None
  2129. else style.color.get_truecolor(_theme).hex
  2130. )
  2131. else:
  2132. bgcolor = style.bgcolor
  2133. has_background = bgcolor is not None and not bgcolor.is_default
  2134. background = (
  2135. _theme.background_color.hex
  2136. if style.bgcolor is None
  2137. else style.bgcolor.get_truecolor(_theme).hex
  2138. )
  2139. text_length = cell_len(text)
  2140. if has_background:
  2141. text_backgrounds.append(
  2142. make_tag(
  2143. "rect",
  2144. fill=background,
  2145. x=x * char_width,
  2146. y=y * line_height + 1.5,
  2147. width=char_width * text_length,
  2148. height=line_height + 0.25,
  2149. shape_rendering="crispEdges",
  2150. )
  2151. )
  2152. if text != " " * len(text):
  2153. text_group.append(
  2154. make_tag(
  2155. "text",
  2156. escape_text(text),
  2157. _class=f"{unique_id}-{class_name}",
  2158. x=x * char_width,
  2159. y=y * line_height + char_height,
  2160. textLength=char_width * len(text),
  2161. clip_path=f"url(#{unique_id}-line-{y})",
  2162. )
  2163. )
  2164. x += cell_len(text)
  2165. line_offsets = [line_no * line_height + 1.5 for line_no in range(y)]
  2166. lines = "\n".join(
  2167. f"""<clipPath id="{unique_id}-line-{line_no}">
  2168. {make_tag("rect", x=0, y=offset, width=char_width * width, height=line_height + 0.25)}
  2169. </clipPath>"""
  2170. for line_no, offset in enumerate(line_offsets)
  2171. )
  2172. styles = "\n".join(
  2173. f".{unique_id}-r{rule_no} {{ {css} }}" for css, rule_no in classes.items()
  2174. )
  2175. backgrounds = "".join(text_backgrounds)
  2176. matrix = "".join(text_group)
  2177. terminal_width = ceil(width * char_width + padding_width)
  2178. terminal_height = (y + 1) * line_height + padding_height
  2179. chrome = make_tag(
  2180. "rect",
  2181. fill=_theme.background_color.hex,
  2182. stroke="rgba(255,255,255,0.35)",
  2183. stroke_width="1",
  2184. x=margin_left,
  2185. y=margin_top,
  2186. width=terminal_width,
  2187. height=terminal_height,
  2188. rx=8,
  2189. )
  2190. title_color = _theme.foreground_color.hex
  2191. if title:
  2192. chrome += make_tag(
  2193. "text",
  2194. escape_text(title),
  2195. _class=f"{unique_id}-title",
  2196. fill=title_color,
  2197. text_anchor="middle",
  2198. x=terminal_width // 2,
  2199. y=margin_top + char_height + 6,
  2200. )
  2201. chrome += f"""
  2202. <g transform="translate(26,22)">
  2203. <circle cx="0" cy="0" r="7" fill="#ff5f57"/>
  2204. <circle cx="22" cy="0" r="7" fill="#febc2e"/>
  2205. <circle cx="44" cy="0" r="7" fill="#28c840"/>
  2206. </g>
  2207. """
  2208. svg = code_format.format(
  2209. unique_id=unique_id,
  2210. char_width=char_width,
  2211. char_height=char_height,
  2212. line_height=line_height,
  2213. terminal_width=char_width * width - 1,
  2214. terminal_height=(y + 1) * line_height - 1,
  2215. width=terminal_width + margin_width,
  2216. height=terminal_height + margin_height,
  2217. terminal_x=margin_left + padding_left,
  2218. terminal_y=margin_top + padding_top,
  2219. styles=styles,
  2220. chrome=chrome,
  2221. backgrounds=backgrounds,
  2222. matrix=matrix,
  2223. lines=lines,
  2224. )
  2225. return svg
  2226. def save_svg(
  2227. self,
  2228. path: Union[str, PathLike[str]],
  2229. *,
  2230. title: str = "Rich",
  2231. theme: Optional[TerminalTheme] = None,
  2232. clear: bool = True,
  2233. code_format: str = CONSOLE_SVG_FORMAT,
  2234. font_aspect_ratio: float = 0.61,
  2235. unique_id: Optional[str] = None,
  2236. ) -> None:
  2237. """Generate an SVG file from the console contents (requires record=True in Console constructor).
  2238. Args:
  2239. path (Union[str, PathLike[str]]): The path to write the SVG to.
  2240. title (str, optional): The title of the tab in the output image
  2241. theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal
  2242. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``
  2243. code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables
  2244. into the string in order to form the final SVG output. The default template used and the variables
  2245. injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.
  2246. font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format``
  2247. string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font).
  2248. If you aren't specifying a different font inside ``code_format``, you probably don't need this.
  2249. unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node
  2250. ids). If not set, this defaults to a computed value based on the recorded content.
  2251. """
  2252. svg = self.export_svg(
  2253. title=title,
  2254. theme=theme,
  2255. clear=clear,
  2256. code_format=code_format,
  2257. font_aspect_ratio=font_aspect_ratio,
  2258. unique_id=unique_id,
  2259. )
  2260. with open(path, "w", encoding="utf-8") as write_file:
  2261. write_file.write(svg)
  2262. if __name__ == "__main__": # pragma: no cover
  2263. console = Console(record=True)
  2264. console.log(
  2265. "JSONRPC [i]request[/i]",
  2266. 5,
  2267. 1.3,
  2268. True,
  2269. False,
  2270. None,
  2271. {
  2272. "jsonrpc": "2.0",
  2273. "method": "subtract",
  2274. "params": {"minuend": 42, "subtrahend": 23},
  2275. "id": 3,
  2276. },
  2277. )
  2278. console.log("Hello, World!", "{'a': 1}", repr(console))
  2279. console.print(
  2280. {
  2281. "name": None,
  2282. "empty": [],
  2283. "quiz": {
  2284. "sport": {
  2285. "answered": True,
  2286. "q1": {
  2287. "question": "Which one is correct team name in NBA?",
  2288. "options": [
  2289. "New York Bulls",
  2290. "Los Angeles Kings",
  2291. "Golden State Warriors",
  2292. "Huston Rocket",
  2293. ],
  2294. "answer": "Huston Rocket",
  2295. },
  2296. },
  2297. "maths": {
  2298. "answered": False,
  2299. "q1": {
  2300. "question": "5 + 7 = ?",
  2301. "options": [10, 11, 12, 13],
  2302. "answer": 12,
  2303. },
  2304. "q2": {
  2305. "question": "12 - 8 = ?",
  2306. "options": [1, 2, 3, 4],
  2307. "answer": 4,
  2308. },
  2309. },
  2310. },
  2311. }
  2312. )