Skip to content

Syntax Highlighting

code_block highlights source code with Pygments, in any of the languages it knows, and draws it on its theme's background.

SOURCE = '''\
@component
def greeting(name: str) -> Text:
    """Say hello."""
    return Text(content=f"Hello, {name}!")
'''


@component
def root() -> Div:
    return Div(
        style=col | gap(1),
        children=tuple(
            Div(
                style=col,
                children=(
                    Text(content=f" {theme} ", style=text_color("slate", 400)),
                    code_block(SOURCE.rstrip("\n"), "python", theme=theme, style=pad(1)),
                ),
            )
            for theme in ("github-dark", "monokai", "solarized-light")
        ),
    )

Syntax highlighting in three themes

 github-dark                                      

 @component                                       
 def greeting(name: str) -> Text:                 
     """Say hello."""                             
     return Text(content=f"Hello, {name}!")       


 monokai                                          

 @component                                       
 def greeting(name: str) -> Text:                 
     """Say hello."""                             
     return Text(content=f"Hello, {name}!")       


 solarized-light                                  

 @component                                       
 def greeting(name: str) -> Text:                 
     """Say hello."""                             
     return Text(content=f"Hello, {name}!")       

A theme is the name of any Pygments style, or a pygments.style.Style subclass, which is how to define your own.

code_block is as wide as its longest line, as an HTML pre is. To scroll lines wider than the space it's given, put it in a scroll container with overflow_x_scroll and scroll_on_wheel, as markdown does, so a sideways wheel, or the wheel with Shift held, scrolls it:

Div(style=overflow_x_scroll, on_input=scroll_on_wheel(), children=(code_block(source, "python"),))

Highlighting is cached by its arguments, so a component can highlight the same code on every render without lexing it again. Tabs are expanded, to four columns unless tab_size says otherwise.

Laying the code out yourself

To lay the code out yourself, highlight returns its chunks, to put in a Text with whatever else you like, and code_style the background and text color to draw them on. Here the chunks are split into lines, each in a row beside its number, and one line is marked, as an editor marks the line its cursor is on:

PATCHED = """\
def mean(values: list[float]) -> float:
    if not values:
        return 0.0

    return sum(values) / len(values)
"""


def lines_of(chunks: tuple[Chunk, ...]) -> list[tuple[Chunk, ...]]:
    """The chunks on each line, split where a chunk holds a line break."""
    lines: list[list[Chunk]] = [[]]
    for chunk in chunks:
        first, *rest = chunk.content.split("\n")
        lines[-1].append(Chunk(content=first, style=chunk.style))
        lines.extend([Chunk(content=part, style=chunk.style)] for part in rest)
    return [tuple(chunk for chunk in line if chunk.content) for line in lines]


@component
def numbered(code: str, marked: int, theme: str = "github-dark") -> Div:
    base = code_style(theme)
    mark = text_bg("slate", 700) | content_color("slate", 700)
    return Div(
        style=col | pad_y(1) | base | fit_content_width,
        children=tuple(
            Div(
                style=row,
                children=(
                    Text(
                        content=f" {number:>2} ",
                        style=base
                        | (text_color("amber", 400) | mark if number == marked else text_color("slate", 500)),
                    ),
                    Text(
                        content=line,
                        style=base | grow(1) | pad_right(2) | (mark if number == marked else default),
                    ),
                ),
            )
            for number, line in enumerate(lines_of(highlight(code.rstrip("\n"), "python", theme)), start=1)
        ),
    )


@component
def lines() -> Div:
    return Div(children=(numbered(PATCHED, marked=3),))

Five lines of Python numbered down the left, the third marked with a lighter background

  1 def mean(values: list[float]) -> float:   
  2     if not values:                        
  3         return 0.0                        
  4                                           
  5     return sum(values) / len(values)      

Highlighting the whole of the code at once, rather than a line at a time, lets the lexer see what spans lines, such as a string in triple quotes.

API

counterweight.highlighting

Syntax highlighting: source code as styled Chunks, colored by a Pygments lexer and style.

Highlighting is a pure function of its arguments, so the results are cached, and a component can highlight the same code on every render without lexing it again.

DEFAULT_CODE_THEME module-attribute

DEFAULT_CODE_THEME: CodeTheme = 'github-dark'

The theme code is highlighted in unless it's given another.

CodeTheme

CodeTheme = str | type[Style]

A Pygments style, by name (any of pygments.styles.get_all_styles()) or as a pygments.style.Style subclass.

highlight cached

highlight(
    code: str,
    language: str,
    theme: CodeTheme = DEFAULT_CODE_THEME,
    tab_size: int = 4,
) -> tuple[Chunk, ...]

code as chunks styled by the tokens a Pygments lexer finds in it.

language is any name or alias of a Pygments lexer, such as python, py, or toml; theme is a Pygments style, by name (any of pygments.styles.get_all_styles()) or as a pygments.style.Style subclass, which is how to define your own. An unknown language or theme raises pygments.util.ClassNotFound. Tabs are expanded to tab_size columns.

The theme's colors are set only where it sets them, so the rest come from the Text's text_style: put the chunks in a Text styled by code_style to draw them on the theme's background.

code_block

code_block(
    code: str,
    language: str,
    theme: CodeTheme = DEFAULT_CODE_THEME,
    style: Style = default,
    tab_size: int = 4,
) -> Text

A Text of code highlighted as language, on the theme's background, with style merged over code_style.

code_style cached

code_style(theme: CodeTheme = DEFAULT_CODE_THEME) -> Style

The theme's background and its plain text's style, for a Text holding chunks from highlight.