3

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 new keywords as following:

self.text = Qscintilla(self)
pythonLexer = QsciLexerPython(self.text)
self.text.setLexer(pythonLexer)
self.text.SendScintilla(QsciScintilla.SCI_SETKEYWORDS,1,bytes('WARNING', 'utf-8'))

Now, how do I choose a color to highlight my newly created keywords?

Thanks a lot!

user3352256
  • 109
  • 2
  • 5

2 Answers2

1

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:

class MyLexer(QsciLexerCustom):

    def __init__(self, parent):
        super(MyLexer, self).__init__(parent)
        [...]
    ''''''

    def language(self):
        [...]
    ''''''

    def description(self, style):
        [...]
    ''''''

    def styleText(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/

K.Mulier
  • 8,069
  • 15
  • 79
  • 141
  • Please note that I have copied some text litterally from the given website. I'm allowed to do that, since I've built that website myself ;-) – K.Mulier May 13 '17 at 18:03
0

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:

class CustomLexer(QsciLexerPython):
    def keywords(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)

ekhumoro
  • 115,249
  • 20
  • 229
  • 336