Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

2681 рядки
98 KiB

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