eric6/QScintilla/Editor.py

branch
maintenance
changeset 7824
096b3ebc1409
parent 7737
5371a22cf2aa
parent 7790
32b8db5a1fb4
child 7850
e64b178499da
--- a/eric6/QScintilla/Editor.py	Sat Oct 03 11:14:23 2020 +0200
+++ b/eric6/QScintilla/Editor.py	Sun Nov 01 11:15:18 2020 +0100
@@ -7,16 +7,15 @@
 Module implementing the editor component of the eric6 IDE.
 """
 
-
 import os
 import re
 import difflib
 
 from PyQt5.QtCore import (
-    QDir, QTimer, QModelIndex, QFileInfo, pyqtSignal, pyqtSlot,
-    QCryptographicHash, QEvent, QDateTime, QRegExp, Qt, QPoint
+    pyqtSignal, pyqtSlot, Qt, QDir, QTimer, QModelIndex, QFileInfo,
+    QCryptographicHash, QEvent, QDateTime, QPoint
 )
-from PyQt5.QtGui import QCursor, QPalette, QFont, QPixmap, QPainter
+from PyQt5.QtGui import QPalette, QFont, QPixmap, QPainter
 from PyQt5.QtWidgets import (
     QLineEdit, QActionGroup, QDialog, QInputDialog, QApplication, QMenu
 )
@@ -25,9 +24,11 @@
 
 from E5Gui.E5Application import e5App
 from E5Gui import E5FileDialog, E5MessageBox
+from E5Gui.E5OverrideCursor import E5OverrideCursor
+
 from E5Utilities.E5Cache import E5Cache
 
-from .QsciScintillaCompat import QsciScintillaCompat, QSCINTILLA_VERSION
+from .QsciScintillaCompat import QsciScintillaCompat
 from .EditorMarkerMap import EditorMarkerMap
 from .SpellChecker import SpellChecker
 
@@ -1741,6 +1742,7 @@
         
         if language.startswith("Pygments|"):
             pyname = language
+            self.filetype = language.split("|")[-1]
             language = ""
         
         from . import Lexers
@@ -2463,7 +2465,7 @@
                     (self.fileName, ln),
                     (cond, temp, enabled, ignorecount),
                     self.condHistory, self, modal=True)
-                if dlg.exec_() == QDialog.Accepted:
+                if dlg.exec() == QDialog.Accepted:
                     cond, temp, enabled, ignorecount = dlg.getData()
                     self.breakpointModel.setBreakPointByIndex(
                         index, self.fileName, ln,
@@ -2656,7 +2658,7 @@
         printDialog = QPrintDialog(printer, self)
         if self.hasSelectedText():
             printDialog.setOption(QAbstractPrintDialog.PrintSelection, True)
-        if printDialog.exec_() == QDialog.Accepted:
+        if printDialog.exec() == QDialog.Accepted:
             sb.showMessage(self.tr('Printing...'))
             QApplication.processEvents()
             fn = self.getFileName()
@@ -2697,7 +2699,7 @@
             printer.setDocName(self.noName)
         preview = QPrintPreviewDialog(printer, self)
         preview.paintRequested.connect(self.__printPreview)
-        preview.exec_()
+        preview.exec()
     
     def __printPreview(self, printer):
         """
