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