eric6/QScintilla/Editor.py

branch
maintenance
changeset 8273
698ae46f40a4
parent 8176
31965986ecd1
parent 8259
2bbec88047dd
child 8400
b3eefd7e58d1
--- a/eric6/QScintilla/Editor.py	Fri Apr 02 11:59:41 2021 +0200
+++ b/eric6/QScintilla/Editor.py	Sat May 01 14:27:20 2021 +0200
@@ -10,6 +10,9 @@
 import os
 import re
 import difflib
+import contextlib
+
+import editorconfig
 
 from PyQt5.QtCore import (
     pyqtSignal, pyqtSlot, Qt, QDir, QTimer, QModelIndex, QFileInfo,
@@ -38,8 +41,6 @@
 
 import UI.PixmapCache
 
-from ThirdParty.EditorConfig import editorconfig
-
 EditorAutoCompletionListID = 1
 TemplateCompletionListID = 2
 
@@ -193,7 +194,7 @@
         @type QWidget
         @exception OSError raised to indicate an issue accessing the file
         """
-        super(Editor, self).__init__(parent)
+        super().__init__(parent)
         self.setAttribute(Qt.WidgetAttribute.WA_KeyCompression)
         self.setUtf8(True)
         
@@ -688,16 +689,12 @@
         
         if not bindName and line0.startswith("#!"):
             # #! marker detection
-            if "python3" in line0:
-                bindName = "dummy.py"
-                self.filetype = "Python3"
-            elif "python" in line0:
-                bindName = "dummy.py"
-                self.filetype = "Python3"
-            elif "pypy3" in line0:
-                bindName = "dummy.py"
-                self.filetype = "Python3"
-            elif "pypy" in line0:
+            if (
+                "python3" in line0 or
+                "python" in line0 or
+                "pypy3" in line0 or
+                "pypy" in line0
+            ):
                 bindName = "dummy.py"
                 self.filetype = "Python3"
             elif ("/bash" in line0 or "/sh" in line0):
@@ -1617,11 +1614,9 @@
         """
         Private method to check the selected encoding of the encodings submenu.
         """
-        try:
+        with contextlib.suppress(AttributeError, KeyError):
             (self.supportedEncodings[self.__normalizedEncoding()]
              .setChecked(True))
-        except (AttributeError, KeyError):
-            pass
         
     def __encodingChanged(self, encoding, propagate=True):
         """
@@ -1674,10 +1669,8 @@
         """
         Private method to check the selected eol type of the eol submenu.
         """
-        try:
+        with contextlib.suppress(AttributeError, TypeError):
             self.supportedEols[self.getLineSeparator()].setChecked(True)
-        except (AttributeError, TypeError):
-            pass
         
     def __eolChanged(self):
         """
@@ -1714,10 +1707,8 @@
         Private slot to check the selected spell check language action.
         """
         language = self.getSpellingLanguage()
-        try:
+        with contextlib.suppress(AttributeError, KeyError):
             self.supportedSpellLanguages[language].setChecked(True)
-        except (AttributeError, KeyError):
-            pass
     
     def __spellLanguageChanged(self, language, propagate=True):
         """
@@ -1813,10 +1804,11 @@
             self.SCN_STYLENEEDED.connect(self.__styleNeeded)
         
         # get the font for style 0 and set it as the default font
-        if pyname and pyname.startswith("Pygments|"):
-            key = 'Scintilla/Guessed/style0/font'
-        else:
-            key = 'Scintilla/{0}/style0/font'.format(self.lexer_.language())
+        key = (
+            'Scintilla/Guessed/style0/font'
+            if pyname and pyname.startswith("Pygments|") else
+            'Scintilla/{0}/style0/font'.format(self.lexer_.language())
+        )
         fdesc = Preferences.Prefs.settings.value(key)
         if fdesc is not None:
             font = QFont(fdesc[0], int(fdesc[1]))
@@ -1829,10 +1821,11 @@
         self.lexer_.initProperties()
         
         # initialize the lexer APIs settings
-        if self.project.isOpen() and self.project.isProjectFile(filename):
-            projectType = self.project.getProjectType()
-        else:
-            projectType = ""
+        projectType = (
+            self.project.getProjectType()
+            if self.project.isOpen() and self.project.isProjectFile(filename)
+            else ""
+        )
         api = self.vm.getAPIsManager().getAPIs(self.apiLanguage,
                                                projectType=projectType)
         if api is not None and not api.isEmpty():
@@ -2165,13 +2158,13 @@
         if self.filetype == "JavaScript":
             return True
         
-        if self.filetype == "":
-            if (
-                self.fileName and
-                os.path.splitext(self.fileName)[1] == ".js"
-            ):
-                self.filetype = "JavaScript"
-                return True
+        if (
+            self.filetype == "" and
+            self.fileName and
+            os.path.splitext(self.fileName)[1] == ".js"
+        ):
+            self.filetype = "JavaScript"
+            return True
         
         return False
     
@@ -2248,25 +2241,25 @@
         """
         if (
             mtype & (self.SC_MOD_INSERTTEXT | self.SC_MOD_DELETETEXT) and
-            linesAdded != 0
+            linesAdded != 0 and
+            self.breaks
         ):
-            if self.breaks:
-                bps = []    # list of breakpoints
-                for handle, (ln, cond, temp, enabled, ignorecount) in (
-                    self.breaks.items()
-                ):
-                    line = self.markerLine(handle) + 1
-                    if ln != line:
-                        bps.append((ln, line))
-                        self.breaks[handle] = (line, cond, temp, enabled,
-                                               ignorecount)
-                self.inLinesChanged = True
-                for ln, line in sorted(bps, reverse=linesAdded > 0):
-                    index1 = self.breakpointModel.getBreakPointIndex(
-                        self.fileName, ln)
-                    index2 = self.breakpointModel.index(index1.row(), 1)
-                    self.breakpointModel.setData(index2, line)
-                self.inLinesChanged = False
+            bps = []    # list of breakpoints
+            for handle, (ln, cond, temp, enabled, ignorecount) in (
+                self.breaks.items()
+            ):
+                line = self.markerLine(handle) + 1
+                if ln != line:
+                    bps.append((ln, line))
+                    self.breaks[handle] = (line, cond, temp, enabled,
+                                           ignorecount)
+            self.inLinesChanged = True
+            for ln, line in sorted(bps, reverse=linesAdded > 0):
+                index1 = self.breakpointModel.getBreakPointIndex(
+                    self.fileName, ln)
+                index2 = self.breakpointModel.index(index1.row(), 1)
+                self.breakpointModel.setData(index2, line)
+            self.inLinesChanged = False
         
     def __restoreBreakpoints(self):
         """
@@ -2849,9 +2842,7 @@
         self.__hasTaskMarkers = False
         
         # now search tasks and record them
-        lineIndex = -1
-        for line in txtList:
-            lineIndex += 1
+        for lineIndex, line in enumerate(txtList):
             shouldBreak = False
             
             if line.endswith("__NO-TASK__"):
@@ -3256,16 +3247,10 @@
             except OSError:
                 # if there was an error, ignore it
                 perms_valid = False
-            try:
+            with contextlib.suppress(OSError):
                 os.remove(bfn)
-            except OSError:
-                # if there was an error, ignore it
-                pass
-            try:
+            with contextlib.suppress(OSError):
                 os.rename(fn, bfn)
-            except OSError:
-                # if there was an error, ignore it
-                pass
         
         # now write text to the file fn
         try:
@@ -3299,7 +3284,7 @@
                 self.project.startswithProjectPath(self.fileName)
             ):
                 path = os.path.dirname(self.fileName)
-            else:
+            elif not self.fileName:
                 path = self.project.getProjectPath()
         
         if not path and self.fileName:
@@ -3364,13 +3349,13 @@
             return False
         
         res = self.writeFile(fn)
-        if res:
+        if (
+            res and
+            self.project.isOpen() and
+            self.project.startswithProjectPath(fn)
+        ):
             # save to project, if a project is loaded
-            if (
-                self.project.isOpen() and
-                self.project.startswithProjectPath(fn)
-            ):
-                self.project.appendFile(fn)
+            self.project.appendFile(fn)
         
         return res
         
@@ -3584,10 +3569,11 @@
         else:
             wc = re.sub(r'\w', "", wc)
             pattern = r"\b[\w{0}]+\b".format(re.escape(wc))
-        if self.caseSensitive():
-            rx = re.compile(pattern)
-        else:
-            rx = re.compile(pattern, re.IGNORECASE)
+        rx = (
+            re.compile(pattern)
+            if self.caseSensitive() else
+            re.compile(pattern, re.IGNORECASE)
+        )
         
         text = self.text(line)
         for match in rx.finditer(text):
@@ -3693,7 +3679,7 @@
         ch = self.charAt(pos)
         
         # Don't go past the end of the previous line
-        if ch == '\n' or ch == '\r':
+        if ch in ('\n', '\r'):
             return "", pos
         
         return ch, pos
@@ -3899,8 +3885,9 @@
         if Preferences.getEditor("CommentColumn0"):
             self.insertAt(self.lexer_.commentStr(), line, 0)
         else:
-            self.insertAt(self.lexer_.commentStr(), line,
-                          self.indentation(line))
+            lineText = self.text(line)
+            pos = len(lineText.replace(lineText.lstrip(" \t"), ""))
+            self.insertAt(self.lexer_.commentStr(), line, pos)
         self.endUndoAction()
         
     def uncommentLine(self):
@@ -3923,8 +3910,9 @@
         if Preferences.getEditor("CommentColumn0"):
             self.setSelection(line, 0, line, len(commentStr))
         else:
-            self.setSelection(line, self.indentation(line),
-                              line, self.indentation(line) + len(commentStr))
+            lineText = self.text(line)
+            pos = len(lineText.replace(lineText.lstrip(" \t"), ""))
+            self.setSelection(line, pos, line, pos + len(commentStr))
         self.removeSelectedText()
         self.endUndoAction()
         
@@ -3942,10 +3930,7 @@
         
         # get the selection boundaries
         lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
-        if indexTo == 0:
-            endLine = lineTo - 1
-        else:
-            endLine = lineTo
+        endLine = lineTo if indexTo else lineTo - 1
         
         self.beginUndoAction()
         # iterate over the lines
@@ -3953,7 +3938,9 @@
             if Preferences.getEditor("CommentColumn0"):
                 self.insertAt(commentStr, line, 0)
             else:
-                self.insertAt(commentStr, line, self.indentation(line))
+                lineText = self.text(line)
+                pos = len(lineText.replace(lineText.lstrip(" \t"), ""))
+                self.insertAt(commentStr, line, pos)
         
         # change the selection accordingly
         self.setSelection(lineFrom, 0, endLine + 1, 0)
@@ -3973,10 +3960,7 @@
         
         # get the selection boundaries
         lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
-        if indexTo == 0:
-            endLine = lineTo - 1
-        else:
-            endLine = lineTo
+        endLine = lineTo if indexTo else lineTo - 1
         
         self.beginUndoAction()
         # iterate over the lines
@@ -3989,10 +3973,9 @@
             if Preferences.getEditor("CommentColumn0"):
                 self.setSelection(line, 0, line, len(commentStr))
             else:
-                self.setSelection(line,
-                                  self.indentation(line),
-                                  line,
-                                  self.indentation(line) + len(commentStr))
+                lineText = self.text(line)
+                pos = len(lineText.replace(lineText.lstrip(" \t"), ""))
+                self.setSelection(line, pos, line, pos + len(commentStr))
             self.removeSelectedText()
             
             # adjust selection start
@@ -4119,10 +4102,7 @@
         
         # get the selection boundaries
         lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
-        if indexTo == 0:
-            endLine = lineTo - 1
-        else:
-            endLine = lineTo
+        endLine = lineTo if indexTo else lineTo - 1
         
         self.beginUndoAction()
         # iterate over the lines
@@ -4186,11 +4166,7 @@
         
         # get the selection
         lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
-        
-        if indexTo == 0:
-            endLine = lineTo - 1
-        else:
-            endLine = lineTo
+        endLine = lineTo if indexTo else lineTo - 1
         
         self.beginUndoAction()
         # iterate over the lines
@@ -4548,10 +4524,8 @@
         if Preferences.getEditor("FoldingMargin"):
             self.setMarginWidth(self.__foldMargin, 16)
             folding = Preferences.getEditor("FoldingStyle")
-            try:
+            with contextlib.suppress(AttributeError):
                 folding = QsciScintilla.FoldStyle(folding)
-            except AttributeError:
-                pass
             self.setFolding(folding, self.__foldMargin)
             self.setFoldMarginColors(
                 Preferences.getEditorColour("FoldmarginBackground"),
@@ -4601,16 +4575,13 @@
         if Preferences.getEditor("ShowWhitespace"):
             self.setWhitespaceVisibility(
                 QsciScintilla.WhitespaceVisibility.WsVisible)
-            try:
+            with contextlib.suppress(AttributeError):
                 self.setWhitespaceForegroundColor(
                     Preferences.getEditorColour("WhitespaceForeground"))
                 self.setWhitespaceBackgroundColor(
                     Preferences.getEditorColour("WhitespaceBackground"))
                 self.setWhitespaceSize(
                     Preferences.getEditor("WhitespaceSize"))
-            except AttributeError:
-                # QScintilla before 2.5 doesn't support this
-                pass
         else:
             self.setWhitespaceVisibility(
                 QsciScintilla.WhitespaceVisibility.WsInvisible)
@@ -4696,15 +4667,13 @@
         
         self.setCursorFlashTime(QApplication.cursorFlashTime())
         
-        try:
+        with contextlib.suppress(AttributeError):
             if Preferences.getEditor("AnnotationsEnabled"):
                 self.setAnnotationDisplay(
                     QsciScintilla.AnnotationDisplay.AnnotationBoxed)
             else:
                 self.setAnnotationDisplay(
                     QsciScintilla.AnnotationDisplay.AnnotationHidden)
-        except AttributeError:
-            pass
         self.__setAnnotationStyles()
         
         if Preferences.getEditor("OverrideEditAreaColours"):
@@ -4789,11 +4758,9 @@
             Preferences.getEditorColour("CallTipsHighlight"))
         self.setCallTipsVisible(Preferences.getEditor("CallTipsVisible"))
         calltipsStyle = Preferences.getEditor("CallTipsStyle")
-        try:
+        with contextlib.suppress(AttributeError):
             self.setCallTipsPosition(
                 Preferences.getEditor("CallTipsPosition"))
-        except AttributeError:
-            pass
         
         if Preferences.getEditor("CallTipsEnabled"):
             if calltipsStyle == QsciScintilla.CallTipsStyle.CallTipsNoContext:
@@ -4944,11 +4911,7 @@
             return False
         
         wseps = self.lexer_.autoCompletionWordSeparators()
-        for wsep in wseps:
-            if wsep.endswith(ch):
-                return True
-        
-        return False
+        return any(wsep.endswith(ch) for wsep in wseps)
     
     def __autocompletionCancelled(self):
         """
@@ -5048,11 +5011,10 @@
                 self.__acTimer.start()
             else:
                 self.__autoComplete(auto, context)
-        elif not auto:
-            self.autoCompleteQScintilla()
         elif (
-            self.autoCompletionSource() !=
-            QsciScintilla.AutoCompletionSource.AcsNone
+            not auto or
+            (self.autoCompletionSource() !=
+             QsciScintilla.AutoCompletionSource.AcsNone)
         ):
             self.autoCompleteQScintilla()
     
@@ -5066,10 +5028,11 @@
         line, col = self.getCursorPosition()
         text = self.text(line)
         try:
-            if self.__isStartChar(text[col - 1]):
-                acText = self.getWordLeft(line, col - 1) + text[col - 1]
-            else:
-                acText = self.getWordLeft(line, col)
+            acText = (
+                self.getWordLeft(line, col - 1) + text[col - 1]
+                if self.__isStartChar(text[col - 1]) else
+                self.getWordLeft(line, col)
+            )
         except IndexError:
             acText = ""
         
@@ -5091,10 +5054,11 @@
         if auto and self.__acText == '':
             return
         
-        if self.__acCacheEnabled:
-            completions = self.__acCache.get(self.__acText)
-        else:
-            completions = None
+        completions = (
+            self.__acCache.get(self.__acText)
+            if self.__acCacheEnabled else
+            None
+        )
         if completions is not None:
             # show list with cached entries
             if self.isListActive():
@@ -5171,12 +5135,13 @@
         @param completions completions to be shown
         @type list of str or set of str
         """
-        if Preferences.getEditor("AutoCompletionReversedList"):
-            acCompletions = sorted(
+        acCompletions = (
+            sorted(
                 list(completions),
                 key=self.__replaceLeadingUnderscores)
-        else:
-            acCompletions = sorted(list(completions))
+            if Preferences.getEditor("AutoCompletionReversedList") else
+            sorted(list(completions))
+        )
         self.showUserList(EditorAutoCompletionListID, acCompletions)
     
     def __replaceLeadingUnderscores(self, txt):
@@ -5315,7 +5280,7 @@
         if bool(self.__ctHookFunctions):
             self.__callTip()
         else:
-            super(Editor, self).callTip()
+            super().callTip()
     
     def __callTip(self):
         """
@@ -5356,16 +5321,20 @@
         if not found:
             return
         
+        callTips = []
         if self.__ctHookFunctions:
-            callTips = []
             for key in self.__ctHookFunctions:
                 callTips.extend(self.__ctHookFunctions[key](self, pos, commas))
             callTips = list(set(callTips))
             callTips.sort()
+        else:
+            # try QScintilla calltips
+            super().callTip()
+            return
         if len(callTips) == 0:
             if Preferences.getEditor("CallTipsScintillaOnFail"):
                 # try QScintilla calltips
-                super(Editor, self).callTip()
+                super().callTip()
             return
         
         ctshift = 0
@@ -5375,12 +5344,13 @@
                 ctshift = shift
         
         cv = self.callTipsVisible()
-        if cv > 0:
+        ct = (
             # this is just a safe guard
-            ct = self._encodeString("\n".join(callTips[:cv]))
-        else:
+            self._encodeString("\n".join(callTips[:cv]))
+            if cv > 0 else
             # until here and unindent below
-            ct = self._encodeString("\n".join(callTips))
+            self._encodeString("\n".join(callTips))
+        )
         
         self.SendScintilla(QsciScintilla.SCI_CALLTIPSHOW,
                            self.__adjustedCallTipPosition(ctshift, pos), ct)
@@ -5434,7 +5404,7 @@
             if ct - ctshift < ctmin:
                 ct = ctmin
             else:
-                ct = ct - ctshift
+                ct -= ctshift
         return ct
     
     #################################################################
@@ -5538,6 +5508,11 @@
                 self.menuActs["Uncomment"].setEnabled(False)
                 self.menuActs["StreamComment"].setEnabled(False)
                 self.menuActs["BoxComment"].setEnabled(False)
+            
+            cline = self.getCursorPosition()[0]
+            line = self.text(cline)
+            self.menuActs["Docstring"].setEnabled(
+                self.getDocstringGenerator().isFunctionStart(line))
         
         self.menuActs["TypingAidsEnabled"].setEnabled(
             self.completer is not None)
@@ -5576,11 +5551,6 @@
         
         self.menuActs["Tools"].setEnabled(not self.toolsMenu.isEmpty())
         
-        cline = self.getCursorPosition()[0]
-        line = self.text(cline)
-        self.menuActs["Docstring"].setEnabled(
-            self.getDocstringGenerator().isFunctionStart(line))
-        
         self.showMenu.emit("Main", self.menu, self)
         
     def __showContextMenuAutocompletion(self):
@@ -6383,7 +6353,7 @@
         seline = self.markerFindNext(0, 1 << self.syntaxerror)
         if seline >= 0:
             index = 0
-            for handle in self.syntaxerrors.keys():
+            for handle in self.syntaxerrors:
                 if self.markerLine(handle) == seline:
                     index = self.syntaxerrors[handle][0][1]
             self.setCursorPosition(seline, index)
@@ -6689,7 +6659,7 @@
             styleAnnotations = []
             
             # step 1: do warnings
-            for handle in self.warnings.keys():
+            for handle in self.warnings:
                 if self.markerLine(handle) == line:
                     for msg, warningType in self.warnings[handle]:
                         if warningType == self.WarningStyle:
@@ -6700,7 +6670,7 @@
                                 self.tr("Warning: {0}").format(msg))
             
             # step 2: do syntax errors