@@ -3076,56 +3078,52 @@
         @keyparam encoding encoding to be used to read the file (string)
             (Note: this parameter overrides encoding detection)
         """
-        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
-        
         self.__loadEditorConfig(fileName=fn)
         
         try:
-            if createIt and not os.path.exists(fn):
-                f = open(fn, "w")
-                f.close()
-            if encoding == "":
-                encoding = self.__getEditorConfig("DefaultEncoding",
-                                                  nodefault=True)
-            if encoding:
-                txt, self.encoding = Utilities.readEncodedFileWithEncoding(
-                    fn, encoding)
-            else:
-                txt, self.encoding = Utilities.readEncodedFile(fn)
+            with E5OverrideCursor():
+                if createIt and not os.path.exists(fn):
+                    with open(fn, "w"):
+                        pass
+                if encoding == "":
+                    encoding = self.__getEditorConfig("DefaultEncoding",
+                                                      nodefault=True)
+                if encoding:
+                    txt, self.encoding = Utilities.readEncodedFileWithEncoding(
+                        fn, encoding)
+                else:
+                    txt, self.encoding = Utilities.readEncodedFile(fn)
         except (UnicodeDecodeError, IOError) as why:
-            QApplication.restoreOverrideCursor()
             E5MessageBox.critical(
                 self.vm,
                 self.tr('Open File'),
                 self.tr('<p>The file <b>{0}</b> could not be opened.</p>'
                         '<p>Reason: {1}</p>')
                     .format(fn, str(why)))
-            QApplication.restoreOverrideCursor()
             raise
         
-        modified = False
-        
-        self.setText(txt)
-        
-        # get eric specific flags
-        self.__processFlags()
-        
-        # perform automatic EOL conversion
-        if (
-            self.__getEditorConfig("EOLMode", nodefault=True) or
-            Preferences.getEditor("AutomaticEOLConversion")
-        ):
-            self.convertEols(self.eolMode())
-        else:
-            fileEol = self.detectEolString(txt)
-            self.setEolModeByEolString(fileEol)
-        
-        self.extractTasks()
-        
-        QApplication.restoreOverrideCursor()
-        
-        self.setModified(modified)
-        self.lastModified = QFileInfo(self.fileName).lastModified()
+        with E5OverrideCursor():
+            modified = False
+            
+            self.setText(txt)
+            
+            # get eric specific flags
+            self.__processFlags()
+            
+            # perform automatic EOL conversion
+            if (
+                self.__getEditorConfig("EOLMode", nodefault=True) or
+                Preferences.getEditor("AutomaticEOLConversion")
+            ):
+                self.convertEols(self.eolMode())
+            else:
+                fileEol = self.detectEolString(txt)
+                self.setEolModeByEolString(fileEol)
+            
+            self.extractTasks()
+            
+            self.setModified(modified)
+            self.lastModified = QFileInfo(self.fileName).lastModified()
     
     def __convertTabs(self):
         """
@@ -3521,29 +3519,25 @@
         @return tuple with start and end indexes of the word at the position
             (integer, integer)
         """
-        text = self.text(line)
-        if self.caseSensitive():
-            cs = Qt.CaseSensitive
-        else:
-            cs = Qt.CaseInsensitive
         wc = self.wordCharacters()
         if wc is None or not useWordChars:
-            regExp = QRegExp(r'[^\w_]', cs)
+            pattern = r"\b[\w_]+\b"
         else:
             wc = re.sub(r'\w', "", wc)
-            regExp = QRegExp(r'[^\w{0}]'.format(re.escape(wc)), cs)
-        start = regExp.lastIndexIn(text, index) + 1
-        end = regExp.indexIn(text, index)
-        if start == end + 1 and index > 0:
-            # we are on a word boundary, try again
-            start = regExp.lastIndexIn(text, index - 1) + 1
-        if start == -1:
-            start = 0
-        if end == -1:
-            end = len(text)
-        
-        return (start, end)
-        
+            pattern = r"\b[\w{0}]+\b".format(re.escape(wc))
+        if self.caseSensitive():
+            rx = re.compile(pattern)
+        else:
+            rx = re.compile(pattern, re.IGNORECASE)
+        
+        text = self.text(line)
+        for match in rx.finditer(text):
+            start, end = match.span()
+            if start <= index <= end:
+                return (start, end)
+        
+        return (index, index)
+    
     def getWord(self, line, index, direction=0, useWordChars=True):
         """
         Public method to get the word at a position.
