Improve indentation support in code editor
MODIFY
src/editor/codeeditor.cpp
src/editor/codeeditor.cpp
#include <QAction>
#include <QApplication>
+#include <QKeyEvent>
#include <QLinearGradient>
#include <QMenu>
#include <QMessageBox>
@@ -82,6 +83,42 @@ void CodeEditor::updateSidebarWidth(int /* newBlockCount */) {
setViewportMargins(m_sidebarWidth, 0, 0, 0);
}
+inline int indentationOf(const QString& text) {
+ int indent = 0;
+ for (const auto& ch : text) {
+ if (ch == " ") {
+ indent++;
+ } else {
+ break;
+ }
+ }
+ return indent;
+}
+
+void CodeEditor::keyPressEvent(QKeyEvent* e) {
+ constexpr int indentAmt = 4;
+ if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {
+ const auto lineText = textCursor().block().text();
+ unsigned indent = 0;
+ // QoL 1: maintain level of indentation
+ indent = indentationOf(lineText);
+
+ // QoL 2: Further indent if last character was an indent start character
+ const auto trimmedLineText = lineText.trimmed();
+ if (!trimmedLineText.isEmpty()) {
+ if (QStringList{":", "(", "{", "["}.contains(QString(trimmedLineText.back()))) {
+ indent += indentAmt;
+ }
+ }
+ QPlainTextEdit::keyPressEvent(e);
+ insertPlainText(QString(" ").repeated(indent));
+ } else if (e->key() == Qt::Key_Tab) {
+ insertPlainText(QString(" ").repeated(indentAmt));
+ } else {
+ QPlainTextEdit::keyPressEvent(e);
+ }
+}
+
bool CodeEditor::eventFilter(QObject* /*observed*/, QEvent* event) {
// Event filter for catching ctrl+Scroll events, for text resizing
if (event->type() == QEvent::Wheel && QApplication::keyboardModifiers() == Qt::ControlModifier) {

MODIFY
src/editor/codeeditor.h
src/editor/codeeditor.h
@@ -70,6 +70,12 @@ private:
QTimer* m_changeTimer;
bool eventFilter(QObject* observed, QEvent* event) override;
+
+ /**
+ * @brief keyPressEvent
+ * We override the key press event to provide any editor quality of life changes that may apply.
+ */
+ void keyPressEvent(QKeyEvent* e) override;
};
class LineNumberArea : public QWidget {

Improve indentation support in code editor #73