Bug in Qt Quarterly 31 Matching Parentheses with QSyntaxHighlighter
-
Hey guys,
I'm writing on a little code editor and I found this page:
http://developer.qt.nokia.com/doc/qt-4.8/widgets-codeeditor.html#suggestions-for-extending-the-code-editorIn the last paragraph stands a link to a parenthesis-matching-algo. So I included the algorithm to my application, but the algorithm has a bug. The function matchRightParenthesis occurs an error, because if it calls itself, it passed '0' as a second parameter, but that's wrong.
I've corrected the Algo quick and dirty:
@bool matchLeftRoundParenthesis(QTextBlock currentBlock, int index, int numRightParentheses);
bool matchRightRoundParenthesis(QTextBlock currentBlock, int index, int numLeftParentheses, bool firstTime = false);@
@void TabWidget::matchParentheses()
{
QListQTextEdit::ExtraSelection selections;
setExtraSelections(selections);TextBlockData *data = static_cast<TextBlockData *>(textCursor().block().userData()); if (data) { QVector<ParenthesisInfo *> infos = data->parentheses(); int pos = textCursor().block().position(); for (int i = 0; i < infos.size(); ++i) { ParenthesisInfo *info = infos.at(i); int curPos = textCursor().position() - textCursor().block().position(); if (info->position == curPos - 1 && info->character == '(') { if (matchLeftParenthesis(textCursor().block(), i + 1, 0)) createParenthesisSelection(pos + info->position); }
else if (info->position == curPos - 1 && info->character == ')') {
if (matchRightParenthesis(textCursor().block(), i - 1, 0, true))
createParenthesisSelection(pos + info->position);
}
}
}
}bool TabWidget::matchRightParenthesis(QTextBlock currentBlock, int i, int numRightParentheses, bool firstTime)
{
TextBlockData *data = static_cast<TextBlockData *>(currentBlock.userData());
QVector<ParenthesisInfo *> parentheses = data->parentheses();if(!firstTime) //Set i to the end of the parentheses list.
i = parentheses.size()-1;
int docPos = currentBlock.position();
for (; i > -1 && parentheses.size() > 0; --i) {
ParenthesisInfo *info = parentheses.at(i);
if (info->character == ')') {
++numRightParentheses;
continue;
}
if (info->character == '(' && numRightParentheses == 0) {
createParenthesisSelection(docPos + info->position);
return true;
} else
--numRightParentheses;
}currentBlock = currentBlock.previous(); if (currentBlock.isValid()) return matchRightParenthesis(currentBlock, 0, numRightParentheses); return false;
}@
Maybe it could be corrected in the example code?
Regards netzlab -
It can if you submit a patch with the correction. :-)
You can also simply leave a docnote on that specific page stating the correction, though. That'll be appreciated.
-
I want to add a docnote, but I haben't enough points to do that. :)
-
Nice post. Helps me a lot.
Wouldn't it be nice to have a Qt native Code Editor like the one in QtCreator?