Monday, February 6, 2012

QSyntaxHighlighter - Colorized Braces

As I've written in one of my previous posts I like the idea to color subsequent braces differently to improve the overall readability.

Hacking this into QSyntaxHighlighter is, as almost everything in Qt, quite easy. I created a struct, which saves the number of braces, left open for each block (paragraph):

struct BlockData : public QTextBlockUserData
    int numBraces;
Within the highlightBlock method, one can easily access this information, process all braces of the current paragraph, and save the number of open braces:
void Highlighter::highlightBlock(const QString &text)
    BlockData* data = dynamic_cast<BlockData*>(
    int numberOfOpenBraces = 0;
    if (data != NULL) {
        numberOfOpenBraces = data->numBraces;

..tokenizing...update numOfOpenBraces..

    BlockData* newData = dynamic_cast<BlockData*>(currentBlockUserData());
    if (newData == NULL) {
        newData = new BlockData();
    newData->numBraces = numberOfOpenBraces;

This is an example expression, without coloring or braces:

This is the same example, with coloring: (Yes, I might want to change the colors, I know...)

The complete source code can be found here: Highlighter.cpp