From 597b7882545f38b8ecc7fbba150fd33f94606a26 Mon Sep 17 00:00:00 2001 From: Veronica Berglyd Olsen <1619840+vkbo@users.noreply.github.com> Date: Sun, 12 Nov 2023 20:11:31 +0100 Subject: [PATCH] Implement a new word auto select feature that is more careful with punctuation --- novelwriter/constants.py | 3 +-- novelwriter/gui/doceditor.py | 46 +++++++++++++++++++++++------------- 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/novelwriter/constants.py b/novelwriter/constants.py index 5579e8a3..514ea9f2 100644 --- a/novelwriter/constants.py +++ b/novelwriter/constants.py @@ -327,8 +327,7 @@ class nwQuotes: class nwUnicode: - """Supported unicode character constants and their HTML equivalents. - """ + """Supported unicode character constants and their HTML equivalents.""" # Unicode Constants # ================= diff --git a/novelwriter/gui/doceditor.py b/novelwriter/gui/doceditor.py index 2bbef05c..3fdc83cf 100644 --- a/novelwriter/gui/doceditor.py +++ b/novelwriter/gui/doceditor.py @@ -1934,27 +1934,39 @@ class GuiDocEditor(QPlainTextEdit): def _autoSelect(self) -> QTextCursor: """Return a cursor which may or may not have a selection based - on user settings and document action. + on user settings and document action. The selection will be the + word closest to the cursor consisting of alphanumerical unicode + characters. """ cursor = self.textCursor() if CONFIG.autoSelect and not cursor.hasSelection(): - cursor.select(QTextCursor.WordUnderCursor) - posS = cursor.selectionStart() - posE = cursor.selectionEnd() + cPos = cursor.position() + bPos = cursor.block().position() + bLen = cursor.block().length() - # Underscore counts as a part of the word, so check that the - # selection isn't wrapped in italics markers. - reSelect = False - if self._qDocument.characterAt(posS) == "_": - posS += 1 - reSelect = True - if self._qDocument.characterAt(posE) == "_": - posE -= 1 - reSelect = True - if reSelect: - cursor.clearSelection() - cursor.setPosition(posS, QTextCursor.MoveAnchor) - cursor.setPosition(posE-1, QTextCursor.KeepAnchor) + # Scan backwards + sPos = cPos + for i in range(cPos - bPos): + sPos = cPos - i - 1 + if not self._qDocument.characterAt(sPos).isalnum(): + sPos += 1 + break + + # Scan forwards + ePos = cPos + for i in range(bPos + bLen - cPos): + ePos = cPos + i + if not self._qDocument.characterAt(ePos).isalnum(): + # ePos -= 1 + break + + if ePos - sPos <= 0: + # No selection possible + return cursor + + cursor.clearSelection() + cursor.setPosition(sPos, QTextCursor.MoveAnchor) + cursor.setPosition(ePos, QTextCursor.KeepAnchor) self.setTextCursor(cursor)