From 6e4a0b2796a22c7c94861900e47bebfefc6a5d4e Mon Sep 17 00:00:00 2001 From: Loren Eteval Date: Mon, 28 Aug 2023 16:45:17 +0800 Subject: [PATCH] Add smart symbol pair typing and backspace Signed-off-by: Loren Eteval --- Furious/Widget/Widget.py | 57 ++++++++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/Furious/Widget/Widget.py b/Furious/Widget/Widget.py index 6583a5f..3ed8fb8 100644 --- a/Furious/Widget/Widget.py +++ b/Furious/Widget/Widget.py @@ -321,32 +321,73 @@ class ZoomablePlainTextEdit(QPlainTextEdit): self.setTextCursor(cursor) - def smartQuotes(self, event): + def smartSymbolPair(self, event, pair): + plainText = self.toPlainText() + cursor = self.textCursor() - if cursor.block().text().endswith('"'): - # Do quote action + if ( + cursor.position() < len(plainText) + and plainText[cursor.position()] == pair[0] + ): + # Do pair0 action super().keyPressEvent(event) else: - # Do quote action + # Do pair0 action super().keyPressEvent(event) - # Add the other quote - cursor.insertText('"') - + # Do pair1 action + cursor.insertText(pair[1]) # Move to middle cursor.movePosition(QTextCursor.MoveOperation.Left) self.setTextCursor(cursor) + def smartBackspace(self, event): + plainText = self.toPlainText() + + cursor = self.textCursor() + cursor.movePosition(QTextCursor.MoveOperation.Left) + + try: + prevChar = self.toPlainText()[cursor.position()] + except Exception: + # Any non-exit exceptions + + prevChar = '' + + # Move the cursor to the next character position + cursor.movePosition(QTextCursor.MoveOperation.Right) + + try: + nextChar = self.toPlainText()[cursor.position()] + except Exception: + # Any non-exit exceptions + + nextChar = '' + + pair = prevChar + nextChar + + if pair == '""' or pair == '{}' or pair == '[]': + cursor.deleteChar() + cursor.deletePreviousChar() + else: + super().keyPressEvent(event) + def keyPressEvent(self, event): if ( event.key() == QtCore.Qt.Key.Key_Return or event.key() == QtCore.Qt.Key.Key_Enter ): self.smartIndent(event) + elif event.key() == QtCore.Qt.Key.Key_Backspace: + self.smartBackspace(event) elif event.key() == QtCore.Qt.Key.Key_QuoteDbl: - self.smartQuotes(event) + self.smartSymbolPair(event, '""') + elif event.key() == QtCore.Qt.Key.Key_BraceLeft: + self.smartSymbolPair(event, '{}') + elif event.key() == QtCore.Qt.Key.Key_BracketLeft: + self.smartSymbolPair(event, '[]') else: super().keyPressEvent(event)