def _prefix_with_indent( s: Union[Text, str], console: Console, *, prefix: str, indent: str, ) -> Text: if isinstance(s, Text): text = s else: text = console.render_str(s) return console.render_str(prefix, overflow="ignore") + console.render_str( f"\n{indent}", overflow="ignore").join(text.split(allow_blank=True))
def __init__(self, stream: Optional[TextIO], no_color: bool) -> None: super().__init__( console=Console(file=stream, no_color=no_color, soft_wrap=True), show_time=False, show_level=False, show_path=False, highlighter=NullHighlighter(), )
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult: segments = console.render(self.renderable, options) lines = Segment.split_lines(segments) for line in lines: yield Segment(" " * self.indent) yield from line yield Segment("\n")
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult: width = options.max_width # Python3.6 doesn't have an isascii method on str isascii = getattr(str, "isascii", None) or (lambda s: all(ord(c) < 128 for c in s)) characters = ("-" if (options.ascii_only and not isascii(self.characters)) else self.characters) chars_len = cell_len(characters) if not self.title: rule_text = Text(characters * ((width // chars_len) + 1), self.style) rule_text.truncate(width) rule_text.plain = set_cell_size(rule_text.plain, width) yield rule_text return if isinstance(self.title, Text): title_text = self.title else: title_text = console.render_str(self.title, style="rule.text") title_text.plain = title_text.plain.replace("\n", " ") title_text.expand_tabs() rule_text = Text(end=self.end) if self.align == "center": title_text.truncate(width - 4, overflow="ellipsis") side_width = (width - cell_len(title_text.plain)) // 2 left = Text(characters * (side_width // chars_len + 1)) left.truncate(side_width - 1) right_length = width - cell_len(left.plain) - cell_len( title_text.plain) right = Text(characters * (side_width // chars_len + 1)) right.truncate(right_length) rule_text.append(left.plain + " ", self.style) rule_text.append(title_text) rule_text.append(" " + right.plain, self.style) elif self.align == "left": title_text.truncate(width - 2, overflow="ellipsis") rule_text.append(title_text) rule_text.append(" ") rule_text.append(characters * (width - rule_text.cell_len), self.style) elif self.align == "right": title_text.truncate(width - 2, overflow="ellipsis") rule_text.append(characters * (width - title_text.cell_len - 1), self.style) rule_text.append(" ") rule_text.append(title_text) rule_text.plain = set_cell_size(rule_text.plain, width) yield rule_text
def reconfigure(*args: Any, **kwargs: Any) -> None: """Reconfigures the global console by replacing it with another. Args: console (Console): Replacement console instance. """ from pipenv.patched.notpip._vendor.rich.console import Console new_console = Console(*args, **kwargs) _console = get_console() _console.__dict__ = new_console.__dict__
def get_console() -> "Console": """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console, and hasn't been explicitly given one. Returns: Console: A console instance. """ global _console if _console is None: from .console import Console _console = Console() return _console
def print( *objects: Any, sep: str = " ", end: str = "\n", file: Optional[IO[str]] = None, flush: bool = False, ) -> None: r"""Print object(s) supplied via positional arguments. This function has an identical signature to the built-in print. For more advanced features, see the :class:`~rich.console.Console` class. Args: sep (str, optional): Separator between printed objects. Defaults to " ". end (str, optional): Character to write at end of output. Defaults to "\\n". file (IO[str], optional): File to write to, or None for stdout. Defaults to None. flush (bool, optional): Has no effect as Rich always flushes output. Defaults to False. """ from .console import Console write_console = get_console() if file is None else Console(file=file) return write_console.print(*objects, sep=sep, end=end)
"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 pipenv.patched.notpip._vendor.rich.console import Console console = Console() error_console = Console(stderr=True) try: if args.path == "-": json_data = sys.stdin.read() else: with open(args.path, "rt") as json_file: json_data = json_file.read() 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)
rule_text.append(left.plain + " ", self.style) rule_text.append(title_text) rule_text.append(" " + right.plain, self.style) elif self.align == "left": title_text.truncate(width - 2, overflow="ellipsis") rule_text.append(title_text) rule_text.append(" ") rule_text.append(characters * (width - rule_text.cell_len), self.style) elif self.align == "right": title_text.truncate(width - 2, overflow="ellipsis") rule_text.append(characters * (width - title_text.cell_len - 1), self.style) rule_text.append(" ") rule_text.append(title_text) rule_text.plain = set_cell_size(rule_text.plain, width) yield rule_text if __name__ == "__main__": # pragma: no cover from pipenv.patched.notpip._vendor.rich.console import Console import sys try: text = sys.argv[1] except IndexError: text = "Hello, World" console = Console() console.print(Rule(title=text))
def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: transparent_background = self._get_base_style().transparent_background code_width = ( ( (options.max_width - self._numbers_column_width - 1) if self.line_numbers else options.max_width ) if self.code_width is None else self.code_width ) line_offset = 0 if self.line_range: start_line, end_line = self.line_range line_offset = max(0, start_line - 1) ends_on_nl = self.code.endswith("\n") code = self.code if ends_on_nl else self.code + "\n" code = textwrap.dedent(code) if self.dedent else code code = code.expandtabs(self.tab_size) text = self.highlight(code, self.line_range) ( background_style, number_style, highlight_number_style, ) = self._get_number_styles(console) if not self.line_numbers and not self.word_wrap and not self.line_range: if not ends_on_nl: text.remove_suffix("\n") # Simple case of just rendering text style = ( self._get_base_style() + self._theme.get_style_for_token(Comment) + Style(dim=True) + self.background_style ) if self.indent_guides and not options.ascii_only: text = text.with_indent_guides(self.tab_size, style=style) text.overflow = "crop" if style.transparent_background: yield from console.render( text, options=options.update(width=code_width) ) else: syntax_lines = console.render_lines( text, options.update(width=code_width, height=None), style=self.background_style, pad=True, new_lines=True, ) for syntax_line in syntax_lines: yield from syntax_line return lines: Union[List[Text], Lines] = text.split("\n", allow_blank=ends_on_nl) if self.line_range: lines = lines[line_offset:end_line] if self.indent_guides and not options.ascii_only: style = ( self._get_base_style() + self._theme.get_style_for_token(Comment) + Style(dim=True) + self.background_style ) lines = ( Text("\n") .join(lines) .with_indent_guides(self.tab_size, style=style) .split("\n", allow_blank=True) ) numbers_column_width = self._numbers_column_width render_options = options.update(width=code_width) highlight_line = self.highlight_lines.__contains__ _Segment = Segment padding = _Segment(" " * numbers_column_width + " ", background_style) new_line = _Segment("\n") line_pointer = "> " if options.legacy_windows else "❱ " for line_no, line in enumerate(lines, self.start_line + line_offset): if self.word_wrap: wrapped_lines = console.render_lines( line, render_options.update(height=None), style=background_style, pad=not transparent_background, ) else: segments = list(line.render(console, end="")) if options.no_wrap: wrapped_lines = [segments] else: wrapped_lines = [ _Segment.adjust_line_length( segments, render_options.max_width, style=background_style, pad=not transparent_background, ) ] if self.line_numbers: for first, wrapped_line in loop_first(wrapped_lines): if first: line_column = str(line_no).rjust(numbers_column_width - 2) + " " if highlight_line(line_no): yield _Segment(line_pointer, Style(color="red")) yield _Segment(line_column, highlight_number_style) else: yield _Segment(" ", highlight_number_style) yield _Segment(line_column, number_style) else: yield padding yield from wrapped_line yield new_line else: for wrapped_line in wrapped_lines: yield from wrapped_line yield new_line
dest="background_color", default=None, help="Override background color", ) parser.add_argument( "-x", "--lexer", default="default", dest="lexer_name", help="Lexer name", ) args = parser.parse_args() from pipenv.patched.notpip._vendor.rich.console import Console console = Console(force_terminal=args.force_color, width=args.width) if args.path == "-": code = sys.stdin.read() syntax = Syntax( code=code, lexer=args.lexer_name, line_numbers=args.line_numbers, word_wrap=args.word_wrap, theme=args.theme, background_color=args.background_color, indent_guides=args.indent_guides, ) else: syntax = Syntax.from_path( args.path,
_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 pipenv.patched.notpip._vendor.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") )
""" table.add_row( "Markdown", comparison("[cyan]" + markdown_example, Markdown(markdown_example))) table.add_row( "+more!", """Progress bars, columns, styled logging handler, tracebacks, etc...""", ) return table if __name__ == "__main__": # pragma: no cover console = Console( file=io.StringIO(), force_terminal=True, ) test_card = make_test_card() # Print once to warm cache start = process_time() console.print(test_card) pre_cache_taken = round((process_time() - start) * 1000.0, 1) console.file = io.StringIO() start = process_time() console.print(test_card) taken = round((process_time() - start) * 1000.0, 1) text = console.file.getvalue()
if __name__ == "__main__": # pragma: no cover from pipenv.patched.notpip._vendor.rich.console import Console from pipenv.patched.notpip._vendor.rich import inspect console = Console() inspect(console)
return auto(cls) if __name__ == "__main__": @auto class Foo: def __rich_repr__(self) -> Result: yield "foo" yield "bar", {"shopping": ["eggs", "ham", "pineapple"]} yield "buy", "hand sanitizer" foo = Foo() from pipenv.patched.notpip._vendor.rich.console import Console console = Console() console.rule("Standard repr") console.print(foo) console.print(foo, width=60) console.print(foo, width=30) console.rule("Angular repr") Foo.__rich_repr__.angular = True # type: ignore console.print(foo) console.print(foo, width=60) console.print(foo, width=30)
else: row.append(log_time_display) self._last_time = log_time_display if self.show_level: row.append(level) row.append(Renderables(renderables)) if self.show_path and path: path_text = Text() path_text.append( path, style=f"link file://{link_path}" if link_path else "") if line_no: path_text.append(":") path_text.append( f"{line_no}", style=f"link file://{link_path}#{line_no}" if link_path else "", ) row.append(path_text) output.add_row(*row) return output if __name__ == "__main__": # pragma: no cover from pipenv.patched.notpip._vendor.rich.console import Console c = Console() c.print("[on blue]Hello", justify="right") c.log("[on blue]hello", justify="right")
"$1,332,539,889", style="on black", end_section=True, ) table.add_row( "Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889", ) def header(text: str) -> None: console.print() console.rule(highlight(text)) console.print() console = Console() highlight = ReprHighlighter() header("Example Table") console.print(table, justify="center") table.expand = True header("expand=True") console.print(table) table.width = 50 header("width=50") console.print(table, justify="center") table.width = None table.expand = False
Style(color="bright_blue"), "markdown.link_url": Style(color="blue"), } if __name__ == "__main__": # pragma: no cover import argparse import io from pipenv.patched.notpip._vendor.rich.console import Console from pipenv.patched.notpip._vendor.rich.table import Table from pipenv.patched.notpip._vendor.rich.text import Text parser = argparse.ArgumentParser() parser.add_argument("--html", action="store_true", help="Export as HTML table") args = parser.parse_args() html: bool = args.html console = Console(record=True, width=70, file=io.StringIO()) if html else Console() table = Table("Name", "Styling") for style_name, style in DEFAULT_STYLES.items(): table.add_row(Text(style_name, style=style), str(style)) console.print(table) if html: print(console.export_html(inline_styles=True))
if __name__ == "__main__": if __name__ == "__main__": # pragma: no cover from pipenv.patched.notpip._vendor.rich.console import Console from pipenv.patched.notpip._vendor.rich.syntax import Syntax from pipenv.patched.notpip._vendor.rich.text import Text code = """from rich.console import Console console = Console() text = Text.from_markup("Hello, [bold magenta]World[/]!") console.print(text)""" text = Text.from_markup("Hello, [bold magenta]World[/]!") console = Console() console.rule("rich.Segment") console.print( "A Segment is the last step in the Rich render process before generating text with ANSI codes." ) console.print("\nConsider the following code:\n") console.print(Syntax(code, "python", line_numbers=True)) console.print() console.print( "When you call [b]print()[/b], Rich [i]renders[/i] the object in to the the following:\n" ) fragments = list(console.render(text)) console.print(fragments) console.print() console.print(
yield from blank_lines(bottom_space) def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> Measurement: measurement = Measurement.get(console, options, self.renderable) return measurement if __name__ == "__main__": # pragma: no cover from pipenv.patched.notpip._vendor.rich.console import Console, Group from pipenv.patched.notpip._vendor.rich.highlighter import ReprHighlighter from pipenv.patched.notpip._vendor.rich.panel import Panel highlighter = ReprHighlighter() console = Console() panel = Panel( Group( Align.left(highlighter("align='left'")), Align.center(highlighter("align='center'")), Align.right(highlighter("align='right'")), ), width=60, style="on dark_blue", title="Algin", ) console.print( Align.center(panel, vertical="middle", style="on red", height=console.height) )
new_lines.extend([Text("", style=style)] * blank_lines) new_text = text.blank_copy("\n").join(new_lines) return new_text if __name__ == "__main__": # pragma: no cover from pipenv.patched.notpip._vendor.rich.console import Console text = Text( """\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n""" ) text.highlight_words(["Lorem"], "bold") text.highlight_words(["ipsum"], "italic") console = Console() console.rule("justify='left'") console.print(text, style="red") console.print() console.rule("justify='center'") console.print(text, style="green", justify="center") console.print() console.rule("justify='right'") console.print(text, style="blue", justify="right") console.print() console.rule("justify='full'") console.print(text, style="magenta", justify="full")
min_index = min(range(len(self._colors)), key=get_color_distance) return min_index if __name__ == "__main__": # pragma: no cover import colorsys from typing import Iterable from pipenv.patched.notpip._vendor.rich.color import Color from pipenv.patched.notpip._vendor.rich.console import Console, ConsoleOptions from pipenv.patched.notpip._vendor.rich.segment import Segment from pipenv.patched.notpip._vendor.rich.style import Style class ColorBox: def __rich_console__(self, console: Console, options: ConsoleOptions) -> Iterable[Segment]: height = console.size.height - 3 for y in range(0, height): for x in range(options.max_width): h = x / options.max_width l = y / (height + 1) r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0) r2, g2, b2 = colorsys.hls_to_rgb(h, l + (1 / height / 2), 1.0) bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255) color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255) yield Segment("▄", Style(color=color, bgcolor=bgcolor)) yield Segment.line() console = Console() console.print(ColorBox())
return _emoji_replace(text) def __repr__(self) -> str: return f"<emoji {self.name!r}>" def __str__(self) -> str: return self._char def __rich_console__(self, console: "Console", options: "ConsoleOptions") -> "RenderResult": yield Segment(self._char, console.get_style(self.style)) if __name__ == "__main__": # pragma: no cover import sys from pipenv.patched.notpip._vendor.rich.columns import Columns from pipenv.patched.notpip._vendor.rich.console import Console console = Console(record=True) columns = Columns( (f":{name}: {name}" for name in sorted(EMOJI.keys()) if "\u200D" not in name), column_first=True, ) console.print(columns) if len(sys.argv) > 1: console.save_html(sys.argv[1])