I also added smart bracket behaviour to the editor to automatically complete (, [, and {, following the standard behaviour of modern IDEs.
This feature supports both pair insertion and wrapping of selected text.
} else if (e->key() == Qt::Key_ParenLeft) {
e->accept();
auto cursor = textCursor();
QString selected = cursor.selectedText();
cursor.insertText("(" + selected + ")");
cursor.movePosition(QTextCursor::Left);
setTextCursor(cursor);
} else if (e->key() == Qt::Key_BracketLeft) {
e->accept();
auto cursor = textCursor();
QString selected = cursor.selectedText();
cursor.insertText("[" + selected + "]");
cursor.movePosition(QTextCursor::Left);
setTextCursor(cursor);
} else if (e->key() == Qt::Key_BraceLeft) {
e->accept();
auto cursor = textCursor();
QString selected = cursor.selectedText();
cursor.insertText("{" + selected + "}");
cursor.movePosition(QTextCursor::Left);
setTextCursor(cursor);
} else if ( e->key() == Qt::Key_ParenRight ||
e->key() == Qt::Key_BracketRight ||
e->key() == Qt::Key_BraceRight ) {
QTextCursor cursor = textCursor();
if (cursor.positionInBlock() < cursor.block().length() - 1) {
cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 1);
QString charRight = cursor.selectedText();
cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 1);
QChar typedChar = e->text().isEmpty() ? QChar() : e->text().at(0);
if (typedChar.isPrint() && charRight == typedChar) {
e->accept();
cursor.movePosition(QTextCursor::Right);
setTextCursor(cursor);
return;
}
}
QPlainTextEdit::keyPressEvent(e);
}