[Workaround found] QSyntaxHighlighter problem
I'm successfully using QSyntaxHighlighter with QPlainTextEdit to successfully highlight parts of a code document's text dynamically (actually subclasses of these components as explained in the class documentation) but have run into a problem which I have not been able to figure out.
The highlighter appears to call on a single QTextBlock on each change to the block. This works great as long as all the syntax checking is done on a single block of text. I've worked around this limitation for many purposes (for example; I use the highlighter documentation suggested method for multiline comments and have created a QList for checking backward syntax compatibility) but now I need to highlight not just the current QtextBlock but the document's next QTextBlock too.
Obtaining the next QtextBlock in my implementation of highlightBlock(const QString &text) is straightforward. It's simply:
but actually highlighting nextBlock is anything but straightforward.
I've tried using
and when that didn't work I tried rehighlighting the whole document using
Both were unsuccessful. I've tried connecting these QSyntaxHighlighter slots using self generated signals and using the editors textChanged() signal.
All my attempts have failed with a message generated on line 220 of qsyntaxhighlighter.cpp (Qt 4.8.2)
@Q_ASSERT_X(!currentBlock.isValid(), "QSyntaxHighlighter::reformatBlock()", "reFormatBlock() called recursively");@
In fact, I've failed to find an actual example where anyone has successfully used the rehightlight or rehighlightBlock slots. If anyone knows if an example I would appreciate a reference.
Does anyone have an idea how one could successfully highlight both the current QSyntaxHighlighter block and the next block?
I figured out the following workaround for the QSyntaxHighlighter problem.
QtextDocument has a signal:
@contentsChange(int position, int charsRemoved, int charsAdded)@ which I used to build my own highlighter that doesn't have the rehighlight problems when using the next text block. Since QSyntaxHighlighter requires subclassing and implementing the @highlightBlock(const QString &text) @
method creating my own highlighter was not much of a problem as most of the code is contained in the highlightBlock anyway. The only real additional work was creating my equivalent of the setFormat method otherwise the implementation was relatively straightforward.
The nice thing about using this signal is that the position provided is at the initial cursor position which makes it convenient for processing paste operation.