Add files using upload-large-folder tool
Browse filesFiles changed (14)
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/errors.pyAdded+34
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/file_proxy.pyAdded+57
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/filesize.pyAdded+88
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/highlighter.pyAdded+232
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/json.pyAdded+139
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/jupyter.pyAdded+101
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/layout.pyAdded+442
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/live.pyAdded+404
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/live_render.pyAdded+116
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/logging.pyAdded+305
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/markdown.pyAdded+793
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/markup.pyAdded+251
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/measure.pyAdded+151
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/padding.pyAdded+141
12345678910111213141516171819202122232425262728293031323334class ConsoleError(Exception): """An error in console operation."""
class StyleError(Exception): """An error in styles."""
class StyleSyntaxError(ConsoleError): """Style was badly formatted."""
class MissingStyle(StyleError): """No such style."""
class StyleStackError(ConsoleError): """Style stack is invalid."""
class NotRenderableError(ConsoleError): """Object is not renderable."""
class MarkupError(ConsoleError): """Markup was badly formatted."""
class LiveError(ConsoleError): """Error related to Live display."""
class NoAltScreen(ConsoleError): """Alt screen mode was required."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import iofrom typing import IO, TYPE_CHECKING, Any, List
from .ansi import AnsiDecoderfrom .text import Text
if TYPE_CHECKING: from .console import Console
class FileProxy(io.TextIOBase): """Wraps a file (e.g. sys.stdout) and redirects writes to a console."""
def __init__(self, console: "Console", file: IO[str]) -> None: self.__console = console self.__file = file self.__buffer: List[str] = [] self.__ansi_decoder = AnsiDecoder()
@property def rich_proxied_file(self) -> IO[str]: """Get proxied file.""" return self.__file
def __getattr__(self, name: str) -> Any: return getattr(self.__file, name)
def write(self, text: str) -> int: if not isinstance(text, str): raise TypeError(f"write() argument must be str, not {type(text).__name__}") buffer = self.__buffer lines: List[str] = [] while text: line, new_line, text = text.partition("\n") if new_line: lines.append("".join(buffer) + line) buffer.clear() else: buffer.append(line) break if lines: console = self.__console with console: output = Text("\n").join( self.__ansi_decoder.decode_line(line) for line in lines ) console.print(output) return len(text)
def flush(self) -> None: output = "".join(self.__buffer) if output: self.__console.print(output) del self.__buffer[:]
def fileno(self) -> int: return self.__file.fileno()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2
The functions declared in this module should cover the differentuse cases needed to generate a string representation of a file sizeusing several different units. Since there are many standards regardingfile size units, three different functions have been implemented.
See Also: * `Wikipedia: Binary prefix <https://en.wikipedia.org/wiki/Binary_prefix>`_
"""
__all__ = ["decimal"]
from typing import Iterable, List, Optional, Tuple
def _to_str( size: int, suffixes: Iterable[str], base: int, *, precision: Optional[int] = 1, separator: Optional[str] = " ",) -> str: if size == 1: return "1 byte" elif size < base: return f"{size:,} bytes"
for i, suffix in enumerate(suffixes, 2): # noqa: B007 unit = base**i if size < unit: break return "{:,.{precision}f}{separator}{}".format( (base * size / unit), suffix, precision=precision, separator=separator, )
def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]: """Pick a suffix and base for the given size.""" for i, suffix in enumerate(suffixes): unit = base**i if size < unit * base: break return unit, suffix
def decimal( size: int, *, precision: Optional[int] = 1, separator: Optional[str] = " ",) -> str: """Convert a filesize in to a string (powers of 1000, SI prefixes).
In this convention, ``1000 B = 1 kB``.
This is typically the format used to advertise the storage capacity of USB flash drives and the like (*256 MB* meaning actually a storage capacity of more than *256 000 000 B*), or used by **Mac OS X** since v10.6 to report file sizes.
Arguments: int (size): A file size. int (precision): The number of decimal places to include (default = 1). str (separator): The string to separate the value from the units (default = " ").
Returns: `str`: A string containing a abbreviated file size and units.
Example: >>> filesize.decimal(30000) '30.0 kB' >>> filesize.decimal(30000, precision=2, separator="") '30.00kB'
""" return _to_str( size, ("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"), 1000, precision=precision, separator=separator, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232import refrom abc import ABC, abstractmethodfrom typing import ClassVar, Sequence, Union
from .text import Span, Text
def _combine_regex(*regexes: str) -> str: """Combine a number of regexes in to a single regex.
Returns: str: New regex with all regexes ORed together. """ return "|".join(regexes)
class Highlighter(ABC): """Abstract base class for highlighters."""
def __call__(self, text: Union[str, Text]) -> Text: """Highlight a str or Text instance.
Args: text (Union[str, ~Text]): Text to highlight.
Raises: TypeError: If not called with text or str.
Returns: Text: A test instance with highlighting applied. """ if isinstance(text, str): highlight_text = Text(text) elif isinstance(text, Text): highlight_text = text.copy() else: raise TypeError(f"str or Text instance required, not {text!r}") self.highlight(highlight_text) return highlight_text
@abstractmethod def highlight(self, text: Text) -> None: """Apply highlighting in place to text.
Args: text (~Text): A text object highlight. """
class NullHighlighter(Highlighter): """A highlighter object that doesn't highlight.
May be used to disable highlighting entirely.
"""
def highlight(self, text: Text) -> None: """Nothing to do"""
class RegexHighlighter(Highlighter): """Applies highlighting from a list of regular expressions."""
highlights: ClassVar[Sequence[str]] = [] base_style: ClassVar[str] = ""
def highlight(self, text: Text) -> None: """Highlight :class:`rich.text.Text` using regular expressions.
Args: text (~Text): Text to highlighted.
"""
highlight_regex = text.highlight_regex for re_highlight in self.highlights: highlight_regex(re_highlight, style_prefix=self.base_style)
class ReprHighlighter(RegexHighlighter): """Highlights the text typically produced from ``__repr__`` methods."""
base_style = "repr." highlights: ClassVar[Sequence[str]] = [ r"(?P<tag_start><)(?P<tag_name>[-\w.:|]*)(?P<tag_contents>[\w\W]*)(?P<tag_end>>)", r'(?P<attrib_name>[\w_]{1,50})=(?P<attrib_value>"?[\w_]+"?)?', r"(?P<brace>[][{}()])", _combine_regex( r"(?P<ipv4>[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})", r"(?P<ipv6>([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})", r"(?P<eui64>(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){3}[0-9A-Fa-f]{4})", r"(?P<eui48>(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})", r"(?P<uuid>[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})", r"(?P<call>[\w.]*?)\(", r"\b(?P<bool_true>True)\b|\b(?P<bool_false>False)\b|\b(?P<none>None)\b", r"(?P<ellipsis>\.\.\.)", r"(?P<number_complex>(?<!\w)(?:\-?[0-9]+\.?[0-9]*(?:e[-+]?\d+?)?)(?:[-+](?:[0-9]+\.?[0-9]*(?:e[-+]?\d+)?))?j)", r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[-+]?\d+?)?\b|0x[0-9a-fA-F]*)", r"(?P<path>\B(/[-\w._+]+)*\/)(?P<filename>[-\w._+]*)?", r"(?<![\\\w])(?P<str>b?'''.*?(?<!\\)'''|b?'.*?(?<!\\)'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")", r"(?P<url>(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#~@]*)", ), ]
class JSONHighlighter(RegexHighlighter): """Highlights JSON"""
# Captures the start and end of JSON strings, handling escaped quotes JSON_STR = r"(?<![\\\w])(?P<str>b?\".*?(?<!\\)\")" JSON_WHITESPACE = {" ", "\n", "\r", "\t"}
base_style: ClassVar[str] = "json." highlights: ClassVar[Sequence[str]] = [ _combine_regex( r"(?P<brace>[\{\[\(\)\]\}])", r"\b(?P<bool_true>true)\b|\b(?P<bool_false>false)\b|\b(?P<null>null)\b", r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[\-\+]?\d+?)?\b|0x[0-9a-fA-F]*)", JSON_STR, ), ]
def highlight(self, text: Text) -> None: super().highlight(text)
# Additional work to handle highlighting JSON keys plain = text.plain append = text.spans.append whitespace = self.JSON_WHITESPACE for match in re.finditer(self.JSON_STR, plain): start, end = match.span() cursor = end while cursor < len(plain): char = plain[cursor] cursor += 1 if char == ":": append(Span(start, end, "json.key")) elif char in whitespace: continue break
class ISO8601Highlighter(RegexHighlighter): """Highlights the ISO8601 date time strings. Regex reference: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html """
base_style: ClassVar[str] = "iso8601." highlights: ClassVar[Sequence[str]] = [ # # Dates # # Calendar month (e.g. 2008-08). The hyphen is required r"^(?P<year>[0-9]{4})-(?P<month>1[0-2]|0[1-9])$", # Calendar date w/o hyphens (e.g. 20080830) r"^(?P<date>(?P<year>[0-9]{4})(?P<month>1[0-2]|0[1-9])(?P<day>3[01]|0[1-9]|[12][0-9]))$", # Ordinal date (e.g. 2008-243). The hyphen is optional r"^(?P<date>(?P<year>[0-9]{4})-?(?P<day>36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]))$", # # Weeks # # Week of the year (e.g., 2008-W35). The hyphen is optional r"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9]))$", # Week date (e.g., 2008-W35-6). The hyphens are optional r"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9])-?(?P<day>[1-7]))$", # # Times # # Hours and minutes (e.g., 17:21). The colon is optional r"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):?(?P<minute>[0-5][0-9]))$", # Hours, minutes, and seconds w/o colons (e.g., 172159) r"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))$", # Time zone designator (e.g., Z, +07 or +07:00). The colons and the minutes are optional r"^(?P<timezone>(Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?))$", # Hours, minutes, and seconds with time zone designator (e.g., 17:21:59+07:00). # All the colons are optional. The minutes in the time zone designator are also optional r"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?)$", # # Date and Time # # Calendar date with hours, minutes, and seconds (e.g., 2008-08-30 17:21:59 or 20080830 172159). # A space is required between the date and the time. The hyphens and colons are optional. # This regex matches dates and times that specify some hyphens or colons but omit others. # This does not follow ISO 8601 r"^(?P<date>(?P<year>[0-9]{4})(?P<hyphen>-)?(?P<month>1[0-2]|0[1-9])(?(hyphen)-)(?P<day>3[01]|0[1-9]|[12][0-9])) (?P<time>(?P<hour>2[0-3]|[01][0-9])(?(hyphen):)(?P<minute>[0-5][0-9])(?(hyphen):)(?P<second>[0-5][0-9]))$", # # XML Schema dates and times # # Date, with optional time zone (e.g., 2008-08-30 or 2008-08-30+07:00). # Hyphens are required. This is the XML Schema 'date' type r"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$", # Time, with optional fractional seconds and time zone (e.g., 01:45:36 or 01:45:36.123+07:00). # There is no limit on the number of digits for the fractional seconds. This is the XML Schema 'time' type r"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<frac>\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$", # Date and time, with optional fractional seconds and time zone (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z). # This is the XML Schema 'dateTime' type r"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))T(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<ms>\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$", ]
if __name__ == "__main__": # pragma: no cover from .console import Console
console = Console() console.print("[bold green]hello world![/bold green]") console.print("'[bold green]hello world![/bold green]'")
console.print(" /foo") console.print("/foo/") console.print("/foo/bar") console.print("foo/bar/baz")
console.print("/foo/bar/baz?foo=bar+egg&egg=baz") console.print("/foo/bar/baz/") console.print("/foo/bar/baz/egg") console.print("/foo/bar/baz/egg.py") console.print("/foo/bar/baz/egg.py word") console.print(" /foo/bar/baz/egg.py word") console.print("foo /foo/bar/baz/egg.py word") console.print("foo /foo/bar/ba._++z/egg+.py word") console.print("https://example.org?foo=bar#header")
console.print(1234567.34) console.print(1 / 2) console.print(-1 / 123123123123)
console.print( "127.0.1.1 bar 192.168.1.4 2001:0db8:85a3:0000:0000:8a2e:0370:7334 foo" ) import json
console.print_json(json.dumps(obj={"name": "apple", "count": 1}), indent=None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139from pathlib import Pathfrom json import loads, dumpsfrom typing import Any, Callable, Optional, Union
from .text import Textfrom .highlighter import JSONHighlighter, NullHighlighter
class JSON: """A renderable which pretty prints JSON.
Args: json (str): JSON encoded data. indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2. highlight (bool, optional): Enable highlighting. Defaults to True. skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. check_circular (bool, optional): Check for circular references. Defaults to True. allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. default (Callable, optional): A callable that converts values that can not be encoded in to something that can be JSON encoded. Defaults to None. sort_keys (bool, optional): Sort dictionary keys. Defaults to False. """
def __init__( self, json: str, indent: Union[None, int, str] = 2, highlight: bool = True, skip_keys: bool = False, ensure_ascii: bool = False, check_circular: bool = True, allow_nan: bool = True, default: Optional[Callable[[Any], Any]] = None, sort_keys: bool = False, ) -> None: data = loads(json) json = dumps( data, indent=indent, skipkeys=skip_keys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, default=default, sort_keys=sort_keys, ) highlighter = JSONHighlighter() if highlight else NullHighlighter() self.text = highlighter(json) self.text.no_wrap = True self.text.overflow = None
@classmethod def from_data( cls, data: Any, indent: Union[None, int, str] = 2, highlight: bool = True, skip_keys: bool = False, ensure_ascii: bool = False, check_circular: bool = True, allow_nan: bool = True, default: Optional[Callable[[Any], Any]] = None, sort_keys: bool = False, ) -> "JSON": """Encodes a JSON object from arbitrary data.
Args: data (Any): An object that may be encoded in to JSON indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2. highlight (bool, optional): Enable highlighting. Defaults to True. default (Callable, optional): Optional callable which will be called for objects that cannot be serialized. Defaults to None. skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. check_circular (bool, optional): Check for circular references. Defaults to True. allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. default (Callable, optional): A callable that converts values that can not be encoded in to something that can be JSON encoded. Defaults to None. sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
Returns: JSON: New JSON object from the given data. """ json_instance: "JSON" = cls.__new__(cls) json = dumps( data, indent=indent, skipkeys=skip_keys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, default=default, sort_keys=sort_keys, ) highlighter = JSONHighlighter() if highlight else NullHighlighter() json_instance.text = highlighter(json) json_instance.text.no_wrap = True json_instance.text.overflow = None return json_instance
def __rich__(self) -> Text: return self.text
if __name__ == "__main__": import argparse import sys
parser = argparse.ArgumentParser(description="Pretty print json") parser.add_argument( "path", metavar="PATH", help="path to file, or - for stdin", ) parser.add_argument( "-i", "--indent", metavar="SPACES", type=int, help="Number of spaces in an indent", default=2, ) args = parser.parse_args()
from rich.console import Console
console = Console() error_console = Console(stderr=True)
try: if args.path == "-": json_data = sys.stdin.read() else: json_data = Path(args.path).read_text() except Exception as error: error_console.print(f"Unable to read {args.path!r}; {error}") sys.exit(-1)
console.print(JSON(json_data, indent=args.indent), soft_wrap=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence
if TYPE_CHECKING: from rich.console import ConsoleRenderable
from . import get_consolefrom .segment import Segmentfrom .terminal_theme import DEFAULT_TERMINAL_THEME
if TYPE_CHECKING: from rich.console import ConsoleRenderable
JUPYTER_HTML_FORMAT = """\<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre>"""
class JupyterRenderable: """A shim to write html to Jupyter notebook."""
def __init__(self, html: str, text: str) -> None: self.html = html self.text = text
def _repr_mimebundle_( self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any ) -> Dict[str, str]: data = {"text/plain": self.text, "text/html": self.html} if include: data = {k: v for (k, v) in data.items() if k in include} if exclude: data = {k: v for (k, v) in data.items() if k not in exclude} return data
class JupyterMixin: """Add to an Rich renderable to make it render in Jupyter notebook."""
__slots__ = ()
def _repr_mimebundle_( self: "ConsoleRenderable", include: Sequence[str], exclude: Sequence[str], **kwargs: Any, ) -> Dict[str, str]: console = get_console() segments = list(console.render(self, console.options)) html = _render_segments(segments) text = console._render_buffer(segments) data = {"text/plain": text, "text/html": html} if include: data = {k: v for (k, v) in data.items() if k in include} if exclude: data = {k: v for (k, v) in data.items() if k not in exclude} return data
def _render_segments(segments: Iterable[Segment]) -> str: def escape(text: str) -> str: """Escape html.""" return text.replace("&", "&").replace("<", "<").replace(">", ">")
fragments: List[str] = [] append_fragment = fragments.append theme = DEFAULT_TERMINAL_THEME for text, style, control in Segment.simplify(segments): if control: continue text = escape(text) if style: rule = style.get_html_style(theme) text = f'<span style="{rule}">{text}</span>' if rule else text if style.link: text = f'<a href="{style.link}" target="_blank">{text}</a>' append_fragment(text)
code = "".join(fragments) html = JUPYTER_HTML_FORMAT.format(code=code)
return html
def display(segments: Iterable[Segment], text: str) -> None: """Render segments to Jupyter.""" html = _render_segments(segments) jupyter_renderable = JupyterRenderable(html, text) try: from IPython.display import display as ipython_display
ipython_display(jupyter_renderable) except ModuleNotFoundError: # Handle the case where the Console has force_jupyter=True, # but IPython is not installed. pass
def print(*args: Any, **kwargs: Any) -> None: """Proxy for Console print.""" console = get_console() return console.print(*args, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442from abc import ABC, abstractmethodfrom itertools import islicefrom operator import itemgetterfrom threading import RLockfrom typing import ( TYPE_CHECKING, Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple, Union,)
from ._ratio import ratio_resolvefrom .align import Alignfrom .console import Console, ConsoleOptions, RenderableType, RenderResultfrom .highlighter import ReprHighlighterfrom .panel import Panelfrom .pretty import Prettyfrom .region import Regionfrom .repr import Result, rich_reprfrom .segment import Segmentfrom .style import StyleType
if TYPE_CHECKING: from rich.tree import Tree
class LayoutRender(NamedTuple): """An individual layout render."""
region: Region render: List[List[Segment]]
RegionMap = Dict["Layout", Region]RenderMap = Dict["Layout", LayoutRender]
class LayoutError(Exception): """Layout related error."""
class NoSplitter(LayoutError): """Requested splitter does not exist."""
class _Placeholder: """An internal renderable used as a Layout placeholder."""
highlighter = ReprHighlighter()
def __init__(self, layout: "Layout", style: StyleType = "") -> None: self.layout = layout self.style = style
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: width = options.max_width height = options.height or options.size.height layout = self.layout title = ( f"{layout.name!r} ({width} x {height})" if layout.name else f"({width} x {height})" ) yield Panel( Align.center(Pretty(layout), vertical="middle"), style=self.style, title=self.highlighter(title), border_style="blue", height=height, )
class Splitter(ABC): """Base class for a splitter."""
name: str = ""
@abstractmethod def get_tree_icon(self) -> str: """Get the icon (emoji) used in layout.tree"""
@abstractmethod def divide( self, children: Sequence["Layout"], region: Region ) -> Iterable[Tuple["Layout", Region]]: """Divide a region amongst several child layouts.
Args: children (Sequence(Layout)): A number of child layouts. region (Region): A rectangular region to divide. """
class RowSplitter(Splitter): """Split a layout region in to rows."""
name = "row"
def get_tree_icon(self) -> str: return "[layout.tree.row]⬌"
def divide( self, children: Sequence["Layout"], region: Region ) -> Iterable[Tuple["Layout", Region]]: x, y, width, height = region render_widths = ratio_resolve(width, children) offset = 0 _Region = Region for child, child_width in zip(children, render_widths): yield child, _Region(x + offset, y, child_width, height) offset += child_width
class ColumnSplitter(Splitter): """Split a layout region in to columns."""
name = "column"
def get_tree_icon(self) -> str: return "[layout.tree.column]⬍"
def divide( self, children: Sequence["Layout"], region: Region ) -> Iterable[Tuple["Layout", Region]]: x, y, width, height = region render_heights = ratio_resolve(height, children) offset = 0 _Region = Region for child, child_height in zip(children, render_heights): yield child, _Region(x, y + offset, width, child_height) offset += child_height
@rich_reprclass Layout: """A renderable to divide a fixed height in to rows or columns.
Args: renderable (RenderableType, optional): Renderable content, or None for placeholder. Defaults to None. name (str, optional): Optional identifier for Layout. Defaults to None. size (int, optional): Optional fixed size of layout. Defaults to None. minimum_size (int, optional): Minimum size of layout. Defaults to 1. ratio (int, optional): Optional ratio for flexible layout. Defaults to 1. visible (bool, optional): Visibility of layout. Defaults to True. """
splitters = {"row": RowSplitter, "column": ColumnSplitter}
def __init__( self, renderable: Optional[RenderableType] = None, *, name: Optional[str] = None, size: Optional[int] = None, minimum_size: int = 1, ratio: int = 1, visible: bool = True, ) -> None: self._renderable = renderable or _Placeholder(self) self.size = size self.minimum_size = minimum_size self.ratio = ratio self.name = name self.visible = visible self.splitter: Splitter = self.splitters["column"]() self._children: List[Layout] = [] self._render_map: RenderMap = {} self._lock = RLock()
def __rich_repr__(self) -> Result: yield "name", self.name, None yield "size", self.size, None yield "minimum_size", self.minimum_size, 1 yield "ratio", self.ratio, 1
@property def renderable(self) -> RenderableType: """Layout renderable.""" return self if self._children else self._renderable
@property def children(self) -> List["Layout"]: """Gets (visible) layout children.""" return [child for child in self._children if child.visible]
@property def map(self) -> RenderMap: """Get a map of the last render.""" return self._render_map
def get(self, name: str) -> Optional["Layout"]: """Get a named layout, or None if it doesn't exist.
Args: name (str): Name of layout.
Returns: Optional[Layout]: Layout instance or None if no layout was found. """ if self.name == name: return self else: for child in self._children: named_layout = child.get(name) if named_layout is not None: return named_layout return None
def __getitem__(self, name: str) -> "Layout": layout = self.get(name) if layout is None: raise KeyError(f"No layout with name {name!r}") return layout
@property def tree(self) -> "Tree": """Get a tree renderable to show layout structure.""" from rich.styled import Styled from rich.table import Table from rich.tree import Tree
def summary(layout: "Layout") -> Table: icon = layout.splitter.get_tree_icon()
table = Table.grid(padding=(0, 1, 0, 0))
text: RenderableType = ( Pretty(layout) if layout.visible else Styled(Pretty(layout), "dim") ) table.add_row(icon, text) _summary = table return _summary
layout = self tree = Tree( summary(layout), guide_style=f"layout.tree.{layout.splitter.name}", highlight=True, )
def recurse(tree: "Tree", layout: "Layout") -> None: for child in layout._children: recurse( tree.add( summary(child), guide_style=f"layout.tree.{child.splitter.name}", ), child, )
recurse(tree, self) return tree
def split( self, *layouts: Union["Layout", RenderableType], splitter: Union[Splitter, str] = "column", ) -> None: """Split the layout in to multiple sub-layouts.
Args: *layouts (Layout): Positional arguments should be (sub) Layout instances. splitter (Union[Splitter, str]): Splitter instance or name of splitter. """ _layouts = [ layout if isinstance(layout, Layout) else Layout(layout) for layout in layouts ] try: self.splitter = ( splitter if isinstance(splitter, Splitter) else self.splitters[splitter]() ) except KeyError: raise NoSplitter(f"No splitter called {splitter!r}") self._children[:] = _layouts
def add_split(self, *layouts: Union["Layout", RenderableType]) -> None: """Add a new layout(s) to existing split.
Args: *layouts (Union[Layout, RenderableType]): Positional arguments should be renderables or (sub) Layout instances.
""" _layouts = ( layout if isinstance(layout, Layout) else Layout(layout) for layout in layouts ) self._children.extend(_layouts)
def split_row(self, *layouts: Union["Layout", RenderableType]) -> None: """Split the layout in to a row (layouts side by side).
Args: *layouts (Layout): Positional arguments should be (sub) Layout instances. """ self.split(*layouts, splitter="row")
def split_column(self, *layouts: Union["Layout", RenderableType]) -> None: """Split the layout in to a column (layouts stacked on top of each other).
Args: *layouts (Layout): Positional arguments should be (sub) Layout instances. """ self.split(*layouts, splitter="column")
def unsplit(self) -> None: """Reset splits to initial state.""" del self._children[:]
def update(self, renderable: RenderableType) -> None: """Update renderable.
Args: renderable (RenderableType): New renderable object. """ with self._lock: self._renderable = renderable
def refresh_screen(self, console: "Console", layout_name: str) -> None: """Refresh a sub-layout.
Args: console (Console): Console instance where Layout is to be rendered. layout_name (str): Name of layout. """ with self._lock: layout = self[layout_name] region, _lines = self._render_map[layout] (x, y, width, height) = region lines = console.render_lines( layout, console.options.update_dimensions(width, height) ) self._render_map[layout] = LayoutRender(region, lines) console.update_screen_lines(lines, x, y)
def _make_region_map(self, width: int, height: int) -> RegionMap: """Create a dict that maps layout on to Region.""" stack: List[Tuple[Layout, Region]] = [(self, Region(0, 0, width, height))] push = stack.append pop = stack.pop layout_regions: List[Tuple[Layout, Region]] = [] append_layout_region = layout_regions.append while stack: append_layout_region(pop()) layout, region = layout_regions[-1] children = layout.children if children: for child_and_region in layout.splitter.divide(children, region): push(child_and_region)
region_map = { layout: region for layout, region in sorted(layout_regions, key=itemgetter(1)) } return region_map
def render(self, console: Console, options: ConsoleOptions) -> RenderMap: """Render the sub_layouts.
Args: console (Console): Console instance. options (ConsoleOptions): Console options.
Returns: RenderMap: A dict that maps Layout on to a tuple of Region, lines """ render_width = options.max_width render_height = options.height or console.height region_map = self._make_region_map(render_width, render_height) layout_regions = [ (layout, region) for layout, region in region_map.items() if not layout.children ] render_map: Dict["Layout", "LayoutRender"] = {} render_lines = console.render_lines update_dimensions = options.update_dimensions
for layout, region in layout_regions: lines = render_lines( layout.renderable, update_dimensions(region.width, region.height) ) render_map[layout] = LayoutRender(region, lines) return render_map
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: with self._lock: width = options.max_width or console.width height = options.height or console.height render_map = self.render(console, options.update_dimensions(width, height)) self._render_map = render_map layout_lines: List[List[Segment]] = [[] for _ in range(height)] _islice = islice for region, lines in render_map.values(): _x, y, _layout_width, layout_height = region for row, line in zip( _islice(layout_lines, y, y + layout_height), lines ): row.extend(line)
new_line = Segment.line() for layout_row in layout_lines: yield from layout_row yield new_line
if __name__ == "__main__": from rich.console import Console
console = Console() layout = Layout()
layout.split_column( Layout(name="header", size=3), Layout(ratio=1, name="main"), Layout(size=10, name="footer"), )
layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2))
layout["body"].split_row(Layout(name="content", ratio=2), Layout(name="s2"))
layout["s2"].split_column( Layout(name="top"), Layout(name="middle"), Layout(name="bottom") )
layout["side"].split_column(Layout(layout.tree, name="left1"), Layout(name="left2"))
layout["content"].update("foo")
console.print(layout)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404from __future__ import annotations
import sysfrom threading import Event, RLock, Threadfrom types import TracebackTypefrom typing import IO, TYPE_CHECKING, Any, Callable, List, Optional, TextIO, Type, cast
from . import get_consolefrom .console import Console, ConsoleRenderable, Group, RenderableType, RenderHookfrom .control import Controlfrom .file_proxy import FileProxyfrom .jupyter import JupyterMixinfrom .live_render import LiveRender, VerticalOverflowMethodfrom .screen import Screenfrom .text import Text
if TYPE_CHECKING: # Can be replaced with `from typing import Self` in Python 3.11+ from typing_extensions import Self # pragma: no cover
class _RefreshThread(Thread): """A thread that calls refresh() at regular intervals."""
def __init__(self, live: "Live", refresh_per_second: float) -> None: self.live = live self.refresh_per_second = refresh_per_second self.done = Event() super().__init__(daemon=True)
def stop(self) -> None: self.done.set()
def run(self) -> None: while not self.done.wait(1 / self.refresh_per_second): with self.live._lock: if not self.done.is_set(): self.live.refresh()
class Live(JupyterMixin, RenderHook): """Renders an auto-updating live display of any given renderable.
Args: renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing. console (Console, optional): Optional Console instance. Defaults to an internal Console instance writing to stdout. screen (bool, optional): Enable alternate screen mode. Defaults to False. auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()` or `update()` with refresh flag. Defaults to True refresh_per_second (float, optional): Number of times per second to refresh the live display. Defaults to 4. transient (bool, optional): Clear the renderable on exit (has no effect when screen=True). Defaults to False. redirect_stdout (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True. redirect_stderr (bool, optional): Enable redirection of stderr. Defaults to True. vertical_overflow (VerticalOverflowMethod, optional): How to handle renderable when it is too tall for the console. Defaults to "ellipsis". get_renderable (Callable[[], RenderableType], optional): Optional callable to get renderable. Defaults to None. """
def __init__( self, renderable: Optional[RenderableType] = None, *, console: Optional[Console] = None, screen: bool = False, auto_refresh: bool = True, refresh_per_second: float = 4, transient: bool = False, redirect_stdout: bool = True, redirect_stderr: bool = True, vertical_overflow: VerticalOverflowMethod = "ellipsis", get_renderable: Optional[Callable[[], RenderableType]] = None, ) -> None: assert refresh_per_second > 0, "refresh_per_second must be > 0" self._renderable = renderable self.console = console if console is not None else get_console() self._screen = screen self._alt_screen = False
self._redirect_stdout = redirect_stdout self._redirect_stderr = redirect_stderr self._restore_stdout: Optional[IO[str]] = None self._restore_stderr: Optional[IO[str]] = None
self._lock = RLock() self.ipy_widget: Optional[Any] = None self.auto_refresh = auto_refresh self._started: bool = False self.transient = True if screen else transient
self._refresh_thread: Optional[_RefreshThread] = None self.refresh_per_second = refresh_per_second
self.vertical_overflow = vertical_overflow self._get_renderable = get_renderable self._live_render = LiveRender( self.get_renderable(), vertical_overflow=vertical_overflow ) self._nested = False
@property def is_started(self) -> bool: """Check if live display has been started.""" return self._started
def get_renderable(self) -> RenderableType: renderable = ( self._get_renderable() if self._get_renderable is not None else self._renderable ) return renderable or ""
def start(self, refresh: bool = False) -> None: """Start live rendering display.
Args: refresh (bool, optional): Also refresh. Defaults to False. """ with self._lock: if self._started: return self._started = True
if not self.console.set_live(self): self._nested = True return
if self._screen: self._alt_screen = self.console.set_alt_screen(True) self.console.show_cursor(False) self._enable_redirect_io() self.console.push_render_hook(self) if refresh: try: self.refresh() except Exception: # If refresh fails, we want to stop the redirection of sys.stderr, # so the error stacktrace is properly displayed in the terminal. # (or, if the code that calls Rich captures the exception and wants to display something, # let this be displayed in the terminal). self.stop() raise if self.auto_refresh: self._refresh_thread = _RefreshThread(self, self.refresh_per_second) self._refresh_thread.start()
def stop(self) -> None: """Stop live rendering display.""" with self._lock: if not self._started: return self._started = False self.console.clear_live() if self._nested: if not self.transient: self.console.print(self.renderable) return
if self.auto_refresh and self._refresh_thread is not None: self._refresh_thread.stop() self._refresh_thread = None # allow it to fully render on the last even if overflow self.vertical_overflow = "visible" with self.console: try: if not self._alt_screen and not self.console.is_jupyter: self.refresh() finally: self._disable_redirect_io() self.console.pop_render_hook() if ( not self._alt_screen and self.console.is_terminal and self._live_render.last_render_height ): self.console.line() self.console.show_cursor(True) if self._alt_screen: self.console.set_alt_screen(False) if self.transient and not self._alt_screen: self.console.control(self._live_render.restore_cursor()) if self.ipy_widget is not None and self.transient: self.ipy_widget.close() # pragma: no cover
def __enter__(self) -> Self: self.start(refresh=self._renderable is not None) return self
def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.stop()
def _enable_redirect_io(self) -> None: """Enable redirecting of stdout / stderr.""" if self.console.is_terminal or self.console.is_jupyter: if self._redirect_stdout and not isinstance(sys.stdout, FileProxy): self._restore_stdout = sys.stdout sys.stdout = cast("TextIO", FileProxy(self.console, sys.stdout)) if self._redirect_stderr and not isinstance(sys.stderr, FileProxy): self._restore_stderr = sys.stderr sys.stderr = cast("TextIO", FileProxy(self.console, sys.stderr))
def _disable_redirect_io(self) -> None: """Disable redirecting of stdout / stderr.""" if self._restore_stdout: sys.stdout = cast("TextIO", self._restore_stdout) self._restore_stdout = None if self._restore_stderr: sys.stderr = cast("TextIO", self._restore_stderr) self._restore_stderr = None
@property def renderable(self) -> RenderableType: """Get the renderable that is being displayed
Returns: RenderableType: Displayed renderable. """ live_stack = self.console._live_stack renderable: RenderableType if live_stack and self is live_stack[0]: # The first Live instance will render everything in the Live stack renderable = Group(*[live.get_renderable() for live in live_stack]) else: renderable = self.get_renderable() return Screen(renderable) if self._alt_screen else renderable
def update(self, renderable: RenderableType, *, refresh: bool = False) -> None: """Update the renderable that is being displayed
Args: renderable (RenderableType): New renderable to use. refresh (bool, optional): Refresh the display. Defaults to False. """ if isinstance(renderable, str): renderable = self.console.render_str(renderable) with self._lock: self._renderable = renderable if refresh: self.refresh()
def refresh(self) -> None: """Update the display of the Live Render.""" with self._lock: self._live_render.set_renderable(self.renderable) if self._nested: if self.console._live_stack: self.console._live_stack[0].refresh() return
if self.console.is_jupyter: # pragma: no cover try: from IPython.display import display from ipywidgets import Output except ImportError: import warnings
warnings.warn('install "ipywidgets" for Jupyter support') else: if self.ipy_widget is None: self.ipy_widget = Output() display(self.ipy_widget)
with self.ipy_widget: self.ipy_widget.clear_output(wait=True) self.console.print(self._live_render.renderable) elif self.console.is_terminal and not self.console.is_dumb_terminal: with self.console: self.console.print(Control()) elif ( not self._started and not self.transient ): # if it is finished allow files or dumb-terminals to see final result with self.console: self.console.print(Control())
def process_renderables( self, renderables: List[ConsoleRenderable] ) -> List[ConsoleRenderable]: """Process renderables to restore cursor and display progress.""" self._live_render.vertical_overflow = self.vertical_overflow if self.console.is_interactive: # lock needs acquiring as user can modify live_render renderable at any time unlike in Progress. with self._lock: reset = ( Control.home() if self._alt_screen else self._live_render.position_cursor() ) renderables = [reset, *renderables, self._live_render] elif ( not self._started and not self.transient ): # if it is finished render the final output for files or dumb_terminals renderables = [*renderables, self._live_render]
return renderables
if __name__ == "__main__": # pragma: no cover import random import time from itertools import cycle from typing import Dict, List, Tuple
from .align import Align from .console import Console from .live import Live as Live from .panel import Panel from .rule import Rule from .syntax import Syntax from .table import Table
console = Console()
syntax = Syntax( '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: """Iterate and generate a tuple with a flag for last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return for value in iter_values: yield False, previous_value previous_value = value yield True, previous_value''', "python", line_numbers=True, )
table = Table("foo", "bar", "baz") table.add_row("1", "2", "3")
progress_renderables = [ "You can make the terminal shorter and taller to see the live table hide" "Text may be printed while the progress bars are rendering.", Panel("In fact, [i]any[/i] renderable will work"), "Such as [magenta]tables[/]...", table, "Pretty printed structures...", {"type": "example", "text": "Pretty printed"}, "Syntax...", syntax, Rule("Give it a try!"), ]
examples = cycle(progress_renderables)
exchanges = [ "SGD", "MYR", "EUR", "USD", "AUD", "JPY", "CNH", "HKD", "CAD", "INR", "DKK", "GBP", "RUB", "NZD", "MXN", "IDR", "TWD", "THB", "VND", ] with Live(console=console) as live_table: exchange_rate_dict: Dict[Tuple[str, str], float] = {}
for index in range(100): select_exchange = exchanges[index % len(exchanges)]
for exchange in exchanges: if exchange == select_exchange: continue time.sleep(0.4) if random.randint(0, 10) < 1: console.log(next(examples)) exchange_rate_dict[(select_exchange, exchange)] = 200 / ( (random.random() * 320) + 1 ) if len(exchange_rate_dict) > len(exchanges) - 1: exchange_rate_dict.pop(list(exchange_rate_dict.keys())[0]) table = Table(title="Exchange Rates")
table.add_column("Source Currency") table.add_column("Destination Currency") table.add_column("Exchange Rate")
for (source, dest), exchange_rate in exchange_rate_dict.items(): table.add_row( source, dest, Text( f"{exchange_rate:.4f}", style="red" if exchange_rate < 1.0 else "green", ), )
live_table.update(Align.center(table))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116from typing import Literal, Optional, Tuple
from ._loop import loop_lastfrom .console import Console, ConsoleOptions, RenderableType, RenderResultfrom .control import Controlfrom .segment import ControlType, Segmentfrom .style import StyleTypefrom .text import Text
VerticalOverflowMethod = Literal["crop", "ellipsis", "visible"]
class LiveRender: """Creates a renderable that may be updated.
Args: renderable (RenderableType): Any renderable object. style (StyleType, optional): An optional style to apply to the renderable. Defaults to "". """
def __init__( self, renderable: RenderableType, style: StyleType = "", vertical_overflow: VerticalOverflowMethod = "ellipsis", ) -> None: self.renderable = renderable self.style = style self.vertical_overflow = vertical_overflow self._shape: Optional[Tuple[int, int]] = None
@property def last_render_height(self) -> int: """The number of lines in the last render (may be 0 if nothing was rendered).
Returns: Height in lines """ if self._shape is None: return 0 return self._shape[1]
def set_renderable(self, renderable: RenderableType) -> None: """Set a new renderable.
Args: renderable (RenderableType): Any renderable object, including str. """ self.renderable = renderable
def position_cursor(self) -> Control: """Get control codes to move cursor to beginning of live render.
Returns: Control: A control instance that may be printed. """ if self._shape is not None: _, height = self._shape return Control( ControlType.CARRIAGE_RETURN, (ControlType.ERASE_IN_LINE, 2), *( ( (ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2), ) * (height - 1) ) ) return Control()
def restore_cursor(self) -> Control: """Get control codes to clear the render and restore the cursor to its previous position.
Returns: Control: A Control instance that may be printed. """ if self._shape is not None: _, height = self._shape return Control( ControlType.CARRIAGE_RETURN, *((ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2)) * height ) return Control()
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: renderable = self.renderable style = console.get_style(self.style) lines = console.render_lines(renderable, options, style=style, pad=False) shape = Segment.get_shape(lines)
_, height = shape if height > options.size.height: if self.vertical_overflow == "crop": lines = lines[: options.size.height] shape = Segment.get_shape(lines) elif self.vertical_overflow == "ellipsis": lines = lines[: (options.size.height - 1)] overflow_text = Text( "...", overflow="crop", justify="center", end="", style="live.ellipsis", ) lines.append(list(console.render(overflow_text))) shape = Segment.get_shape(lines) self._shape = shape
new_line = Segment.line() for last, line in loop_last(lines): yield from line if not last: yield new_line123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305from __future__ import annotations
import loggingimport osfrom datetime import datetimefrom logging import Handler, LogRecordfrom types import ModuleTypefrom typing import TYPE_CHECKING, ClassVar, Iterable, List, Optional, Type, Union
if TYPE_CHECKING: from ._log_render import FormatTimeCallable from .console import Console, ConsoleRenderable from .highlighter import Highlighter from .traceback import Traceback
from rich._null_file import NullFile
from . import get_consolefrom ._log_render import LogRenderfrom .highlighter import ReprHighlighterfrom .text import Text
class RichHandler(Handler): """A logging handler that renders output with Rich. The time / level / message and file are displayed in columns. The level is color coded, and the message is syntax highlighted.
Note: Be careful when enabling console markup in log messages if you have configured logging for libraries not under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.
Args: level (Union[int, str], optional): Log level. Defaults to logging.NOTSET. console (:class:`~rich.console.Console`, optional): Optional console instance to write logs. Default will use a global console instance writing to stdout. show_time (bool, optional): Show a column for the time. Defaults to True. omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True. show_level (bool, optional): Show a column for the level. Defaults to True. show_path (bool, optional): Show the path to the original log call. Defaults to True. enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True. highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None. markup (bool, optional): Enable console markup in log messages. Defaults to False. rich_tracebacks (bool, optional): Enable rich tracebacks with syntax highlighting and formatting. Defaults to False. tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None. tracebacks_code_width (int, optional): Number of code characters used to render tracebacks, or None for full width. Defaults to 88. tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None. tracebacks_theme (str, optional): Override pygments theme used in traceback. tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True. tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False. tracebacks_suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. tracebacks_max_frames (int, optional): Optional maximum number of frames returned by traceback. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. 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 %X] ". keywords (List[str], optional): List of words to highlight instead of ``RichHandler.KEYWORDS``. """
KEYWORDS: ClassVar[Optional[List[str]]] = [ "GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS", "TRACE", "PATCH", ] HIGHLIGHTER_CLASS: ClassVar[Type[Highlighter]] = ReprHighlighter
def __init__( self, level: Union[int, str] = logging.NOTSET, console: Optional[Console] = None, *, show_time: bool = True, omit_repeated_times: bool = True, show_level: bool = True, show_path: bool = True, enable_link_path: bool = True, highlighter: Optional[Highlighter] = None, markup: bool = False, rich_tracebacks: bool = False, tracebacks_width: Optional[int] = None, tracebacks_code_width: Optional[int] = 88, tracebacks_extra_lines: int = 3, tracebacks_theme: Optional[str] = None, tracebacks_word_wrap: bool = True, tracebacks_show_locals: bool = False, tracebacks_suppress: Iterable[Union[str, ModuleType]] = (), tracebacks_max_frames: int = 100, locals_max_length: int = 10, locals_max_string: int = 80, log_time_format: Union[str, FormatTimeCallable] = "[%x %X]", keywords: Optional[List[str]] = None, ) -> None: super().__init__(level=level) self.console = console or get_console() self.highlighter = highlighter or self.HIGHLIGHTER_CLASS() self._log_render = LogRender( show_time=show_time, show_level=show_level, show_path=show_path, time_format=log_time_format, omit_repeated_times=omit_repeated_times, level_width=None, ) self.enable_link_path = enable_link_path self.markup = markup self.rich_tracebacks = rich_tracebacks self.tracebacks_width = tracebacks_width self.tracebacks_extra_lines = tracebacks_extra_lines self.tracebacks_theme = tracebacks_theme self.tracebacks_word_wrap = tracebacks_word_wrap self.tracebacks_show_locals = tracebacks_show_locals self.tracebacks_suppress = tracebacks_suppress self.tracebacks_max_frames = tracebacks_max_frames self.tracebacks_code_width = tracebacks_code_width self.locals_max_length = locals_max_length self.locals_max_string = locals_max_string self.keywords = keywords
def get_level_text(self, record: LogRecord) -> Text: """Get the level name from the record.
Args: record (LogRecord): LogRecord instance.
Returns: Text: A tuple of the style and level name. """ level_name = record.levelname level_text = Text.styled( level_name.ljust(8), f"logging.level.{level_name.lower()}" ) return level_text
def emit(self, record: LogRecord) -> None: """Invoked by logging.""" message = self.format(record) traceback = None if ( self.rich_tracebacks and record.exc_info and record.exc_info != (None, None, None) ): exc_type, exc_value, exc_traceback = record.exc_info assert exc_type is not None assert exc_value is not None from .traceback import Traceback
traceback = Traceback.from_exception( exc_type, exc_value, exc_traceback, width=self.tracebacks_width, code_width=self.tracebacks_code_width, extra_lines=self.tracebacks_extra_lines, theme=self.tracebacks_theme, word_wrap=self.tracebacks_word_wrap, show_locals=self.tracebacks_show_locals, locals_max_length=self.locals_max_length, locals_max_string=self.locals_max_string, suppress=self.tracebacks_suppress, max_frames=self.tracebacks_max_frames, ) message = record.getMessage() if self.formatter: record.message = record.getMessage() formatter = self.formatter if hasattr(formatter, "usesTime") and formatter.usesTime(): record.asctime = formatter.formatTime(record, formatter.datefmt) message = formatter.formatMessage(record)
message_renderable = self.render_message(record, message) log_renderable = self.render( record=record, traceback=traceback, message_renderable=message_renderable ) if isinstance(self.console.file, NullFile): # Handles pythonw, where stdout/stderr are null, and we return NullFile # instance from Console.file. In this case, we still want to make a log record # even though we won't be writing anything to a file. self.handleError(record) else: try: self.console.print(log_renderable) except Exception: self.handleError(record)
def render_message(self, record: LogRecord, message: str) -> ConsoleRenderable: """Render message text in to Text.
Args: record (LogRecord): logging Record. message (str): String containing log message.
Returns: ConsoleRenderable: Renderable to display log message. """ use_markup = getattr(record, "markup", self.markup) message_text = Text.from_markup(message) if use_markup else Text(message)
highlighter = getattr(record, "highlighter", self.highlighter) if highlighter: message_text = highlighter(message_text)
if self.keywords is None: self.keywords = self.KEYWORDS
if self.keywords: message_text.highlight_words(self.keywords, "logging.keyword")
return message_text
def render( self, *, record: LogRecord, traceback: Optional[Traceback], message_renderable: ConsoleRenderable, ) -> ConsoleRenderable: """Render log for display.
Args: record (LogRecord): logging Record. traceback (Optional[Traceback]): Traceback instance or None for no Traceback. message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents.
Returns: ConsoleRenderable: Renderable to display log. """ path = os.path.basename(record.pathname) level = self.get_level_text(record) time_format = None if self.formatter is None else self.formatter.datefmt log_time = datetime.fromtimestamp(record.created)
log_renderable = self._log_render( self.console, [message_renderable] if not traceback else [message_renderable, traceback], log_time=log_time, time_format=time_format, level=level, path=path, line_no=record.lineno, link_path=record.pathname if self.enable_link_path else None, ) return log_renderable
if __name__ == "__main__": # pragma: no cover from time import sleep
FORMAT = "%(message)s" # FORMAT = "%(asctime)-15s - %(levelname)s - %(message)s" logging.basicConfig( level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)], ) log = logging.getLogger("rich")
log.info("Server starting...") log.info("Listening on http://127.0.0.1:8080") sleep(1)
log.info("GET /index.html 200 1298") log.info("GET /imgs/backgrounds/back1.jpg 200 54386") log.info("GET /css/styles.css 200 54386") log.warning("GET /favicon.ico 404 242") sleep(1)
log.debug( "JSONRPC request\n--> %r\n<-- %r", { "version": "1.1", "method": "confirmFruitPurchase", "params": [["apple", "orange", "mangoes", "pomelo"], 1.123], "id": "194521489", }, {"version": "1.1", "result": True, "error": None, "id": "194521489"}, ) log.debug( "Loading configuration file /adasd/asdasd/qeqwe/qwrqwrqwr/sdgsdgsdg/werwerwer/dfgerert/ertertert/ertetert/werwerwer" ) log.error("Unable to find 'pomelo' in database!") log.info("POST /jsonrpc/ 200 65532") log.info("POST /admin/ 401 42234") log.warning("password was rejected for admin site.")
def divide() -> None: number = 1 divisor = 0 foos = ["foo"] * 100 log.debug("in divide") try: number / divisor except: log.exception("An error of some kind occurred!")
divide() sleep(1) log.critical("Out of memory!") log.info("Server exited with code=-1") log.info("[bold]EXITING...[/bold]", extra=dict(markup=True))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793from __future__ import annotations
import sysfrom dataclasses import dataclassfrom typing import ClassVar, Iterable, get_args
from markdown_it import MarkdownItfrom markdown_it.token import Token
from rich.table import Table
from . import boxfrom ._loop import loop_firstfrom ._stack import Stackfrom .console import Console, ConsoleOptions, JustifyMethod, RenderResultfrom .containers import Renderablesfrom .jupyter import JupyterMixinfrom .rule import Rulefrom .segment import Segmentfrom .style import Style, StyleStackfrom .syntax import Syntaxfrom .text import Text, TextType
class MarkdownElement: new_line: ClassVar[bool] = True
@classmethod def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: """Factory to create markdown element,
Args: markdown (Markdown): The parent Markdown object. token (Token): A node from markdown-it.
Returns: MarkdownElement: A new markdown element """ return cls()
def on_enter(self, context: MarkdownContext) -> None: """Called when the node is entered.
Args: context (MarkdownContext): The markdown context. """
def on_text(self, context: MarkdownContext, text: TextType) -> None: """Called when text is parsed.
Args: context (MarkdownContext): The markdown context. """
def on_leave(self, context: MarkdownContext) -> None: """Called when the parser leaves the element.
Args: context (MarkdownContext): [description] """
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: """Called when a child element is closed.
This method allows a parent element to take over rendering of its children.
Args: context (MarkdownContext): The markdown context. child (MarkdownElement): The child markdown element.
Returns: bool: Return True to render the element, or False to not render the element. """ return True
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: return ()
class UnknownElement(MarkdownElement): """An unknown element.
Hopefully there will be no unknown elements, and we will have a MarkdownElement for everything in the document.
"""
class TextElement(MarkdownElement): """Base class for elements that render text."""
style_name = "none"
def on_enter(self, context: MarkdownContext) -> None: self.style = context.enter_style(self.style_name) self.text = Text(justify="left")
def on_text(self, context: MarkdownContext, text: TextType) -> None: self.text.append(text, context.current_style if isinstance(text, str) else None)
def on_leave(self, context: MarkdownContext) -> None: context.leave_style()
class Paragraph(TextElement): """A Paragraph."""
style_name = "markdown.paragraph" justify: JustifyMethod
@classmethod def create(cls, markdown: Markdown, token: Token) -> Paragraph: return cls(justify=markdown.justify or "left")
def __init__(self, justify: JustifyMethod) -> None: self.justify = justify
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: self.text.justify = self.justify yield self.text
@dataclassclass HeadingFormat: justify: JustifyMethod = "left" style: str = ""
class Heading(TextElement): """A heading."""
LEVEL_ALIGN: ClassVar[dict[str, JustifyMethod]] = { "h1": "center", "h2": "left", "h3": "left", "h4": "left", "h5": "left", "h6": "left", }
@classmethod def create(cls, markdown: Markdown, token: Token) -> Heading: return cls(token.tag)
def on_enter(self, context: MarkdownContext) -> None: self.text = Text() context.enter_style(self.style_name)
def __init__(self, tag: str) -> None: self.tag = tag self.style_name = f"markdown.{tag}" super().__init__()
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: text = self.text.copy() heading_justify = self.LEVEL_ALIGN.get(self.tag, "left") text.justify = heading_justify yield text
class CodeBlock(TextElement): """A code block with syntax highlighting."""
style_name = "markdown.code_block"
@classmethod def create(cls, markdown: Markdown, token: Token) -> CodeBlock: node_info = token.info or "" lexer_name = node_info.partition(" ")[0] return cls(lexer_name or "text", markdown.code_theme)
def __init__(self, lexer_name: str, theme: str) -> None: self.lexer_name = lexer_name self.theme = theme
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: code = str(self.text).rstrip() syntax = Syntax( code, self.lexer_name, theme=self.theme, word_wrap=True, padding=1 ) yield syntax
class BlockQuote(TextElement): """A block quote."""
style_name = "markdown.block_quote"
def __init__(self) -> None: self.elements: Renderables = Renderables()
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: self.elements.append(child) return False
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: render_options = options.update(width=options.max_width - 4) lines = console.render_lines(self.elements, render_options, style=self.style) style = self.style new_line = Segment("\n") padding = Segment("▌ ", style) for line in lines: yield padding yield from line yield new_line
class HorizontalRule(MarkdownElement): """A horizontal rule to divide sections."""
new_line = False
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: style = console.get_style("markdown.hr", default="none") yield Rule(style=style, characters="-") yield Text()
class TableElement(MarkdownElement): """MarkdownElement corresponding to `table_open`."""
def __init__(self) -> None: self.header: TableHeaderElement | None = None self.body: TableBodyElement | None = None
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: if isinstance(child, TableHeaderElement): self.header = child elif isinstance(child, TableBodyElement): self.body = child else: raise RuntimeError("Couldn't process markdown table.") return False
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: table = Table( box=box.SIMPLE, pad_edge=False, style="markdown.table.border", show_edge=True, collapse_padding=True, )
if self.header is not None and self.header.row is not None: for column in self.header.row.cells: heading = column.content.copy() heading.stylize("markdown.table.header") table.add_column(heading)
if self.body is not None: for row in self.body.rows: row_content = [element.content for element in row.cells] table.add_row(*row_content)
yield table
class TableHeaderElement(MarkdownElement): """MarkdownElement corresponding to `thead_open` and `thead_close`."""
def __init__(self) -> None: self.row: TableRowElement | None = None
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, TableRowElement) self.row = child return False
class TableBodyElement(MarkdownElement): """MarkdownElement corresponding to `tbody_open` and `tbody_close`."""
def __init__(self) -> None: self.rows: list[TableRowElement] = []
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, TableRowElement) self.rows.append(child) return False
class TableRowElement(MarkdownElement): """MarkdownElement corresponding to `tr_open` and `tr_close`."""
def __init__(self) -> None: self.cells: list[TableDataElement] = []
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, TableDataElement) self.cells.append(child) return False
class TableDataElement(MarkdownElement): """MarkdownElement corresponding to `td_open` and `td_close` and `th_open` and `th_close`."""
@classmethod def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: style = str(token.attrs.get("style")) or ""
justify: JustifyMethod if "text-align:right" in style: justify = "right" elif "text-align:center" in style: justify = "center" elif "text-align:left" in style: justify = "left" else: justify = "default"
assert justify in get_args(JustifyMethod) return cls(justify=justify)
def __init__(self, justify: JustifyMethod) -> None: self.content: Text = Text("", justify=justify) self.justify = justify
def on_text(self, context: MarkdownContext, text: TextType) -> None: text = Text(text) if isinstance(text, str) else text text.stylize(context.current_style) self.content.append_text(text)
class ListElement(MarkdownElement): """A list element."""
@classmethod def create(cls, markdown: Markdown, token: Token) -> ListElement: return cls(token.type, int(token.attrs.get("start", 1)))
def __init__(self, list_type: str, list_start: int | None) -> None: self.items: list[ListItem] = [] self.list_type = list_type self.list_start = list_start
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: assert isinstance(child, ListItem) self.items.append(child) return False
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: if self.list_type == "bullet_list_open": for item in self.items: yield from item.render_bullet(console, options) else: number = 1 if self.list_start is None else self.list_start last_number = number + len(self.items) for index, item in enumerate(self.items): yield from item.render_number( console, options, number + index, last_number )
class ListItem(TextElement): """An item in a list."""
style_name = "markdown.item"
def __init__(self) -> None: self.elements: Renderables = Renderables()
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool: self.elements.append(child) return False
def render_bullet(self, console: Console, options: ConsoleOptions) -> RenderResult: render_options = options.update(width=options.max_width - 3) lines = console.render_lines(self.elements, render_options, style=self.style) bullet_style = console.get_style("markdown.item.bullet", default="none")
bullet = Segment(" • ", bullet_style) padding = Segment(" " * 3, bullet_style) new_line = Segment("\n") for first, line in loop_first(lines): yield bullet if first else padding yield from line yield new_line
def render_number( self, console: Console, options: ConsoleOptions, number: int, last_number: int ) -> RenderResult: number_width = len(str(last_number)) + 2 render_options = options.update(width=options.max_width - number_width) lines = console.render_lines(self.elements, render_options, style=self.style) number_style = console.get_style("markdown.item.number", default="none")
new_line = Segment("\n") padding = Segment(" " * number_width, number_style) numeral = Segment(f"{number}".rjust(number_width - 1) + " ", number_style) for first, line in loop_first(lines): yield numeral if first else padding yield from line yield new_line
class Link(TextElement): @classmethod def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: url = token.attrs.get("href", "#") return cls(token.content, str(url))
def __init__(self, text: str, href: str): self.text = Text(text) self.href = href
class ImageItem(TextElement): """Renders a placeholder for an image."""
new_line = False
@classmethod def create(cls, markdown: Markdown, token: Token) -> MarkdownElement: """Factory to create markdown element,
Args: markdown (Markdown): The parent Markdown object. token (Any): A token from markdown-it.
Returns: MarkdownElement: A new markdown element """ return cls(str(token.attrs.get("src", "")), markdown.hyperlinks)
def __init__(self, destination: str, hyperlinks: bool) -> None: self.destination = destination self.hyperlinks = hyperlinks self.link: str | None = None super().__init__()
def on_enter(self, context: MarkdownContext) -> None: self.link = context.current_style.link self.text = Text(justify="left") super().on_enter(context)
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: link_style = Style(link=self.link or self.destination or None) title = self.text or Text(self.destination.strip("/").rsplit("/", 1)[-1]) if self.hyperlinks: title.stylize(link_style) text = Text.assemble("🌆 ", title, " ", end="") yield text
class MarkdownContext: """Manages the console render state."""
def __init__( self, console: Console, options: ConsoleOptions, style: Style, inline_code_lexer: str | None = None, inline_code_theme: str = "monokai", ) -> None: self.console = console self.options = options self.style_stack: StyleStack = StyleStack(style) self.stack: Stack[MarkdownElement] = Stack()
self._syntax: Syntax | None = None if inline_code_lexer is not None: self._syntax = Syntax("", inline_code_lexer, theme=inline_code_theme)
@property def current_style(self) -> Style: """Current style which is the product of all styles on the stack.""" return self.style_stack.current
def on_text(self, text: str, node_type: str) -> None: """Called when the parser visits text.""" if node_type in {"fence", "code_inline"} and self._syntax is not None: highlight_text = self._syntax.highlight(text) highlight_text.rstrip() self.stack.top.on_text( self, Text.assemble(highlight_text, style=self.style_stack.current) ) else: self.stack.top.on_text(self, text)
def enter_style(self, style_name: str | Style) -> Style: """Enter a style context.""" style = self.console.get_style(style_name, default="none") self.style_stack.push(style) return self.current_style
def leave_style(self) -> Style: """Leave a style context.""" style = self.style_stack.pop() return style
class Markdown(JupyterMixin): """A Markdown renderable.
Args: markup (str): A string containing markdown. code_theme (str, optional): Pygments theme for code blocks. Defaults to "monokai". See https://pygments.org/styles/ for code themes. justify (JustifyMethod, optional): Justify value for paragraphs. Defaults to None. style (Union[str, Style], optional): Optional style to apply to markdown. hyperlinks (bool, optional): Enable hyperlinks. Defaults to ``True``. inline_code_lexer: (str, optional): Lexer to use if inline code highlighting is enabled. Defaults to None. inline_code_theme: (Optional[str], optional): Pygments theme for inline code highlighting, or None for no highlighting. Defaults to None. """
elements: ClassVar[dict[str, type[MarkdownElement]]] = { "paragraph_open": Paragraph, "heading_open": Heading, "fence": CodeBlock, "code_block": CodeBlock, "blockquote_open": BlockQuote, "hr": HorizontalRule, "bullet_list_open": ListElement, "ordered_list_open": ListElement, "list_item_open": ListItem, "image": ImageItem, "table_open": TableElement, "tbody_open": TableBodyElement, "thead_open": TableHeaderElement, "tr_open": TableRowElement, "td_open": TableDataElement, "th_open": TableDataElement, }
inlines = {"em", "strong", "code", "s"}
def __init__( self, markup: str, code_theme: str = "monokai", justify: JustifyMethod | None = None, style: str | Style = "none", hyperlinks: bool = True, inline_code_lexer: str | None = None, inline_code_theme: str | None = None, ) -> None: parser = MarkdownIt().enable("strikethrough").enable("table") self.markup = markup self.parsed = parser.parse(markup) self.code_theme = code_theme self.justify: JustifyMethod | None = justify self.style = style self.hyperlinks = hyperlinks self.inline_code_lexer = inline_code_lexer self.inline_code_theme = inline_code_theme or code_theme
def _flatten_tokens(self, tokens: Iterable[Token]) -> Iterable[Token]: """Flattens the token stream.""" for token in tokens: is_fence = token.type == "fence" is_image = token.tag == "img" if token.children and not (is_image or is_fence): yield from self._flatten_tokens(token.children) else: yield token
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: """Render markdown to the console.""" style = console.get_style(self.style, default="none") options = options.update(height=None) context = MarkdownContext( console, options, style, inline_code_lexer=self.inline_code_lexer, inline_code_theme=self.inline_code_theme, ) tokens = self.parsed inline_style_tags = self.inlines new_line = False _new_line_segment = Segment.line()
for token in self._flatten_tokens(tokens): node_type = token.type tag = token.tag
entering = token.nesting == 1 exiting = token.nesting == -1 self_closing = token.nesting == 0
if node_type == "text": context.on_text(token.content, node_type) elif node_type == "hardbreak": context.on_text("\n", node_type) elif node_type == "softbreak": context.on_text(" ", node_type) elif node_type == "link_open": href = str(token.attrs.get("href", "")) if self.hyperlinks: link_style = console.get_style("markdown.link_url", default="none") link_style += Style(link=href) context.enter_style(link_style) else: context.stack.push(Link.create(self, token)) elif node_type == "link_close": if self.hyperlinks: context.leave_style() else: element = context.stack.pop() assert isinstance(element, Link) link_style = console.get_style("markdown.link", default="none") context.enter_style(link_style) context.on_text(element.text.plain, node_type) context.leave_style() context.on_text(" (", node_type) link_url_style = console.get_style( "markdown.link_url", default="none" ) context.enter_style(link_url_style) context.on_text(element.href, node_type) context.leave_style() context.on_text(")", node_type) elif ( tag in inline_style_tags and node_type != "fence" and node_type != "code_block" ): if entering: # If it's an opening inline token e.g. strong, em, etc. # Then we move into a style context i.e. push to stack. context.enter_style(f"markdown.{tag}") elif exiting: # If it's a closing inline style, then we pop the style # off of the stack, to move out of the context of it... context.leave_style() else: # If it's a self-closing inline style e.g. `code_inline` context.enter_style(f"markdown.{tag}") if token.content: context.on_text(token.content, node_type) context.leave_style() else: # Map the markdown tag -> MarkdownElement renderable element_class = self.elements.get(token.type) or UnknownElement element = element_class.create(self, token)
if entering or self_closing: context.stack.push(element) element.on_enter(context)
if exiting: # CLOSING tag element = context.stack.pop()
should_render = not context.stack or ( context.stack and context.stack.top.on_child_close(context, element) )
if should_render: if new_line: yield _new_line_segment
yield from console.render(element, context.options) elif self_closing: # SELF-CLOSING tags (e.g. text, code, image) context.stack.pop() text = token.content if text is not None: element.on_text(context, text)
should_render = ( not context.stack or context.stack and context.stack.top.on_child_close(context, element) ) if should_render: if new_line and node_type != "inline": yield _new_line_segment yield from console.render(element, context.options)
if exiting or self_closing: element.on_leave(context) new_line = element.new_line
if __name__ == "__main__": # pragma: no cover import argparse import sys
parser = argparse.ArgumentParser( description="Render Markdown to the console with Rich" ) parser.add_argument( "path", metavar="PATH", help="path to markdown file, or - for stdin", ) parser.add_argument( "-c", "--force-color", dest="force_color", action="store_true", default=None, help="force color for non-terminals", ) parser.add_argument( "-t", "--code-theme", dest="code_theme", default="monokai", help="pygments code theme", ) parser.add_argument( "-i", "--inline-code-lexer", dest="inline_code_lexer", default=None, help="inline_code_lexer", ) parser.add_argument( "-y", "--hyperlinks", dest="hyperlinks", action="store_true", help="enable hyperlinks", ) parser.add_argument( "-w", "--width", type=int, dest="width", default=None, help="width of output (default will auto-detect)", ) parser.add_argument( "-j", "--justify", dest="justify", action="store_true", help="enable full text justify", ) parser.add_argument( "-p", "--page", dest="page", action="store_true", help="use pager to scroll output", ) args = parser.parse_args()
from rich.console import Console
if args.path == "-": markdown_body = sys.stdin.read() else: with open(args.path, encoding="utf-8") as markdown_file: markdown_body = markdown_file.read()
markdown = Markdown( markdown_body, justify="full" if args.justify else "left", code_theme=args.code_theme, hyperlinks=args.hyperlinks, inline_code_lexer=args.inline_code_lexer, ) if args.page: import io import pydoc
fileio = io.StringIO() console = Console( file=fileio, force_terminal=args.force_color, width=args.width ) console.print(markdown) pydoc.pager(fileio.getvalue())
else: console = Console( force_terminal=args.force_color, width=args.width, record=True ) console.print(markdown)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251import refrom ast import literal_evalfrom operator import attrgetterfrom typing import Callable, Iterable, List, Match, NamedTuple, Optional, Tuple, Union
from ._emoji_replace import _emoji_replacefrom .emoji import EmojiVariantfrom .errors import MarkupErrorfrom .style import Stylefrom .text import Span, Text
RE_TAGS = re.compile( r"""((\\*)\[([a-z#/@][^[]*?)])""", re.VERBOSE,)
RE_HANDLER = re.compile(r"^([\w.]*?)(\(.*?\))?$")
class Tag(NamedTuple): """A tag in console markup."""
name: str """The tag name. e.g. 'bold'.""" parameters: Optional[str] """Any additional parameters after the name."""
def __str__(self) -> str: return ( self.name if self.parameters is None else f"{self.name} {self.parameters}" )
@property def markup(self) -> str: """Get the string representation of this tag.""" return ( f"[{self.name}]" if self.parameters is None else f"[{self.name}={self.parameters}]" )
_ReStringMatch = Match[str] # regex match object_ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub_EscapeSubMethod = Callable[[_ReSubCallable, str], str] # Sub method of a compiled re
def escape( markup: str, _escape: _EscapeSubMethod = re.compile(r"(\\*)(\[[a-z#/@][^[]*?])").sub,) -> str: """Escapes text so that it won't be interpreted as markup.
Args: markup (str): Content to be inserted in to markup.
Returns: str: Markup with square brackets escaped. """
def escape_backslashes(match: Match[str]) -> str: """Called by re.sub replace matches.""" backslashes, text = match.groups() return f"{backslashes}{backslashes}\\{text}"
markup = _escape(escape_backslashes, markup) if markup.endswith("\\") and not markup.endswith("\\\\"): return markup + "\\"
return markup
def _parse(markup: str) -> Iterable[Tuple[int, Optional[str], Optional[Tag]]]: """Parse markup in to an iterable of tuples of (position, text, tag).
Args: markup (str): A string containing console markup
""" position = 0 _divmod = divmod _Tag = Tag for match in RE_TAGS.finditer(markup): full_text, escapes, tag_text = match.groups() start, end = match.span() if start > position: yield start, markup[position:start], None if escapes: backslashes, escaped = _divmod(len(escapes), 2) if backslashes: # Literal backslashes yield start, "\\" * backslashes, None start += backslashes * 2 if escaped: # Escape of tag yield start, full_text[len(escapes) :], None position = end continue text, equals, parameters = tag_text.partition("=") yield start, None, _Tag(text, parameters if equals else None) position = end if position < len(markup): yield position, markup[position:], None
def render( markup: str, style: Union[str, Style] = "", emoji: bool = True, emoji_variant: Optional[EmojiVariant] = None,) -> Text: """Render console markup in to a Text instance.
Args: markup (str): A string containing console markup. style: (Union[str, Style]): The style to use. emoji (bool, optional): Also render emoji code. Defaults to True. emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None.
Raises: MarkupError: If there is a syntax error in the markup.
Returns: Text: A test instance. """ emoji_replace = _emoji_replace if "[" not in markup: return Text( emoji_replace(markup, default_variant=emoji_variant) if emoji else markup, style=style, ) text = Text(style=style) append = text.append normalize = Style.normalize
style_stack: List[Tuple[int, Tag]] = [] pop = style_stack.pop
spans: List[Span] = [] append_span = spans.append
_Span = Span _Tag = Tag
def pop_style(style_name: str) -> Tuple[int, Tag]: """Pop tag matching given style name.""" for index, (_, tag) in enumerate(reversed(style_stack), 1): if tag.name == style_name: return pop(-index) raise KeyError(style_name)
for position, plain_text, tag in _parse(markup): if plain_text is not None: # Handle open brace escapes, where the brace is not part of a tag. plain_text = plain_text.replace("\\[", "[") append(emoji_replace(plain_text) if emoji else plain_text) elif tag is not None: if tag.name.startswith("/"): # Closing tag style_name = tag.name[1:].strip()
if style_name: # explicit close style_name = normalize(style_name) try: start, open_tag = pop_style(style_name) except KeyError: raise MarkupError( f"closing tag '{tag.markup}' at position {position} doesn't match any open tag" ) from None else: # implicit close try: start, open_tag = pop() except IndexError: raise MarkupError( f"closing tag '[/]' at position {position} has nothing to close" ) from None
if open_tag.name.startswith("@"): if open_tag.parameters: handler_name = "" parameters = open_tag.parameters.strip() handler_match = RE_HANDLER.match(parameters) if handler_match is not None: handler_name, match_parameters = handler_match.groups() parameters = ( "()" if match_parameters is None else match_parameters )
try: meta_params = literal_eval(parameters) except SyntaxError as error: raise MarkupError( f"error parsing {parameters!r} in {open_tag.parameters!r}; {error.msg}" ) except Exception as error: raise MarkupError( f"error parsing {open_tag.parameters!r}; {error}" ) from None
if handler_name: meta_params = ( handler_name, meta_params if isinstance(meta_params, tuple) else (meta_params,), )
else: meta_params = ()
append_span( _Span( start, len(text), Style(meta={open_tag.name: meta_params}) ) ) else: append_span(_Span(start, len(text), str(open_tag)))
else: # Opening tag normalized_tag = _Tag(normalize(tag.name), tag.parameters) style_stack.append((len(text), normalized_tag))
text_length = len(text) while style_stack: start, tag = style_stack.pop() style = str(tag) if style: append_span(_Span(start, text_length, style))
text.spans = sorted(spans[::-1], key=attrgetter("start")) return text
if __name__ == "__main__": # pragma: no cover MARKUP = [ "[red]Hello World[/red]", "[magenta]Hello [b]World[/b]", "[bold]Bold[italic] bold and italic [/bold]italic[/italic]", "Click [link=https://www.willmcgugan.com]here[/link] to visit my Blog", ":warning-emoji: [bold red blink] DANGER![/]", ]
from rich import print from rich.table import Table
grid = Table("Markup", "Result", padding=(0, 1))
for markup in MARKUP: grid.add_row(Text(markup), markup)
print(grid)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151from operator import itemgetterfrom typing import TYPE_CHECKING, Callable, NamedTuple, Optional, Sequence
from . import errorsfrom .protocol import is_renderable, rich_cast
if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderableType
class Measurement(NamedTuple): """Stores the minimum and maximum widths (in characters) required to render an object."""
minimum: int """Minimum number of cells required to render.""" maximum: int """Maximum number of cells required to render."""
@property def span(self) -> int: """Get difference between maximum and minimum.""" return self.maximum - self.minimum
def normalize(self) -> "Measurement": """Get measurement that ensures that minimum <= maximum and minimum >= 0
Returns: Measurement: A normalized measurement. """ minimum, maximum = self minimum = min(max(0, minimum), maximum) return Measurement(max(0, minimum), max(0, max(minimum, maximum)))
def with_maximum(self, width: int) -> "Measurement": """Get a RenderableWith where the widths are <= width.
Args: width (int): Maximum desired width.
Returns: Measurement: New Measurement object. """ minimum, maximum = self return Measurement(min(minimum, width), min(maximum, width))
def with_minimum(self, width: int) -> "Measurement": """Get a RenderableWith where the widths are >= width.
Args: width (int): Minimum desired width.
Returns: Measurement: New Measurement object. """ minimum, maximum = self width = max(0, width) return Measurement(max(minimum, width), max(maximum, width))
def clamp( self, min_width: Optional[int] = None, max_width: Optional[int] = None ) -> "Measurement": """Clamp a measurement within the specified range.
Args: min_width (int): Minimum desired width, or ``None`` for no minimum. Defaults to None. max_width (int): Maximum desired width, or ``None`` for no maximum. Defaults to None.
Returns: Measurement: New Measurement object. """ measurement = self if min_width is not None: measurement = measurement.with_minimum(min_width) if max_width is not None: measurement = measurement.with_maximum(max_width) return measurement
@classmethod def get( cls, console: "Console", options: "ConsoleOptions", renderable: "RenderableType" ) -> "Measurement": """Get a measurement for a renderable.
Args: console (~rich.console.Console): Console instance. options (~rich.console.ConsoleOptions): Console options. renderable (RenderableType): An object that may be rendered with Rich.
Raises: errors.NotRenderableError: If the object is not renderable.
Returns: Measurement: Measurement object containing range of character widths required to render the object. """ _max_width = options.max_width if _max_width < 1: return Measurement(0, 0) if isinstance(renderable, str): renderable = console.render_str( renderable, markup=options.markup, highlight=False ) renderable = rich_cast(renderable) if is_renderable(renderable): get_console_width: Optional[ Callable[["Console", "ConsoleOptions"], "Measurement"] ] = getattr(renderable, "__rich_measure__", None) if get_console_width is not None: render_width = ( get_console_width(console, options) .normalize() .with_maximum(_max_width) ) if render_width.maximum < 1: return Measurement(0, 0) return render_width.normalize() else: return Measurement(0, _max_width) else: raise errors.NotRenderableError( f"Unable to get render width for {renderable!r}; " "a str, Segment, or object with __rich_console__ method is required" )
def measure_renderables( console: "Console", options: "ConsoleOptions", renderables: Sequence["RenderableType"],) -> "Measurement": """Get a measurement that would fit a number of renderables.
Args: console (~rich.console.Console): Console instance. options (~rich.console.ConsoleOptions): Console options. renderables (Iterable[RenderableType]): One or more renderable objects.
Returns: Measurement: Measurement object containing range of character widths required to contain all given renderables. """ if not renderables: return Measurement(0, 0) get_measurement = Measurement.get measurements = [ get_measurement(console, options, renderable) for renderable in renderables ] measured_width = Measurement( max(measurements, key=itemgetter(0)).minimum, max(measurements, key=itemgetter(1)).maximum, ) return measured_width123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141from typing import TYPE_CHECKING, List, Optional, Tuple, Union
if TYPE_CHECKING: from .console import ( Console, ConsoleOptions, RenderableType, RenderResult, )
from .jupyter import JupyterMixinfrom .measure import Measurementfrom .segment import Segmentfrom .style import Style
PaddingDimensions = Union[int, Tuple[int], Tuple[int, int], Tuple[int, int, int, int]]
class Padding(JupyterMixin): """Draw space around content.
Example: >>> print(Padding("Hello", (2, 4), style="on blue"))
Args: renderable (RenderableType): String or other renderable. pad (Union[int, Tuple[int]]): Padding for top, right, bottom, and left borders. May be specified with 1, 2, or 4 integers (CSS style). style (Union[str, Style], optional): Style for padding characters. Defaults to "none". expand (bool, optional): Expand padding to fit available width. Defaults to True. """
def __init__( self, renderable: "RenderableType", pad: "PaddingDimensions" = (0, 0, 0, 0), *, style: Union[str, Style] = "none", expand: bool = True, ): self.renderable = renderable self.top, self.right, self.bottom, self.left = self.unpack(pad) self.style = style self.expand = expand
@classmethod def indent(cls, renderable: "RenderableType", level: int) -> "Padding": """Make padding instance to render an indent.
Args: renderable (RenderableType): String or other renderable. level (int): Number of characters to indent.
Returns: Padding: A Padding instance. """
return Padding(renderable, pad=(0, 0, 0, level), expand=False)
@staticmethod def unpack(pad: "PaddingDimensions") -> Tuple[int, int, int, int]: """Unpack padding specified in CSS style.""" if isinstance(pad, int): return (pad, pad, pad, pad) if len(pad) == 1: _pad = pad[0] return (_pad, _pad, _pad, _pad) if len(pad) == 2: pad_top, pad_right = pad return (pad_top, pad_right, pad_top, pad_right) if len(pad) == 4: top, right, bottom, left = pad return (top, right, bottom, left) raise ValueError(f"1, 2 or 4 integers required for padding; {len(pad)} given")
def __repr__(self) -> str: return f"Padding({self.renderable!r}, ({self.top},{self.right},{self.bottom},{self.left}))"
def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": style = console.get_style(self.style) if self.expand: width = options.max_width else: width = min( Measurement.get(console, options, self.renderable).maximum + self.left + self.right, options.max_width, ) render_options = options.update_width(width - self.left - self.right) if render_options.height is not None: render_options = render_options.update_height( height=render_options.height - self.top - self.bottom ) lines = console.render_lines( self.renderable, render_options, style=style, pad=True ) _Segment = Segment
left = _Segment(" " * self.left, style) if self.left else None right = ( [_Segment(f'{" " * self.right}', style), _Segment.line()] if self.right else [_Segment.line()] ) blank_line: Optional[List[Segment]] = None if self.top: blank_line = [_Segment(f'{" " * width}\n', style)] yield from blank_line * self.top if left: for line in lines: yield left yield from line yield from right else: for line in lines: yield from line yield from right if self.bottom: blank_line = blank_line or [_Segment(f'{" " * width}\n', style)] yield from blank_line * self.bottom
def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> "Measurement": max_width = options.max_width extra_width = self.left + self.right if max_width - extra_width < 1: return Measurement(max_width, max_width) measure_min, measure_max = Measurement.get(console, options, self.renderable) measurement = Measurement(measure_min + extra_width, measure_max + extra_width) measurement = measurement.with_maximum(max_width) return measurement
if __name__ == "__main__": # pragma: no cover from rich import print
print(Padding("Hello, World", (2, 4), style="on blue")).cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/errors.pyAdded+34
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/file_proxy.pyAdded+57
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/filesize.pyAdded+88
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/highlighter.pyAdded+232
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/json.pyAdded+139
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/jupyter.pyAdded+101
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/layout.pyAdded+442
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/live.pyAdded+404
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/live_render.pyAdded+116
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/logging.pyAdded+305
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/markdown.pyAdded+793
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/markup.pyAdded+251
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/measure.pyAdded+151
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/padding.pyAdded+141