Search code examples
pythontextformatting

Python library that color text which is a code?


I am building Chat but not web based, Python based. in the chat you exchange information with the AI API. I was wondering if there is libary that recognize that this is code text and color it with the right colors, cause now I did some manual work and it looks bad.

class PythonHighlighter(QSyntaxHighlighter):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._highlight_rules = []

        # Keyword format
        keyword_format = QTextCharFormat()
        keyword_format.setForeground(QColor("blue"))
        keyword_format.setFontWeight(QFont.Bold)
        keywords = ["False", "await", "else", "import", "pass", "None", "break", "except", "in", "raise", "True", "class", "finally", "is", "return", "and", "continue", "for", "lambda", "try", "as", "def","from","nonlocal","while","assert","del","global","not","with","async","elif","if","or","yield","print","range","open","self"]
        self._highlight_rules.append((QRegExp(r"\b" + "|".join(keywords) + r"\b"), keyword_format))

        # String format
        string_format = QTextCharFormat()
        string_format.setForeground(QColor("green"))
        self._highlight_rules.append((QRegExp(r"\".*\""), string_format))
        self._highlight_rules.append((QRegExp(r"\'.*\'"), string_format))

        # Comment format
        comment_format = QTextCharFormat()
        comment_format.setForeground(QColor("gray"))
        self._highlight_rules.append((QRegExp(r"#[^\n]*"), comment_format))

    def highlightBlock(self, text):
        for pattern, format in self._highlight_rules:
            expression = QRegExp(pattern)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, format)
                index = expression.indexIn(text, index + length)

Solution

  • Take a look Pygments maybe this will be enough.

    This is the home of Pygments. It is a generic syntax highlighter suitable for use in code hosting, forums, wikis or other applications that need to prettify source code.
    Highlights are:

    • a wide range of 581 languages and other text formats is supported
    • special attention is paid to details that increase highlighting quality
    • support for new languages and formats are added easily; most languages use a simple regex-based lexing mechanism
    • a number of output formats is available, among them HTML, RTF, LaTeX and ANSI sequences
    • it is usable as a command-line tool and as a library