Skip to content Skip to sidebar Skip to footer

Creating And Colorizing New Constructs On A Existing Scintilla Lexer

All, I'm using QScintilla to syntax-highlight my domain specific language (DSL). Since my DSL is based on python, I use the existing Python Lexer for QScintilla. I manage to create

Solution 1:

The QsciLexerPython is quite limited when it comes to highlighting sets of keywords, as it only gives you two to play with. This limitation is imposed by the Python Lexer class from the underlying Scintilla library, so there's not much that can be done about it (unless you want to create a patch).

However, if you only need to highlight one extra set of keywords, then you can subclass QsciLexerPython and reimplement its keywords method:

classCustomLexer(QsciLexerPython):defkeywords(self, keyset):
        if keyset == QsciLexerPython.HighlightedIdentifier:return b'WARNING'return QsciLexerPython.keywords(self, keyset)

With that in place, you can then set the color, font, etc for the style:

    pythonLexer = CustomLexer(self.text)
    pythonLexer.setColor(
        QColor('purple'), QsciLexerPython.HighlightedIdentifier)
    ...

(PS: note that keywords can only contain single-byte characters in the range 0-255)

Solution 2:

To gain even more flexibility, you can consider to build your own custom lexer, not derived from the existing QsciLexerPython one. Watch out - it will be more work.

QScintilla provides the QsciLexerCustom class for this purpose. You have to subclass it like this:

classMyLexer(QsciLexerCustom):

    def__init__(self, parent):
        super(MyLexer, self).__init__(parent)
        [...]
    ''''''deflanguage(self):
        [...]
    ''''''defdescription(self, style):
        [...]
    ''''''defstyleText(self, start, end):
        # Called everytime the editors text has changed
        [...]
    '''''''''--- end class ---'''

Please notice the following parts:

  • __init__(self, parent) : The constructor is typically where you create style-objects.

  • language(self) : This method must return the name of the language. You have to implement it, but what it actually gets used for is unclear to me.

  • description(self, style_nr) : Returns the descriptive name for a given style.

  • styleText(self, start, end) : Gets called everytime editors text has changed. Here you implement syntax highlighting!

For more details, you can visit the following website: https://qscintilla.com/subclass-qscilexercustom/

Post a Comment for "Creating And Colorizing New Constructs On A Existing Scintilla Lexer"