Today I've been playing with py-tree-sitter a bit and I wanted to highlight match ranges, but was unable to figure out how to do it with rich, so I reached out to @textualizeio for help.

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 import Style

console = Console()

some code

Now we need some code to highlight. I am going to rip my register_pipeline from another post.

code = '''
from find_kedro import find_kedro

def register_pipelines(self) -> Dict[str, Pipeline]:
    """Register the project's pipeline.
        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)


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

highlight lines

Now we can start highlighting lines right when we initialize our Syntax 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 register_pipelines.

syntax = Syntax(code, 'python', line_numbers=True, highlight_lines=[4])


This hows the line, but still is not very accurate.

highlight text

[@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))

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 register_pipelines.


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.