-            for handle in self.syntaxerrors.keys():
+            for handle in self.syntaxerrors:
                 if self.markerLine(handle) == line:
                     for msg, _ in self.syntaxerrors[handle]:
                         errorAnnotations.append(
@@ -6968,7 +6938,7 @@
         """
         Public method to undo the last recorded change.
         """
-        super(Editor, self).undo()
+        super().undo()
         self.undoAvailable.emit(self.isUndoAvailable())
         self.redoAvailable.emit(self.isRedoAvailable())
         
@@ -6976,7 +6946,7 @@
         """
         Public method to redo the last recorded change.
         """
-        super(Editor, self).redo()
+        super().redo()
         self.undoAvailable.emit(self.isUndoAvailable())
         self.redoAvailable.emit(self.isRedoAvailable())
         
@@ -7022,16 +6992,14 @@
         if self.spell:
             self.spell.stopIncrementalCheck()
         
-        try:
+        with contextlib.suppress(TypeError):
             self.project.projectPropertiesChanged.disconnect(
                 self.__projectPropertiesChanged)
-        except TypeError:
-            pass
         
         if self.fileName:
             self.taskViewer.clearFileTasks(self.fileName, True)
         
-        super(Editor, self).close()
+        super().close()
         
     def keyPressEvent(self, ev):
         """
@@ -7050,10 +7018,7 @@
             @type str
             """
             startChar = encString[0]
-            if len(encString) == 2:
-                endChar = encString[1]
-            else:
-                endChar = startChar
+            endChar = encString[1] if len(encString) == 2 else startChar
             
             sline, sindex, eline, eindex = self.getSelection()
             replaceText = startChar + self.selectedText() + endChar
@@ -7066,13 +7031,15 @@
         
         # See it is text to insert.
         if len(txt) and txt >= " ":
-            if self.hasSelectedText():
-                if txt in Editor.EncloseChars:
-                    encloseSelectedText(Editor.EncloseChars[txt])
-                    ev.accept()
-                    return
+            if (
+                self.hasSelectedText() and
+                txt in Editor.EncloseChars
+            ):
+                encloseSelectedText(Editor.EncloseChars[txt])
+                ev.accept()
+                return
             
-            super(Editor, self).keyPressEvent(ev)
+            super().keyPressEvent(ev)
         else:
             ev.ignore()
         
@@ -7094,10 +7061,8 @@
         self.vm.copyActGrp.setEnabled(True)
         self.vm.viewActGrp.setEnabled(True)
         self.vm.searchActGrp.setEnabled(True)
-        try:
+        with contextlib.suppress(AttributeError):
             self.setCaretWidth(self.caretWidth)
-        except AttributeError:
-            pass
         self.__updateReadOnly(False)
         if (
             self.vm.editorsCheckFocusInEnabled() and
@@ -7133,7 +7098,7 @@
         
         self.setCursorFlashTime(QApplication.cursorFlashTime())
         
-        super(Editor, self).focusInEvent(event)
+        super().focusInEvent(event)
         
     def focusOutEvent(self, event):
         """
@@ -7145,7 +7110,7 @@
         self.vm.editorActGrp.setEnabled(False)
         self.setCaretWidth(0)
         
-        super(Editor, self).focusOutEvent(event)
+        super().focusOutEvent(event)
         
     def changeEvent(self, evt):
         """
@@ -7175,7 +7140,7 @@
                 cap = self.tr("{0} (ro)").format(cap)
             self.setWindowTitle(cap)
         
-        super(Editor, self).changeEvent(evt)
+        super().changeEvent(evt)
         
     def mousePressEvent(self, event):
         """
@@ -7185,7 +7150,7 @@
         @type QMouseEvent
         """
         self.vm.eventFilter(self, event)
-        super(Editor, self).mousePressEvent(event)
+        super().mousePressEvent(event)
     
     def mouseDoubleClickEvent(self, evt):
         """
@@ -7194,7 +7159,7 @@
         @param evt reference to the mouse event
         @type QMouseEvent
         """
-        super(Editor, self).mouseDoubleClickEvent(evt)
+        super().mouseDoubleClickEvent(evt)
         
         self.mouseDoubleClick.emit(evt.pos(), evt.buttons())
         
@@ -7222,7 +7187,7 @@
             evt.accept()
             return
         
-        super(Editor, self).wheelEvent(evt)
+        super().wheelEvent(evt)
     
     def event(self, evt):
         """
@@ -7237,7 +7202,7 @@
             self.gestureEvent(evt)
             return True
         
-        return super(Editor, self).event(evt)
+        return super().event(evt)
     
     def gestureEvent(self, evt):
         """
@@ -7269,7 +7234,7 @@
         @param evt reference to the resize event
         @type QResizeEvent
         """
-        super(Editor, self).resizeEvent(evt)
+        super().resizeEvent(evt)
         self.__markerMap.calculateGeometry()
     
     def viewportEvent(self, evt):
@@ -7281,13 +7246,9 @@
         @return flag indiating that the event was handled
         @rtype bool
         """
-        try:
+        with contextlib.suppress(AttributeError):
             self.__markerMap.calculateGeometry()
-        except AttributeError:
-            # ignore this - there seems to be a runtime issue when the editor
-            # is created
-            pass
-        return super(Editor, self).viewportEvent(evt)
+        return super().viewportEvent(evt)
     
     def __updateReadOnly(self, bForce=True):
         """
@@ -7397,7 +7358,7 @@
         Public method to set the styles according the selected Qt style
         or the selected editor colours.
         """
-        super(Editor, self).clearStyles()
+        super().clearStyles()
         if Preferences.getEditor("OverrideEditAreaColours"):
             self.setColor(Preferences.getEditorColour("EditAreaForeground"))
             self.setPaper(Preferences.getEditorColour("EditAreaBackground"))
@@ -7416,7 +7377,7 @@
         if self.inDragDrop:
             event.acceptProposedAction()
         else:
-            super(Editor, self).dragEnterEvent(event)
+            super().dragEnterEvent(event)
         
     def dragMoveEvent(self, event):
         """
@@ -7427,7 +7388,7 @@
         if self.inDragDrop:
             event.accept()
         else:
-            super(Editor, self).dragMoveEvent(event)
+            super().dragMoveEvent(event)
         
     def dragLeaveEvent(self, event):
         """
@@ -7439,7 +7400,7 @@
             self.inDragDrop = False
             event.accept()
         else:
-            super(Editor, self).dragLeaveEvent(event)
+            super().dragLeaveEvent(event)
         
     def dropEvent(self, event):
         """
@@ -7461,7 +7422,7 @@
                             .format(fname))
             event.acceptProposedAction()
         else:
-            super(Editor, self).dropEvent(event)
+            super().dropEvent(event)
         
         self.inDragDrop = False
     
@@ -7734,7 +7695,7 @@
             if text in matchingPairs:
                 self.delete()
         
-        super(Editor, self).editorCommand(cmd)
+        super().editorCommand(cmd)
     
     def __applyTemplate(self, templateName, language):
         """
@@ -7803,11 +7764,9 @@
         """
         Public slot to handle the closing of a project.
         """
-        try:
+        with contextlib.suppress(TypeError):
             self.project.projectPropertiesChanged.disconnect(
                 self.__projectPropertiesChanged)
-        except TypeError:
-            pass
     
     #######################################################################
     ## Spell checking related methods
@@ -7875,17 +7834,13 @@
         Public method to set the automatic spell checking.
         """
         if Preferences.getEditor("AutoSpellCheckingEnabled"):
-            try:
+            with contextlib.suppress(TypeError):
                 self.SCN_CHARADDED.connect(
                     self.__spellCharAdded, Qt.ConnectionType.UniqueConnection)
-            except TypeError:
-                pass
             self.spell.checkDocumentIncrementally()
         else:
-            try:
+            with contextlib.suppress(TypeError):
                 self.SCN_CHARADDED.disconnect(self.__spellCharAdded)
-            except TypeError:
-                pass
             self.clearAllIndicators(self.spellingIndicator)
     
     def isSpellCheckRegion(self, pos):
@@ -7905,13 +7860,10 @@
         """
         if self.__spellCheckStringsOnly:
             if (
-                self.__fileNameExtension in
-                Preferences.getEditor("FullSpellCheckExtensions")
-            ):
-                return True
-            elif (
-                not self.__fileNameExtension and
-                Preferences.getEditor("FullSpellCheckUnknown")
+                (self.__fileNameExtension in
+                 Preferences.getEditor("FullSpellCheckExtensions")) or
+                (not self.__fileNameExtension and
+                 Preferences.getEditor("FullSpellCheckUnknown"))
             ):
                 return True
             else:
@@ -8349,10 +8301,7 @@
         wordEndPos = self.positionFromLineIndex(line, wordEnd)
         
         regExp = re.compile(r"\b{0}\b".format(word))
-        if forward:
-            startPos = wordEndPos
-        else:
-            startPos = wordStartPos
+        startPos = wordEndPos if forward else wordStartPos
         
         matches = [m for m in regExp.finditer(self.text())]
         if matches:
@@ -8471,7 +8420,7 @@
         key = (int(modifiers), int(button))
         
         self.vm.eventFilter(self, evt)
-        super(Editor, self).mouseReleaseEvent(evt)
+        super().mouseReleaseEvent(evt)
         
         if (
             button != Qt.MouseButton.NoButton and

eric ide

mercurial