Comment/uncomment code command for the SQL editor

A new command is added for commenting or uncommenting SQL code (depending
of the state of the first line of the block).

It is bound to "Ctrl+/" as used by many IDEs ("Ctrl+-" is more standard as
Zoom out). Unusual Scintilla binding for "Ctrl+/" is removed for avoiding
interference.

If there is no selection, the current line is un/commented.

See issue #1614
This commit is contained in:
mgrojo
2018-11-18 01:44:59 +01:00
parent 12b4fd91a7
commit 2c4ff851b1
2 changed files with 47 additions and 0 deletions

View File

@@ -3,6 +3,12 @@
#include "Settings.h"
#include "SqlUiLexer.h"
#include <Qsci/qscicommandset.h>
#include <Qsci/qscicommand.h>
#include <QShortcut>
#include <QRegExp>
SqlUiLexer* SqlTextEdit::sqlLexer = nullptr;
SqlTextEdit::SqlTextEdit(QWidget* parent) :
@@ -22,6 +28,15 @@ SqlTextEdit::SqlTextEdit(QWidget* parent) :
registerImage(SqlUiLexer::ApiCompleterIconIdColumn, QImage(":/icons/field"));
registerImage(SqlUiLexer::ApiCompleterIconIdSchema, QImage(":/icons/database"));
// Remove command bindings that would interfere with our shortcutToggleComment
QsciCommand * command = standardCommands()->boundTo(Qt::ControlModifier+Qt::Key_Slash);
command->setKey(0);
command = standardCommands()->boundTo(Qt::ControlModifier+Qt::ShiftModifier+Qt::Key_Slash);
command->setKey(0);
QShortcut* shortcutToggleComment = new QShortcut(QKeySequence(tr("Ctrl+/")), this, nullptr, nullptr, Qt::WidgetShortcut);
connect(shortcutToggleComment, &QShortcut::activated, this, &SqlTextEdit::toggleBlockComment);
// Do rest of initialisation
reloadSettings();
}
@@ -69,3 +84,32 @@ void SqlTextEdit::reloadSettings()
setupSyntaxHighlightingFormat(sqlLexer, "identifier", QsciLexerSQL::Identifier);
setupSyntaxHighlightingFormat(sqlLexer, "identifier", QsciLexerSQL::QuotedIdentifier);
}
void SqlTextEdit::toggleBlockComment()
{
int lineFrom, indexFrom, lineTo, indexTo;
// If there is no selection, select the current line
if (!hasSelectedText()) {
getCursorPosition(&lineFrom, &indexFrom);
setSelection(lineFrom, 0, lineFrom, lineLength(lineFrom));
}
getSelection(&lineFrom, &indexFrom, &lineTo, &indexTo);
bool uncomment = text(lineFrom).contains(QRegExp("^[ \t]*--"));
// Iterate over the selected lines, get line text, make
// replacement depending on whether the first line was commented
// or uncommented, and replace the line text.
for (int line=lineFrom; line<lineTo; line++) {
QString lineText = text(line);
if (uncomment)
lineText.replace(QRegExp("^([ \t]*)-- ?"), "\\1");
else
lineText.replace(QRegExp("^"), "-- ");
setSelection(line, 0, line, lineLength(line));
replaceSelectedText(lineText);
}
}

View File

@@ -23,6 +23,9 @@ public:
public slots:
void reloadSettings();
private slots:
void toggleBlockComment();
};
#endif