@@ -4409,6 +4403,8 @@
             Preferences.getEditor("ShowMarkerMapOnRight"))
         self.__markerMap.initColors()
         
+        self.setLanguage(self.fileName)
+        
         self.settingsRead.emit()
     
     def __setLineMarkerColours(self):
@@ -4593,8 +4589,7 @@
         self.caretWidth = Preferences.getEditor("CaretWidth")
         self.setCaretWidth(self.caretWidth)
         self.caretLineFrameWidth = Preferences.getEditor("CaretLineFrameWidth")
-        if QSCINTILLA_VERSION() >= 0x020B00:
-            self.setCaretLineFrameWidth(self.caretLineFrameWidth)
+        self.setCaretLineFrameWidth(self.caretLineFrameWidth)
         self.useMonospaced = Preferences.getEditor("UseMonospacedFont")
         self.setMonospaced(self.useMonospaced)
         edgeMode = Preferences.getEditor("EdgeMode")
@@ -6749,9 +6744,8 @@
             return  # user aborted
         
         try:
-            f = open(fname, "r", encoding="utf-8")
-            lines = f.readlines()
-            f.close()
+            with open(fname, "r", encoding="utf-8") as f:
+                lines = f.readlines()
         except IOError:
             E5MessageBox.critical(
                 self,
@@ -6810,10 +6804,9 @@
         fname = Utilities.toNativeSeparators(fname)
         
         try:
-            f = open(fname, "w", encoding="utf-8")
-            f.write("{0}{1}".format(name, "\n"))
-            f.write(self.macros[name].save())
-            f.close()
+            with open(fname, "w", encoding="utf-8") as f:
+                f.write("{0}{1}".format(name, "\n"))
+                f.write(self.macros[name].save())
         except IOError:
             E5MessageBox.critical(
                 self,
@@ -7420,7 +7413,7 @@
         """
         from Project.AddLanguageDialog import AddLanguageDialog
         dlg = AddLanguageDialog(self)
-        if dlg.exec_() == QDialog.Accepted:
+        if dlg.exec() == QDialog.Accepted:
             lang = dlg.getSelectedLanguage()
             line, index = self.getCursorPosition()
             self.insert('<qresource lang="{0}">\n</qresource>\n'.format(lang))
@@ -7790,7 +7783,7 @@
             cline, cindex = self.getCursorPosition()
             from .SpellCheckingDialog import SpellCheckingDialog
             dlg = SpellCheckingDialog(self.spell, 0, self.length(), self)
-            dlg.exec_()
+            dlg.exec()
             self.setCursorPosition(cline, cindex)
             if Preferences.getEditor("AutoSpellCheckingEnabled"):
                 self.spell.checkDocumentIncrementally()
@@ -7804,7 +7797,7 @@
         startPos = self.positionFromLineIndex(sline, sindex)
         endPos = self.positionFromLineIndex(eline, eindex)
         dlg = SpellCheckingDialog(self.spell, startPos, endPos, self)
-        dlg.exec_()
+        dlg.exec()
     
     def __checkSpellingWord(self):
         """
@@ -7816,7 +7809,7 @@
         wordStartPos = self.positionFromLineIndex(line, wordStart)
         wordEndPos = self.positionFromLineIndex(line, wordEnd)
         dlg = SpellCheckingDialog(self.spell, wordStartPos, wordEndPos, self)
-        dlg.exec_()
+        dlg.exec()
     
     def __showContextMenuSpelling(self):
         """
@@ -8231,7 +8224,7 @@
         
         from .SortOptionsDialog import SortOptionsDialog
         dlg = SortOptionsDialog()
-        if dlg.exec_() == QDialog.Accepted:
+        if dlg.exec() == QDialog.Accepted:
             ascending, alnum, caseSensitive = dlg.getData()
             origStartLine, origStartIndex, origEndLine, origEndIndex = (
                 self.getRectangularSelection()

eric ide

mercurial