Textualize / rich

Rich is a Python library for rich text and beautiful formatting in the terminal.
https://rich.readthedocs.io/en/latest/
MIT License
49.04k stars 1.71k forks source link

[BUG] iPython ignores custom highlighter #2714

Open alexklapheke opened 1 year ago

alexklapheke commented 1 year ago

Describe the bug

Not sure if it's a bug per se, but it was unexpected behavior. I wanted to add some custom highlighting rules to iPython, so I made a custom highlighter object and added the following to ~/.ipython/profile_default/startup/:

from rich import reconfigure
from rich.highlighter import RegexHighlighter
from rich.pretty import install

class CustomReprHighlighter(RegexHighlighter):
    base_style = "repr."
    highlights = [
        # ... my custom highlights ...
    ]

reconfigure(highlighter=CustomReprHighlighter())
install()

The custom highlighting shows up in rich.print, but not in the Out[] cells. It seems like the iPython display hook is using it's own instance of ReprHighlighter and not the one from get_console(). This is the workaround I found:

--- a/pretty.py
+++ b/pretty.py
@@ -174,6 +174,7 @@ def _ipy_display_hook(
         if _safe_isinstance(value, RichRenderable)
         else Pretty(
             value,
+            highlighter=console.highlighter,
             overflow=overflow,
             indent_guides=indent_guides,
             max_length=max_length,

Platform

github-actions[bot] commented 1 year ago

Thank you for your issue. Give us a little time to review it.

PS. You might want to check the FAQ if you haven't done so already.

This is an automated reply, generated by FAQtory

xsjk commented 1 year ago

Describe the bug

I have the same bug. And the bug exists not only IPython but also in Python REPL.

1679497181707

The last output uses the default highlighter ReprHighlighter() instead of RainbowHighlighter()

image

It might be a bug that the evaluated results of any REPL ignores the custom options of the console.

The output format of REPL evaluated result is decided by sys.displayhook. And rich.pretty.install() installs to the global console by assigning display_hook to it. However the implementation of display_hook prints the Pretty value without setting the options to theconsole's. Therefore, specifying the param highlighter to the console's highlighter fix it. And I hope that the customization of console options will be synchronized to the REPL output in the future.

Platform