While waiting for that reply let's show how we got this far.
Lets import all the classes that we need from rich and setup a console to print to.
from rich.console import Console from rich.syntax import Syntax from rich.style import Style console = Console()
Now we need some code to highlight. I am going to rip my
from another post.
code = ''' from find_kedro import find_kedro def register_pipelines(self) -> Dict[str, Pipeline]: """Register the project's pipeline. Returns: A mapping from a pipeline name to a ``Pipeline`` object. """ return find_kedro() '''
We could simply print out the code we have as a variable, but thats a bit hard to read.
printing with rich's console makes it a little better, but not much by default.
We can pull from rich's syntax module to really pretty this up.
syntax = Syntax(code, 'python', line_numbers=True) console.print(syntax)
Now we are getting some really impressive print outs right in the terminal!
note that I have ipython set to use rich, you will need to console.print() in scripts
Now we can start highlighting lines right when we initialize our
instance. It looks ok. It's not super visible, but more importantly its not
granular enough. I want to highlight specific ranges like the word
syntax = Syntax(code, 'python', line_numbers=True, highlight_lines=) console.print(syntax)
This hows the line, but still is not very accurate.
[@textualizeio] got back to me, let's see if What we can do with stylize_range!
syntax = Syntax(code, 'python', line_numbers=True) style = Style(bgcolor='deep_pink4') syntax.stylize_range(style, (4, 4), (4, 22)) console.print(syntax)
This gives us the final result we are looking for, we can easily see what is
being targeted here. In this case the function name
This turns out to be exacly what I am looking for. Now I have an easy way to print out highlighted code wtih my py-tree-sitter query results.