Skip to content

syntaxhighlighters

Class info

Classes

Name Children Inherits
BaseRuleSyntaxHighlighter
prettyqt.syntaxhighlighters.baserulesyntaxhighlighter
HighlightRule
prettyqt.syntaxhighlighters.highlightrule
A highlighting rule, configured via class attributes of subclasses.
  • Rule
  • Rule
  • Rule
JsonHighlighter
prettyqt.syntaxhighlighters.jsonhighlighter
    MarkdownHighlighter
    prettyqt.syntaxhighlighters.markdownhighlighter
      PygmentsHighlighter
      prettyqt.syntaxhighlighters.pygmentshighlighter
      Syntax highlighter that uses Pygments for parsing.
        PythonHighlighter
        prettyqt.syntaxhighlighters.pythonhighlighter
        Syntax highlighter for the Python language.
          RegexMatchHighlighter
          prettyqt.syntaxhighlighters.regexmatchhighlighter
            SelectedWordHighlighter
            prettyqt.syntaxhighlighters.selectedwordhighlighter
              YamlHighlighter
              prettyqt.syntaxhighlighters.yamlhighlighter

                🛈 DocStrings

                syntaxhighlighters module.

                contains some custom syntax highlighers

                BaseRuleSyntaxHighlighter

                Bases: SyntaxHighlighter

                Source code in prettyqt/syntaxhighlighters/baserulesyntaxhighlighter.py
                class BaseRuleSyntaxHighlighter(gui.SyntaxHighlighter):
                    RULES: ClassVar[list] = []
                
                    @classmethod
                    def iter_rules(cls) -> Iterator[tuple[Pattern, int, gui.TextCharFormat]]:
                        for rule in cls.RULES:
                            if isinstance(rule.compiled, list):
                                for i in rule.compiled:
                                    yield (i, rule.nth, rule.fmt)
                            else:
                                yield (rule.compiled, rule.nth, rule.fmt)
                
                    def highlightBlock(self, text: str):
                        """Apply syntax highlighting to the given block of text."""
                        # Do other syntax formatting
                        for expression, nth, fmt in self.iter_rules():
                            for match in expression.finditer(text):
                                span = match.span(nth)
                                self.setFormat(span[0], span[1] - span[0], fmt)
                

                highlightBlock(text: str)

                Apply syntax highlighting to the given block of text.

                Source code in prettyqt/syntaxhighlighters/baserulesyntaxhighlighter.py
                def highlightBlock(self, text: str):
                    """Apply syntax highlighting to the given block of text."""
                    # Do other syntax formatting
                    for expression, nth, fmt in self.iter_rules():
                        for match in expression.finditer(text):
                            span = match.span(nth)
                            self.setFormat(span[0], span[1] - span[0], fmt)
                

                HighlightRule

                A highlighting rule, configured via class attributes of subclasses.

                Source code in prettyqt/syntaxhighlighters/highlightrule.py
                class HighlightRule:
                    """A highlighting rule, configured via class attributes of subclasses."""
                
                    regex: ClassVar[str | list[str]] = ""
                    color: ClassVar[datatypes.ColorType] = "black"
                    italic: ClassVar[bool] = False
                    bold: ClassVar[bool] = False
                    minimal: ClassVar[bool] = False
                    font_size: ClassVar[float | None] = None
                    nth: ClassVar[int] = 0
                    compiled: ClassVar[re.Pattern | list[re.Pattern] | None] = None
                    fmt: ClassVar[gui.TextCharFormat]
                
                    def __init_subclass__(cls):
                        super().__init_subclass__()
                        if isinstance(cls.regex, str):
                            cls.compiled = re.compile(cls.regex)
                            # cls.compiled.setMinimal(True)
                        else:
                            cls.compiled = [re.compile(r) for r in cls.regex]
                        cls.fmt = cls.get_format()
                
                    @classmethod
                    def get_format(cls) -> gui.TextCharFormat:
                        fmt = gui.TextCharFormat()
                        fmt.setFontItalic(cls.italic)
                        fmt.set_foreground_color(cls.color)
                        if cls.font_size:
                            fmt.setFontPointSize(cls.font_size)
                        if cls.bold:
                            fmt.set_font_weight("bold")
                        return fmt
                

                JsonHighlighter

                Bases: SyntaxHighlighter

                Source code in prettyqt/syntaxhighlighters/jsonhighlighter.py
                class JsonHighlighter(gui.SyntaxHighlighter):
                    def highlightBlock(self, text: str):
                        """Highlight a block of code using the rules outlined in the Constructor."""
                        for m in BRACKETS.finditer(text):
                            self.setFormat(m.span()[0], m.span()[1] - m.span()[0], SYMBOL_FORMAT)
                
                        text = text.replace('\\"', "  ")
                        for m in REGEXP1.finditer(text):
                            self.setFormat(m.span()[0], m.span()[1] - m.span()[0], NAME_FORMAT)
                        for m in REGEXP2.finditer(text):
                            self.setFormat(m.span()[0], m.span()[1] - m.span()[0], VALUE_FORMAT)
                

                highlightBlock(text: str)

                Highlight a block of code using the rules outlined in the Constructor.

                Source code in prettyqt/syntaxhighlighters/jsonhighlighter.py
                def highlightBlock(self, text: str):
                    """Highlight a block of code using the rules outlined in the Constructor."""
                    for m in BRACKETS.finditer(text):
                        self.setFormat(m.span()[0], m.span()[1] - m.span()[0], SYMBOL_FORMAT)
                
                    text = text.replace('\\"', "  ")
                    for m in REGEXP1.finditer(text):
                        self.setFormat(m.span()[0], m.span()[1] - m.span()[0], NAME_FORMAT)
                    for m in REGEXP2.finditer(text):
                        self.setFormat(m.span()[0], m.span()[1] - m.span()[0], VALUE_FORMAT)
                

                PygmentsHighlighter

                Bases: SyntaxHighlighter

                Syntax highlighter that uses Pygments for parsing.

                Source code in prettyqt/syntaxhighlighters/pygmentshighlighter.py
                class PygmentsHighlighter(gui.SyntaxHighlighter):
                    """Syntax highlighter that uses Pygments for parsing."""
                
                    # ---------------------------------------------------------------------------
                    #  "QSyntaxHighlighter" interface
                    # ---------------------------------------------------------------------------
                
                    def __init__(
                        self,
                        parent: gui.QTextDocument,
                        lexer: str,
                        style: StyleStr | None = None,
                    ):
                        super().__init__(parent)
                        self._document = gui.QTextDocument(self)
                        self._formatter = html.HtmlFormatter(nowrap=True)
                        self._style = None
                        self._stylename = ""
                        if style is None:
                            gui.GuiApplication.styleHints().colorSchemeChanged.connect(
                                self.adjust_style_to_palette
                            )
                        self.set_style(style)
                        if lexer == "regex":
                            self._lexer = lexers.load_lexer_from_file(str(paths.RE_LEXER_PATH))
                        else:
                            self._lexer = lexers.get_lexer_by_name(lexer)
                
                    def __repr__(self):
                        return get_repr(self, lexer=self._lexer.aliases[0])
                
                    def highlightBlock(self, string):
                        """Highlight a block of text."""
                        if (
                            isinstance(self._lexer, lexer.RegexLexer)
                            and type(self._lexer).get_tokens_unprocessed
                            is lexer.RegexLexer.get_tokens_unprocessed
                        ):
                            prev_data = self.currentBlock().previous().userData()
                            prev_stack = getattr(prev_data, "syntax_stack", None)
                            statestack = list(prev_stack) if isinstance(prev_stack, list) else ["root"]
                            text = self._lexer._preprocess_lexer_input(string)
                            tokens: Iterable[tuple[Any, str]] = (
                                (tok, val)
                                for _, tok, val in _get_tokens_unprocessed(self._lexer, text, statestack)
                            )
                            if self._lexer.filters:
                                tokens = pygments_filter.apply_filters(
                                    tokens, self._lexer.filters, self._lexer
                                )
                            index = 0
                            for token, chunk in tokens:
                                length = qstring_length(chunk)
                                self.setFormat(index, length, self._get_format(token))
                                index += length
                            data = gui.TextBlockUserData(syntax_stack=statestack)
                            self.currentBlock().setUserData(data)
                        else:
                            index = 0
                            for token, chunk in self._lexer.get_tokens(string):
                                length = qstring_length(chunk)
                                self.setFormat(index, length, self._get_format(token))
                                index += length
                
                    # ---------------------------------------------------------------------------
                    # "PygmentsHighlighter" interface
                    # ---------------------------------------------------------------------------
                
                    def set_style(self, style: StyleStr | None):
                        match style:
                            case None:
                                self.adjust_style_to_palette()
                                return
                            case str():
                                self._style = styles.get_style_by_name(style)
                                self._stylename = style
                            case _:
                                raise TypeError(style)
                        self._clear_caches()
                
                    def get_style(self) -> StyleStr | str:
                        return self._stylename
                
                    def adjust_style_to_palette(self):
                        pal = gui.GuiApplication.get_palette()
                        style = "monokai" if pal.is_dark() else "default"
                        self.set_style(style)
                
                    def set_style_sheet(self, stylesheet: str):
                        """Sets a CSS stylesheet.
                
                        The classes in the stylesheet should correspond to those generated by:
                
                            pygmentize -S <style> -f html
                
                        Note that "set_style" and "set_style_sheet" completely override each
                        other, i.e. they cannot be used in conjunction.
                        """
                        self._document.setDefaultStyleSheet(stylesheet)
                        self._style = None
                        self._clear_caches()
                
                    # ---------------------------------------------------------------------------
                    # Protected interface
                    # ---------------------------------------------------------------------------
                
                    def _clear_caches(self):
                        """Clear caches for brushes and formats."""
                        _get_brush.cache_clear()
                        self._get_format.cache_clear()
                
                    @functools.cache  # noqa: B019
                    def _get_format(self, token: str) -> gui.QTextCharFormat:
                        """Returns a QTextCharFormat for token or None."""
                        if self._style is None:
                            return self._get_format_from_document(token, self._document)
                        return _get_format_from_style(token, self._style)
                
                    def _get_format_from_document(
                        self, token: str, document: gui.QTextDocument
                    ) -> gui.QTextCharFormat:
                        """Return a QTextCharFormat for token from document."""
                        _, html = next(self._formatter._format_lines([(token, "dummy")]))
                        document.setHtml(html)
                        return gui.TextCursor(document).charFormat()
                
                    style = core.Property(
                        str,
                        get_style,
                        set_style,
                        doc="Pygments style for the highlighter",
                    )
                

                highlightBlock(string)

                Highlight a block of text.

                Source code in prettyqt/syntaxhighlighters/pygmentshighlighter.py
                def highlightBlock(self, string):
                    """Highlight a block of text."""
                    if (
                        isinstance(self._lexer, lexer.RegexLexer)
                        and type(self._lexer).get_tokens_unprocessed
                        is lexer.RegexLexer.get_tokens_unprocessed
                    ):
                        prev_data = self.currentBlock().previous().userData()
                        prev_stack = getattr(prev_data, "syntax_stack", None)
                        statestack = list(prev_stack) if isinstance(prev_stack, list) else ["root"]
                        text = self._lexer._preprocess_lexer_input(string)
                        tokens: Iterable[tuple[Any, str]] = (
                            (tok, val)
                            for _, tok, val in _get_tokens_unprocessed(self._lexer, text, statestack)
                        )
                        if self._lexer.filters:
                            tokens = pygments_filter.apply_filters(
                                tokens, self._lexer.filters, self._lexer
                            )
                        index = 0
                        for token, chunk in tokens:
                            length = qstring_length(chunk)
                            self.setFormat(index, length, self._get_format(token))
                            index += length
                        data = gui.TextBlockUserData(syntax_stack=statestack)
                        self.currentBlock().setUserData(data)
                    else:
                        index = 0
                        for token, chunk in self._lexer.get_tokens(string):
                            length = qstring_length(chunk)
                            self.setFormat(index, length, self._get_format(token))
                            index += length
                

                set_style_sheet(stylesheet: str)

                Sets a CSS stylesheet.

                The classes in the stylesheet should correspond to those generated by:

                pygmentize -S <style> -f html
                

                Note that "set_style" and "set_style_sheet" completely override each other, i.e. they cannot be used in conjunction.

                Source code in prettyqt/syntaxhighlighters/pygmentshighlighter.py
                def set_style_sheet(self, stylesheet: str):
                    """Sets a CSS stylesheet.
                
                    The classes in the stylesheet should correspond to those generated by:
                
                        pygmentize -S <style> -f html
                
                    Note that "set_style" and "set_style_sheet" completely override each
                    other, i.e. they cannot be used in conjunction.
                    """
                    self._document.setDefaultStyleSheet(stylesheet)
                    self._style = None
                    self._clear_caches()
                

                PythonHighlighter

                Bases: BaseRuleSyntaxHighlighter

                Syntax highlighter for the Python language.

                Source code in prettyqt/syntaxhighlighters/pythonhighlighter.py
                class PythonHighlighter(syntaxhighlighters.BaseRuleSyntaxHighlighter):
                    """Syntax highlighter for the Python language."""
                
                    RULES = Rule.__subclasses__()
                
                    def highlightBlock(self, text: str):
                        """Apply syntax highlighting to the given block of text."""
                        # Do other syntax formatting
                        super().highlightBlock(text)
                        self.setCurrentBlockState(0)
                        # Do multi-line strings
                        if not self.match_multiline(text, *TRI_SINGLE):
                            self.match_multiline(text, *TRI_DOUBLE)
                
                    def match_multiline(
                        self,
                        text: str,
                        delimiter: core.RegularExpression,
                        in_state: int,
                        style: gui.TextCharFormat,
                    ):
                        """Do highlighting of multi-line strings.
                
                        ``delimiter`` should be a
                        ``core.RegExp`` for triple-single-quotes or triple-double-quotes, and
                        ``in_state`` should be a unique integer to represent the corresponding
                        state changes when inside those strings. Returns True if we're still
                        inside a multi-line string when this function is finished.
                        """
                        # If inside triple-single quotes, start at 0
                        if self.previousBlockState() == in_state:
                            start = 0
                            add = 0
                        # Otherwise, look for the delimiter on this line
                        else:
                            match = delimiter.match(text)
                            if not match.hasMatch():
                                return None
                            start = match.capturedStart()
                            add = match.capturedLength()
                
                        # As long as there's a delimiter match on this line...
                        while start >= 0:
                            # Look for the ending delimiter
                            match = delimiter.match(text, start + add)
                            end = match.capturedStart()
                            # Ending delimiter on this line?
                            if end >= add:
                                length = end - start + add + match.capturedLength()
                                self.setCurrentBlockState(0)
                            # No; multi-line string
                            else:
                                self.setCurrentBlockState(in_state)
                                length = len(text) - start + add
                            # Apply formatting
                            self.setFormat(start, length, style)
                            # Look for the next match
                            start = delimiter.match(text, start + length).capturedStart()
                
                        # Return True if still inside a multi-line string, False otherwise
                        return self.currentBlockState() == in_state
                

                highlightBlock(text: str)

                Apply syntax highlighting to the given block of text.

                Source code in prettyqt/syntaxhighlighters/pythonhighlighter.py
                def highlightBlock(self, text: str):
                    """Apply syntax highlighting to the given block of text."""
                    # Do other syntax formatting
                    super().highlightBlock(text)
                    self.setCurrentBlockState(0)
                    # Do multi-line strings
                    if not self.match_multiline(text, *TRI_SINGLE):
                        self.match_multiline(text, *TRI_DOUBLE)
                

                match_multiline(text: str, delimiter: core.RegularExpression, in_state: int, style: gui.TextCharFormat)

                Do highlighting of multi-line strings.

                delimiter should be a core.RegExp for triple-single-quotes or triple-double-quotes, and in_state should be a unique integer to represent the corresponding state changes when inside those strings. Returns True if we're still inside a multi-line string when this function is finished.

                Source code in prettyqt/syntaxhighlighters/pythonhighlighter.py
                def match_multiline(
                    self,
                    text: str,
                    delimiter: core.RegularExpression,
                    in_state: int,
                    style: gui.TextCharFormat,
                ):
                    """Do highlighting of multi-line strings.
                
                    ``delimiter`` should be a
                    ``core.RegExp`` for triple-single-quotes or triple-double-quotes, and
                    ``in_state`` should be a unique integer to represent the corresponding
                    state changes when inside those strings. Returns True if we're still
                    inside a multi-line string when this function is finished.
                    """
                    # If inside triple-single quotes, start at 0
                    if self.previousBlockState() == in_state:
                        start = 0
                        add = 0
                    # Otherwise, look for the delimiter on this line
                    else:
                        match = delimiter.match(text)
                        if not match.hasMatch():
                            return None
                        start = match.capturedStart()
                        add = match.capturedLength()
                
                    # As long as there's a delimiter match on this line...
                    while start >= 0:
                        # Look for the ending delimiter
                        match = delimiter.match(text, start + add)
                        end = match.capturedStart()
                        # Ending delimiter on this line?
                        if end >= add:
                            length = end - start + add + match.capturedLength()
                            self.setCurrentBlockState(0)
                        # No; multi-line string
                        else:
                            self.setCurrentBlockState(in_state)
                            length = len(text) - start + add
                        # Apply formatting
                        self.setFormat(start, length, style)
                        # Look for the next match
                        start = delimiter.match(text, start + length).capturedStart()
                
                    # Return True if still inside a multi-line string, False otherwise
                    return self.currentBlockState() == in_state