Did some more string format conversions.

Thu, 29 Jul 2010 20:00:59 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Thu, 29 Jul 2010 20:00:59 +0200
changeset 432
497e188ee86e
parent 431
96cc7d322f89
child 433
988006cb898f

Did some more string format conversions.

Templates/TemplateViewer.py file | annotate | diff | comparison | revisions
Tools/TrayStarter.py file | annotate | diff | comparison | revisions
UI/BrowserModel.py file | annotate | diff | comparison | revisions
UI/CompareDialog.py file | annotate | diff | comparison | revisions
UI/DiffDialog.py file | annotate | diff | comparison | revisions
UI/EmailDialog.py file | annotate | diff | comparison | revisions
UI/FindFileDialog.py file | annotate | diff | comparison | revisions
UI/UserInterface.py file | annotate | diff | comparison | revisions
Utilities/Startup.py file | annotate | diff | comparison | revisions
Utilities/__init__.py file | annotate | diff | comparison | revisions
ViewManager/ViewManager.py file | annotate | diff | comparison | revisions
--- a/Templates/TemplateViewer.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/Templates/TemplateViewer.py	Thu Jul 29 20:00:59 2010 +0200
@@ -292,15 +292,15 @@
             else:
                 txt = txt.replace(var, val)
         sepchar = Preferences.getTemplates("SeparatorChar")
-        txt = txt.replace("%s%s" % (sepchar, sepchar), sepchar)
-        prefix = "%s%s" % (os.linesep, indent)
+        txt = txt.replace("{0}{1}".format(sepchar, sepchar), sepchar)
+        prefix = "{0}{1}".format(os.linesep, indent)
         trailingEol = txt.endswith(os.linesep)
         lines = txt.splitlines()
         lineCount = len(lines)
         lineLen = len(lines[-1])
         txt = prefix.join(lines).lstrip()
         if trailingEol:
-            txt = "%s%s" % (txt, os.linesep)
+            txt = "{0}{1}".format(txt, os.linesep)
             lineCount += 1
             lineLen = 0
         return txt, lineCount, lineLen
@@ -322,7 +322,7 @@
                     prefix = line[:ind]
                     postfix = line [ind + len(var):]
                     for v in val.splitlines():
-                        t = "%s%s%s%s%s" % (t, os.linesep, prefix, v, postfix)
+                        t = "{0}{1}{2}{3}{4}".format(t, os.linesep, prefix, v, postfix)
                 elif format == 'ml':
                     indent = line.replace(line.lstrip(), "")
                     prefix = line[:ind]
@@ -330,15 +330,15 @@
                     count = 0
                     for v in val.splitlines():
                         if count:
-                            t = "%s%s%s%s" % (t, os.linesep, indent, v)
+                            t = "{0}{1}{2}{3}".format(t, os.linesep, indent, v)
                         else:
-                            t = "%s%s%s%s" % (t, os.linesep, prefix, v)
+                            t = "{0}{1}{2}{3}".format(t, os.linesep, prefix, v)
                         count += 1
-                    t = "%s%s" % (t, postfix)
+                    t = "{0}{1}".format(t, postfix)
                 else:
-                    t = "%s%s%s" % (t, os.linesep, line)
+                    t = "{0}{1}{2}".format(t, os.linesep, line)
             else:
-                t = "%s%s%s" % (t, os.linesep, line)
+                t = "{0}{1}{2}".format(t, os.linesep, line)
         return "".join(t.splitlines(1)[1:])
 
     def getVariables(self):
@@ -355,8 +355,8 @@
         """
         sepchar = Preferences.getTemplates("SeparatorChar")
         variablesPattern = \
-            re.compile(r"""\%s[a-zA-Z][a-zA-Z0-9_]*(?::(?:ml|rl))?\%s""" % \
-                       (sepchar, sepchar))
+            re.compile(r"""\{0}[a-zA-Z][a-zA-Z0-9_]*(?::(?:ml|rl))?\{1}""".format(
+                       sepchar, sepchar))
         variables = variablesPattern.findall(self.template)
         self.variables = []
         self.formatedVariables = []
@@ -585,17 +585,15 @@
         editor = self.viewmanager.activeWindow()
         today = datetime.datetime.now().date()
         sepchar = Preferences.getTemplates("SeparatorChar")
-        if sepchar == '%':
-            sepchar = '%%'
-        keyfmt = sepchar + "%s" + sepchar
-        varValues = {keyfmt % 'date': today.isoformat(),
-                     keyfmt % 'year': str(today.year)}
+        keyfmt = sepchar + "{0}" + sepchar
+        varValues = {keyfmt.format('date'): today.isoformat(),
+                     keyfmt.format('year'): str(today.year)}
 
         if project.name:
-            varValues[keyfmt % 'project_name'] = project.name
+            varValues[keyfmt.format('project_name')] = project.name
 
         if project.ppath:
-            varValues[keyfmt % 'project_path'] = project.ppath
+            varValues[keyfmt.format('project_path')] = project.ppath
 
         path_name = editor.getFileName()
         if path_name:
@@ -604,27 +602,27 @@
             if ext:
                 ext = ext[1:]
             varValues.update({
-                    keyfmt % 'path_name': path_name,
-                    keyfmt % 'dir_name': dir_name,
-                    keyfmt % 'file_name': file_name,
-                    keyfmt % 'base_name': base_name,
-                    keyfmt % 'ext': ext
+                    keyfmt.format('path_name'): path_name,
+                    keyfmt.format('dir_name'): dir_name,
+                    keyfmt.format('file_name'): file_name,
+                    keyfmt.format('base_name'): base_name,
+                    keyfmt.format('ext'): ext
             })
         
-        varValues[keyfmt % 'clipboard:ml'] = QApplication.clipboard().text()
-        varValues[keyfmt % 'clipboard'] = QApplication.clipboard().text()
+        varValues[keyfmt.format('clipboard:ml')] = QApplication.clipboard().text()
+        varValues[keyfmt.format('clipboard')] = QApplication.clipboard().text()
 
         if editor.hasSelectedText():
-            varValues[keyfmt % 'cur_select:ml'] = editor.selectedText()
-            varValues[keyfmt % 'cur_select'] = editor.selectedText()
+            varValues[keyfmt.format('cur_select:ml')] = editor.selectedText()
+            varValues[keyfmt.format('cur_select')] = editor.selectedText()
         else:
-            varValues[keyfmt % 'cur_select:ml'] = os.linesep
-            varValues[keyfmt % 'cur_select'] = ""
+            varValues[keyfmt.format('cur_select:ml')] = os.linesep
+            varValues[keyfmt.format('cur_select')] = ""
 
-        varValues[keyfmt % 'insertion'] = "i_n_s_e_r_t_i_o_n"
+        varValues[keyfmt.format('insertion')] = "i_n_s_e_r_t_i_o_n"
         
-        varValues[keyfmt % 'select_start'] = "s_e_l_e_c_t_s_t_a_r_t"
-        varValues[keyfmt % 'select_end'] = "s_e_l_e_c_t_e_n_d"
+        varValues[keyfmt.format('select_start')] = "s_e_l_e_c_t_s_t_a_r_t"
+        varValues[keyfmt.format('select_end')] = "s_e_l_e_c_t_e_n_d"
 
         return varValues
 
--- a/Tools/TrayStarter.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/Tools/TrayStarter.py	Thu Jul 29 20:00:59 2010 +0200
@@ -211,94 +211,106 @@
         """
         Private slot to start the eric5 Mini Editor.
         """
-        self.__startProc("eric5-editor.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-editor.py", "--config={0}".format(
+            Utilities.getConfigDir()))
     
     def __startEric(self):
         """
         Private slot to start the eric5 IDE.
         """
-        self.__startProc("eric5.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startPreferences(self):
         """
         Private slot to start the eric5 configuration dialog.
         """
-        self.__startProc("eric5-configure.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-configure.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startPluginInstall(self):
         """
         Private slot to start the eric5 plugin installation dialog.
         """
-        self.__startProc("eric5-plugininstall.py", 
-                         "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-plugininstall.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startPluginUninstall(self):
         """
         Private slot to start the eric5 plugin uninstallation dialog.
         """
-        self.__startProc("eric5-pluginuninstall.py", 
-                         "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-pluginuninstall.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startPluginRepository(self):
         """
         Private slot to start the eric5 plugin repository dialog.
         """
-        self.__startProc("eric5-pluginrepository.py", 
-                         "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-pluginrepository.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startHelpViewer(self):
         """
         Private slot to start the eric5 web browser.
         """
-        self.__startProc("eric5-webbrowser.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-webbrowser.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startUIPreviewer(self):
         """
         Private slot to start the eric5 UI previewer.
         """
-        self.__startProc("eric5-uipreviewer.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-uipreviewer.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startTRPreviewer(self):
         """
         Private slot to start the eric5 translations previewer.
         """
-        self.__startProc("eric5-trpreviewer.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-trpreviewer.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startUnittest(self):
         """
         Private slot to start the eric5 unittest dialog.
         """
-        self.__startProc("eric5-unittest.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-unittest.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startDiff(self):
         """
         Private slot to start the eric5 diff dialog.
         """
-        self.__startProc("eric5-diff.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-diff.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startCompare(self):
         """
         Private slot to start the eric5 compare dialog.
         """
-        self.__startProc("eric5-compare.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-compare.py", "--config={0}".format(
+            Utilities.getConfigDir()))
     
     def __startSqlBrowser(self):
         """
         Private slot to start the eric5 sql browser dialog.
         """
-        self.__startProc("eric5-sqlbrowser.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-sqlbrowser.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startQRegExp(self):
         """
         Private slot to start the eric5 QRegExp editor dialog.
         """
-        self.__startProc("eric5-qregexp.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-qregexp.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __startPyRe(self):
         """
         Private slot to start the eric5 Python re editor dialog.
         """
-        self.__startProc("eric5-re.py", "--config=%s" % Utilities.getConfigDir())
+        self.__startProc("eric5-re.py", "--config={0}".format(
+            Utilities.getConfigDir()))
 
     def __showRecentProjectsMenu(self):
         """
@@ -313,11 +325,11 @@
         idx = 1
         for rp in self.recentProjects:
             if idx < 10:
-                formatStr = '&%d. %s'
+                formatStr = '&{0:d}. {1}'
             else:
-                formatStr = '%d. %s'
+                formatStr = '{0:d}. {1}'
             act = self.recentProjectsMenu.addAction(
-                formatStr % (idx, 
+                formatStr.format(idx, 
                     Utilities.compactPath(rp, self.maxMenuFilePathLen)))
             act.setData(rp)
             idx += 1
@@ -335,11 +347,11 @@
         idx = 1
         for rmp in self.recentMultiProjects:
             if idx < 10:
-                formatStr = '&%d. %s'
+                formatStr = '&{0:d}. {1}'
             else:
-                formatStr = '%d. %s'
+                formatStr = '{0:d}. {1}'
             act = self.recentMultiProjectsMenu.addAction(
-                formatStr % (idx, 
+                formatStr.format(idx, 
                     Utilities.compactPath(rmp, self.maxMenuFilePathLen)))
             act.setData(rmp)
             idx += 1
@@ -357,11 +369,11 @@
         idx = 1
         for rf in self.recentFiles:
             if idx < 10:
-                formatStr = '&%d. %s'
+                formatStr = '&{0:d}. {1}'
             else:
-                formatStr = '%d. %s'
+                formatStr = '{0:d}. {1}'
             act = self.recentFilesMenu.addAction(\
-                formatStr % (idx, 
+                formatStr.format(idx, 
                     Utilities.compactPath(rf, self.maxMenuFilePathLen)))
             act.setData(rf)
             idx += 1
--- a/UI/BrowserModel.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/UI/BrowserModel.py	Thu Jul 29 20:00:59 2010 +0200
@@ -1197,11 +1197,11 @@
                 try:
                     sname = sup.name
                     if sup.module != cl.module:
-                        sname = "%s.%s" % (sup.module, sname)
+                        sname = "{0}.{1}".format(sup.module, sname)
                 except AttributeError:
                     sname = sup
                 supers.append(sname)
-            name = name + "(%s)" % ", ".join(supers)
+            name = name + "({0})".format(", ".join(supers))
         
         BrowserItem.__init__(self, parent, name)
         
@@ -1221,10 +1221,11 @@
                 self.icon = UI.PixmapCache.getIcon("method_protected.png")
             else:
                 self.icon = UI.PixmapCache.getIcon("method.png")
-            self.itemData[0] = "%s(%s)" % (name, ", ".join(self._classObject.parameters))
+            self.itemData[0] = "{0}({1})".format(
+                name, ", ".join(self._classObject.parameters))
             # if no defaults are wanted
-            # ... % (name, ", ".join([e.split('=')[0].strip() \
-            #                        for e in self._classObject.parameters]))
+            # ....format(name, ", ".join([e.split('=')[0].strip() \
+            #                             for e in self._classObject.parameters]))
         elif self.ismodule:
             self.icon = UI.PixmapCache.getIcon("module.png")
         else:
@@ -1319,11 +1320,11 @@
             self.icon = UI.PixmapCache.getIcon("method_protected.png")
         else:
             self.icon = UI.PixmapCache.getIcon("method.png")
-        self.itemData[0] =  "%s(%s)" % \
-            (name, ", ".join(self._functionObject.parameters))
+        self.itemData[0] =  "{0}({1})".format(
+            name, ", ".join(self._functionObject.parameters))
         # if no defaults are wanted
-        # ... % (name, ", ".join(\
-        #       [e.split('=')[0].strip() for e in self._functionObject.parameters]))
+        # ....format(name, ", ".join(\
+        #            [e.split('=')[0].strip() for e in self._functionObject.parameters]))
         if self._functionObject and \
            (self._functionObject.methods or self._functionObject.classes):
             self._populated = False
--- a/UI/CompareDialog.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/UI/CompareDialog.py	Thu Jul 29 20:00:59 2010 +0200
@@ -51,24 +51,24 @@
             .replace('\0^', "")\
             .replace('\1', "")
 
-    linenumberformat = "%%%dd" % linenumberwidth
+    linenumberformat = "{{0:{0:d}d}}".format(linenumberwidth)
     emptylineno = ' ' * linenumberwidth
     
     for (ln1, l1), (ln2, l2), flag in _mdiff(a, b, None, None, IS_CHARACTER_JUNK):
         if not flag:
-            yield ('e', linenumberformat % ln1, l1,
-                        linenumberformat % ln2, l2)
+            yield ('e', linenumberformat.format(ln1), l1,
+                        linenumberformat.format(ln2), l2)
             continue
         if ln2 == "" and l2 == "\n":
-            yield ('d', linenumberformat % ln1, removeMarkers(l1),
+            yield ('d', linenumberformat.format(ln1), removeMarkers(l1),
                         emptylineno, '\n')
             continue
         if ln1 == "" and l1 == "\n":
             yield ('i', emptylineno, '\n',
-                        linenumberformat % ln2, removeMarkers(l2))
+                        linenumberformat.format(ln2), removeMarkers(l2))
             continue
-        yield ('r', linenumberformat % ln1, l1,
-                    linenumberformat % ln2, l2)
+        yield ('r', linenumberformat.format(ln1), l1,
+                    linenumberformat.format(ln2), l2)
 
 class CompareDialog(QWidget, Ui_CompareDialog):
     """
@@ -185,7 +185,7 @@
         pane.setTextCursor(tc)
         pane.setCurrentCharFormat(format)
         if interLine:
-            pane.insertPlainText("%s " % linenumber)
+            pane.insertPlainText("{0} ".format(linenumber))
             for txt in re.split(self.markerPattern, line):
                 if txt:
                     if txt.count('\1'):
@@ -201,7 +201,7 @@
                     pane.setCurrentCharFormat(self.cNormalFormat)
                     pane.insertPlainText(txt)
         else:
-            pane.insertPlainText("%s %s" % (linenumber, line))
+            pane.insertPlainText("{0} {1}".format(linenumber, line))
 
     def on_buttonBox_clicked(self, button):
         """
--- a/UI/DiffDialog.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/UI/DiffDialog.py	Thu Jul 29 20:00:59 2010 +0200
@@ -77,11 +77,12 @@
     started = False
     for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
         if not started:
-            yield '--- %s\t%s%s' % (fromfile, fromfiledate, lineterm)
-            yield '+++ %s\t%s%s' % (tofile, tofiledate, lineterm)
+            yield '--- {0}\t{1}{2}'.format(fromfile, fromfiledate, lineterm)
+            yield '+++ {0}\t{1}{2}'.format(tofile, tofiledate, lineterm)
             started = True
         i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
-        yield "@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm)
+        yield "@@ -{0:d},{1:d} +{2:d},{3:d} @@{4}".format(
+            i1+1, i2-i1, j1+1, j2-j1, lineterm)
         for tag, i1, i2, j1, j2 in group:
             if tag == 'equal':
                 for line in a[i1:i2]:
@@ -156,15 +157,15 @@
     prefixmap = {'insert':'+ ', 'delete':'- ', 'replace':'! ', 'equal':'  '}
     for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
         if not started:
-            yield '*** %s\t%s%s' % (fromfile, fromfiledate, lineterm)
-            yield '--- %s\t%s%s' % (tofile, tofiledate, lineterm)
+            yield '*** {0}\t{1}{2}'.format(fromfile, fromfiledate, lineterm)
+            yield '--- {0}\t{1}{2}'.format(tofile, tofiledate, lineterm)
             started = True
 
-        yield '***************%s' % (lineterm,)
+        yield '***************{0}'.format(lineterm)
         if group[-1][2] - group[0][1] >= 2:
-            yield '*** %d,%d ****%s' % (group[0][1]+1, group[-1][2], lineterm)
+            yield '*** {0:d},{1:d} ****{2}'.format(group[0][1]+1, group[-1][2], lineterm)
         else:
-            yield '*** %d ****%s' % (group[-1][2], lineterm)
+            yield '*** {0:d} ****{1}'.format(group[-1][2], lineterm)
         visiblechanges = [e for e in group if e[0] in ('replace', 'delete')]
         if visiblechanges:
             for tag, i1, i2, _, _ in group:
@@ -173,9 +174,9 @@
                         yield prefixmap[tag] + line
 
         if group[-1][4] - group[0][3] >= 2:
-            yield '--- %d,%d ----%s' % (group[0][3]+1, group[-1][4], lineterm)
+            yield '--- {0:d},{1:d} ----{2}'.format(group[0][3]+1, group[-1][4], lineterm)
         else:
-            yield '--- %d ----%s' % (group[-1][4], lineterm)
+            yield '--- {0:d} ----{1}'.format(group[-1][4], lineterm)
         visiblechanges = [e for e in group if e[0] in ('replace', 'insert')]
         if visiblechanges:
             for tag, _, _, j1, j2 in group:
@@ -265,7 +266,7 @@
         """
         dname, fname = Utilities.splitPath(self.filename2)
         if fname != '.':
-            fname = "%s.diff" % self.filename2
+            fname = "{0}.diff".format(self.filename2)
         else:
             fname = dname
             
--- a/UI/EmailDialog.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/UI/EmailDialog.py	Thu Jul 29 20:00:59 2010 +0200
@@ -191,16 +191,16 @@
         
         @return string containing the mail message
         """
-        msgtext = "%s\r\n----\r\n%s----\r\n%s----\r\n%s" % \
-            (self.message.toPlainText(), 
-             Utilities.generateVersionInfo("\r\n"), 
-             Utilities.generatePluginsVersionInfo("\r\n"), 
-             Utilities.generateDistroInfo("\r\n"))
+        msgtext = "{0}\r\n----\r\n{1}----\r\n{2}----\r\n{3}".format(
+            self.message.toPlainText(), 
+            Utilities.generateVersionInfo("\r\n"), 
+            Utilities.generatePluginsVersionInfo("\r\n"), 
+            Utilities.generateDistroInfo("\r\n"))
         
         msg = self.__encodedText(msgtext)
         msg['From']    = Preferences.getUser("Email")
         msg['To']      = self.__toAddress
-        subject = '[eric5] %s' % self.subject.text()
+        subject = '[eric5] {0}'.format(self.subject.text())
         msg['Subject'] = self.__encodedHeader(subject)
         
         return msg.as_string()
@@ -215,17 +215,17 @@
             "If you see this message, your mail client is not "
             "capable of displaying the attachments.")
         
-        msgtext = "%s\r\n----\r\n%s----\r\n%s----\r\n%s" % \
-            (self.message.toPlainText(), 
-             Utilities.generateVersionInfo("\r\n"), 
-             Utilities.generatePluginsVersionInfo("\r\n"), 
-             Utilities.generateDistroInfo("\r\n"))
+        msgtext = "{0}\r\n----\r\n{1}----\r\n{2}----\r\n{3}".format(
+            self.message.toPlainText(), 
+            Utilities.generateVersionInfo("\r\n"), 
+            Utilities.generatePluginsVersionInfo("\r\n"), 
+            Utilities.generateDistroInfo("\r\n"))
         
         # first part of multipart mail explains format
         msg = MIMEMultipart()
         msg['From']    = Preferences.getUser("Email")
         msg['To']      = self.__toAddress
-        subject = '[eric5] %s' % self.subject.text()
+        subject = '[eric5] {0}'.format(self.subject.text())
         msg['Subject'] = self.__encodedHeader(subject)
         msg.preamble = mpPreamble
         msg.epilogue = ''
--- a/UI/FindFileDialog.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/UI/FindFileDialog.py	Thu Jul 29 20:00:59 2010 +0200
@@ -135,7 +135,7 @@
                 # Qt bug: 
                 # item is not user checkable if setFirstColumnSpanned is True (< 4.5.0)
         
-        itm = QTreeWidgetItem(self.__lastFileItem, [' %5d ' % line, text])
+        itm = QTreeWidgetItem(self.__lastFileItem, [' {0:5d} '.format(line), text])
         itm.setTextAlignment(0,  Qt.AlignRight)
         itm.setData(0, self.lineRole, line)
         itm.setData(0, self.startRole, start)
@@ -271,7 +271,7 @@
         
         if self.filterCheckBox.isChecked():
             fileFilter = self.filterEdit.text()
-            fileFilterList = ["^%s$" % filter.replace(".", "\.").replace("*", ".*") \
+            fileFilterList = ["^{0}$".format(filter.replace(".", "\.").replace("*", ".*")) \
                               for filter in fileFilter.split(";")]
             filterRe = re.compile("|".join(fileFilterList))
         
@@ -295,7 +295,7 @@
                 filters = []
                 if self.sourcesCheckBox.isChecked():
                     filters.extend(
-                        ["^%s$" % assoc.replace(".", "\.").replace("*", ".*") \
+                        ["^{0}$".format(assoc.replace(".", "\.").replace("*", ".*")) \
                          for assoc in list(Preferences.getEditorLexerAssocs().keys()) \
                          if assoc not in self.formsExt + self.interfacesExt])
                 if self.formsCheckBox.isChecked():
@@ -326,7 +326,7 @@
         else:
             txt = re.escape(ct)
         if wo:
-            txt = "\\b%s\\b" % txt
+            txt = "\\b{0}\\b".format(txt)
         flags = re.UNICODE | re.LOCALE
         if not cs:
             flags |= re.IGNORECASE
@@ -413,11 +413,11 @@
                     else:
                         rline = ""
                     if len(line) > 1024:
-                        line = "%s ..." % line[:1024]
+                        line = "{0} ...".format(line[:1024])
                     if self.__replaceMode:
                         if len(rline) > 1024:
-                            rline = "%s ..." % line[:1024]
-                        line = "- %s\n+ %s" % (line, rline)
+                            rline = "{0} ...".format(line[:1024])
+                        line = "- {0}\n+ {1}".format(line, rline)
                     self.__createItem(file, count, line, start, end, rline)
                     
                     if self.feelLikeCheckBox.isChecked():
--- a/UI/UserInterface.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/UI/UserInterface.py	Thu Jul 29 20:00:59 2010 +0200
@@ -725,7 +725,7 @@
             self.__createFloatingWindowsLayout(debugServer)
         
         else:
-            raise RuntimeError("wrong layout type given (%s)" % self.layout)
+            raise RuntimeError("wrong layout type given ({0})".format(self.layout))
         logging.debug("Created Layout")
 
     def __createFloatingWindowsLayout(self, debugServer):
@@ -1265,7 +1265,7 @@
                 if argsStr is None:
                     argsStr = arg
                 else:
-                    argsStr = "%s %s" % (argsStr, arg)
+                    argsStr = "{0} {1}".format(argsStr, arg)
                 continue
 
             ext = os.path.splitext(arg)[1]
@@ -1348,12 +1348,12 @@
             if not self.capProject and not self.capEditor:
                 self.setWindowTitle(Program)
             elif self.capProject and not self.capEditor:
-                self.setWindowTitle("%s - %s" % (self.capProject, Program))
+                self.setWindowTitle("{0} - {1}".format(self.capProject, Program))
             elif not self.capProject and self.capEditor:
-                self.setWindowTitle("%s - %s" % (self.capEditor, Program))
+                self.setWindowTitle("{0} - {1}".format(self.capEditor, Program))
             else:
-                self.setWindowTitle("%s - %s - %s" % \
-                    (self.capProject, self.capEditor, Program))
+                self.setWindowTitle("{0} - {1} - {2}".format(
+                    self.capProject, self.capEditor, Program))
         
     def __initActions(self):
         """
@@ -1871,7 +1871,7 @@
         
         # check for Qt4 designer and linguist
         designerExe = Utilities.isWindowsPlatform() and \
-            "%s.exe" % Utilities.generateQtToolName("designer") or \
+            "{0}.exe".format(Utilities.generateQtToolName("designer")) or \
             Utilities.generateQtToolName("designer")
         if Utilities.isinpath(designerExe):
             self.designer4Act = E5Action(self.trUtf8('Qt-Designer 4'), 
@@ -1888,7 +1888,7 @@
             self.designer4Act = None
         
         linguistExe = Utilities.isWindowsPlatform() and \
-            "%s.exe" % Utilities.generateQtToolName("linguist") or \
+            "{0}.exe".format(Utilities.generateQtToolName("linguist")) or \
             Utilities.generateQtToolName("linguist")
         if Utilities.isinpath(linguistExe):
             self.linguist4Act = E5Action(self.trUtf8('Qt-Linguist 4'), 
@@ -2662,7 +2662,7 @@
                 if tool['menutext'] != '--':
                     act = QAction(UI.PixmapCache.getIcon(tool['icon']), tool['menutext'], 
                                   self)
-                    act.setObjectName("%s@@%s" % (toolGroup[0], 
+                    act.setObjectName("{0}@@{1}".format(toolGroup[0], 
                                       tool['menutext']))
                     self.connect(act, SIGNAL("triggered()"), self.__toolActionTriggered)
                     self.toolGroupActions[act.objectName()] = act
@@ -2674,7 +2674,7 @@
         Private method to update the external tools actions for the current tool group.
         """
         toolGroup = self.toolGroups[self.currentToolGroup]
-        groupkey = "%s@@" % toolGroup[0]
+        groupkey = "{0}@@".format(toolGroup[0])
         groupActionKeys = []
         # step 1: get actions for this group
         for key in self.toolGroupActions:
@@ -2685,7 +2685,7 @@
         ckeys = []
         for tool in toolGroup[1]:
             if tool['menutext'] != '--':
-                ckeys.append("%s@@%s" % (toolGroup[0], tool['menutext']))
+                ckeys.append("{0}@@{1}".format(toolGroup[0], tool['menutext']))
         
         # step 3: remove all actions not configured any more
         for key in groupActionKeys:
@@ -2699,7 +2699,7 @@
         category = self.trUtf8("External Tools/{0}").format(toolGroup[0])
         for tool in toolGroup[1]:
             if tool['menutext'] != '--':
-                key = "%s@@%s" % (toolGroup[0], tool['menutext'])
+                key = "{0}@@{1}".format(toolGroup[0], tool['menutext'])
                 if key not in groupActionKeys:
                     act = QAction(UI.PixmapCache.getIcon(tool['icon']), tool['menutext'], 
                                   self)
@@ -2868,12 +2868,12 @@
             if deleteAttachFile:
                 os.remove(attachFile)
         else:
-            body = "\r\n----\r\n%s----\r\n%s----\r\n%s" % \
-                (Utilities.generateVersionInfo("\r\n"), 
-                 Utilities.generatePluginsVersionInfo("\r\n"), 
-                 Utilities.generateDistroInfo("\r\n"))
-        
-        url = QUrl("mailto:%s" % address)
+            body = "\r\n----\r\n{0}----\r\n{1}----\r\n{2}".format(
+                Utilities.generateVersionInfo("\r\n"), 
+                Utilities.generatePluginsVersionInfo("\r\n"), 
+                Utilities.generateDistroInfo("\r\n"))
+        
+        url = QUrl("mailto:{0}".format(address))
         url.addQueryItem("subject", subject)
         url.addQueryItem("body", body)
         QDesktopServices.openUrl(url)
@@ -3047,7 +3047,7 @@
             already registered
         """
         if name in self.__toolbars:
-            raise KeyError("Toolbar '%s' already registered." % name)
+            raise KeyError("Toolbar '{0}' already registered.".format(name))
         
         self.__toolbars[name] = [text, toolbar]
         
@@ -4531,7 +4531,7 @@
                toolProcData[1] not in ["insert", "replaceSelection"]: 
                 # not connected to an editor or wrong mode
                 while toolProc.canReadLine():
-                    s = "%s - " % program
+                    s = "{0} - ".format(program)
                     output = str(toolProc.readLine(), ioEncoding, 'replace')
                     s.append(output)
                     self.appendToStdout(s)
@@ -4554,7 +4554,7 @@
             toolProc.setReadChannel(QProcess.StandardError)
             
             while toolProc.canReadLine():
-                s = "%s - " % program
+                s = "{0} - ".format(program)
                 error = str(toolProc.readLine(), ioEncoding, 'replace')
                 s.append(error)
                 self.appendToStderr(s)
@@ -4605,8 +4605,8 @@
                 
                 if Utilities.isWindowsPlatform() and not os.path.exists(home):
                     pyversion = sys.hexversion >> 16
-                    vers = "%d%d" % ((pyversion >> 8) & 0xff, pyversion & 0xff)
-                    home = os.path.join(pythonDocDir, "python%s.chm" % vers)
+                    vers = "{0:d}{1:d}".format((pyversion >> 8) & 0xff, pyversion & 0xff)
+                    home = os.path.join(pythonDocDir, "python{0}.chm".format(vers))
             else:
                 home = pythonDocDir
             
--- a/Utilities/Startup.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/Utilities/Startup.py	Thu Jul 29 20:00:59 2010 +0200
@@ -62,13 +62,13 @@
     options.extend(appinfo["options"])
     
     print("""
-Usage: %(bin)s [OPTIONS] %(arg)s
+Usage: {bin} [OPTIONS] {arg}
 
-%(name)s - %(description)s
+{name} - {description}
     
-Options:""" % appinfo)
+Options:""".format(**appinfo))
     for opt in options:
-        print("  %s  %s" % (opt[0].ljust(optlen), opt[1]))
+        print("  {0}  {1}".format(opt[0].ljust(optlen), opt[1]))
     sys.exit(0)
 
 def version(appinfo):
@@ -78,14 +78,14 @@
     @param appinfo dictionary describing the application
     """
     print("""
-%(name)s %(version)s
+{name} {version}
 
-%(description)s
+{description}
 
 Copyright (c) 2002 - 2010 Detlev Offenbach <detlev@die-offenbachs.de>
 This is free software; see LICENSE.GPL3 for copying conditions.
 There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
-PARTICULAR PURPOSE.""" % appinfo)
+PARTICULAR PURPOSE.""".format(**appinfo))
     sys.exit(0)
 
 def handleArgs(argv, appinfo):
@@ -182,7 +182,7 @@
             dirs.append(qtTransDir)
 
         loca = loc
-        for tf in ["%s_%s" % (tr, loc) for tr in translations]:
+        for tf in ["{0}_{1}".format(tr, loc) for tr in translations]:
             translator, ok = loadTranslatorForLocale(dirs, tf)
             loaded_translators[tf] = translator
             if ok:
--- a/Utilities/__init__.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/Utilities/__init__.py	Thu Jul 29 20:00:59 2010 +0200
@@ -189,7 +189,7 @@
             guess = ThirdParty.CharDet.chardet.detect(text)
             if guess and guess['confidence'] > 0.95 and guess['encoding'] is not None:
                 codec = guess['encoding'].lower()
-                return str(text, codec), '%s-guessed' % codec
+                return str(text, codec), '{0}-guessed'.format(codec)
         except (UnicodeError, LookupError):
             pass
         except ImportError:
@@ -198,7 +198,7 @@
     # Try default encoding
     try:
         codec = Preferences.getEditor("DefaultEncoding")
-        return str(text, codec), '%s-default' % codec
+        return str(text, codec), '{0}-default'.format(codec)
     except (UnicodeError, LookupError):
         pass
     
@@ -207,7 +207,7 @@
         if guess and guess['encoding'] is not None:
             try:
                 codec = guess['encoding'].lower()
-                return str(text, codec), '%s-guessed' % codec
+                return str(text, codec), '{0}-guessed'.format(codec)
             except (UnicodeError, LookupError):
                 pass
     
@@ -305,7 +305,7 @@
     char = m.group()
     text = map.get(char)
     if text is None:
-        text = "&#%d;" % ord(char)
+        text = "&#{0:d};".format(ord(char))
     return text
     
 def html_encode(text, pattern=_escape):
@@ -331,7 +331,7 @@
     @return the converted text (string)
     """
     char = m.group()
-    text = "&#%d;" % ord(char)
+    text = "&#{0:d};".format(ord(char))
     return text
     
 def html_uencode(text, pattern=_uescape):
@@ -578,7 +578,7 @@
     @return the complete filename (string)
     """
     if ext[0] != ".":
-        ext = ".%s" % ext # require leading separator, to match os.path.splitext
+        ext = ".{0}".format(ext) # require leading separator, to match os.path.splitext
     return prefix + EXTSEP + ext[1:]
 
 def compactPath(path, width, measure = len):
@@ -601,7 +601,7 @@
     head2 = head[mid:]
     while head1:
         # head1 is same size as head2 or one shorter
-        path = os.path.join("%s%s%s" % (head1, ellipsis, head2), tail)
+        path = os.path.join("{0}{1}{2}".format(head1, ellipsis, head2), tail)
         if measure(path) <= width:
             return path
         head1 = head1[:-1]
@@ -610,7 +610,7 @@
     if measure(path) <= width:
         return path
     while tail:
-        path = "%s%s" % (ellipsis, tail)
+        path = "{0}{1}".format(ellipsis, tail)
         if measure(path) <= width:
             return path
         tail = tail[1:]
@@ -708,7 +708,7 @@
     @return filename of the corresponding unittest file (string)
     """
     dn, fn = os.path.split(fn)
-    return os.path.join(dn, "test%s" % fn)
+    return os.path.join(dn, "test{0}".format(fn))
 
 def parseOptionString(s):
     """
@@ -778,7 +778,7 @@
             column = -1
         else:
             column = aw.getCursorPosition()[1]
-        return "%d" % column
+        return "{0:d}".format(column)
     elif code in ["D", "%D"]:
         # directory of active editor
         aw = e5App().getObject("ViewManager").activeWindow()
@@ -811,7 +811,7 @@
             line = 0
         else:
             line = aw.getCursorPosition()[0] + 1
-        return "%d" % line
+        return "{0:d}".format(line)
     elif code in ["P", "%P"]:
         # project path
         projectPath = e5App().getObject("Project").getProjectPath()
@@ -961,7 +961,7 @@
         import traceback, re
         lines = traceback.format_exception_only(SyntaxError, detail)
         match = re.match('\s*File "(.+)", line (\d+)', 
-            lines[0].replace('<string>', '%s' % file))
+            lines[0].replace('<string>', '{0}'.format(file)))
         if match is not None:
             fn, line = match.group(1, 2)
             if lines[1].startswith('SyntaxError:'):
@@ -1045,7 +1045,7 @@
     @return the requested entry or the default value, if the entry wasn't 
         found (string or None)
     """
-    filter = QRegExp("^%s[ \t]*=" % key)
+    filter = QRegExp("^{0}[ \t]*=".format(key))
     if isWindowsPlatform():
         filter.setCaseSensitivity(Qt.CaseInsensitive)
     
@@ -1064,7 +1064,7 @@
     @param key key of the requested environment entry (string)
     @return flag indicating the presence of the requested entry (boolean)
     """
-    filter = QRegExp("^%s[ \t]*=" % key)
+    filter = QRegExp("^{0}[ \t]*=".format(key))
     if isWindowsPlatform():
         filter.setCaseSensitivity(Qt.CaseInsensitive)
     
@@ -1082,10 +1082,10 @@
     @param toolname base name of the tool (string)
     @return the Qt tool name without extension (string)
     """
-    return "%s%s%s" % (Preferences.getQt("QtToolsPrefix4"), 
-                       toolname, 
-                       Preferences.getQt("QtToolsPostfix4")
-                      )
+    return "{0}{1}{2}".format(Preferences.getQt("QtToolsPrefix4"), 
+                              toolname, 
+                              Preferences.getQt("QtToolsPostfix4")
+                             )
 
 def prepareQtMacBundle(toolname, version, args):
     """
@@ -1128,21 +1128,21 @@
     except ImportError:
         sip_version_str = "sip version not available"
     
-    info =  "Version Numbers:%s  Python %s%s" % \
-        (linesep, sys.version.split()[0], linesep)
-    info += "  Qt %s%s  PyQt4 %s%s" % \
-        (qVersion(), linesep, PYQT_VERSION_STR, linesep)
-    info += "  sip %s%s  QScintilla %s%s" % \
-        (sip_version_str, linesep, QSCINTILLA_VERSION_STR, linesep)
+    info =  "Version Numbers:{0}  Python {1}{2}".format(
+        linesep, sys.version.split()[0], linesep)
+    info += "  Qt {0}{1}  PyQt4 {2}{3}".format(
+        qVersion(), linesep, PYQT_VERSION_STR, linesep)
+    info += "  sip {0}{1}  QScintilla {2}{3}".format(
+        sip_version_str, linesep, QSCINTILLA_VERSION_STR, linesep)
     try:
         from PyQt4.QtWebKit import qWebKitVersion
-        info += "  WebKit %s%s" % (qWebKitVersion(), linesep)
+        info += "  WebKit {0}{1}".format(qWebKitVersion(), linesep)
     except ImportError:
         pass
-    info += "  %s %s%s" % \
-        (Program, Version, linesep * 2)
-    info += "Platform: %s%s%s%s" % \
-        (sys.platform, linesep, sys.version, linesep)
+    info += "  {0} {1}{2}".format(
+        Program, Version, linesep * 2)
+    info += "Platform: {0}{1}{2}{3}".format(
+        sys.platform, linesep, sys.version, linesep)
     
     return info
 
@@ -1162,9 +1162,10 @@
             for info in pm.getPluginInfos():
                 versions[info[0]] = info[2]
             
-            infoStr = "Plugins Version Numbers:%s" % linesep
+            infoStr = "Plugins Version Numbers:{0}".format(linesep)
             for pluginName in sorted(versions.keys()):
-                infoStr += "  %s %s%s" % (pluginName, versions[pluginName], linesep)
+                infoStr += "  {0} {1}{2}".format(
+                           pluginName, versions[pluginName], linesep)
         except KeyError:
             pass
     
@@ -1181,7 +1182,7 @@
     if sys.platform.startswith("linux"):
         releaseList = glob.glob("/etc/*-release")
         if releaseList:
-            infoStr = "Distribution Info:%s" % linesep
+            infoStr = "Distribution Info:{0}".format(linesep)
             infoParas = []
             for rfile in releaseList:
                 try:
--- a/ViewManager/ViewManager.py	Thu Jul 29 18:34:15 2010 +0200
+++ b/ViewManager/ViewManager.py	Thu Jul 29 20:00:59 2010 +0200
@@ -3609,11 +3609,11 @@
         idx = 1
         for rs in self.recent:
             if idx < 10:
-                formatStr = '&%d. %s'
+                formatStr = '&{0:d}. {1}'
             else:
-                formatStr = '%d. %s'
+                formatStr = '{0:d}. {1}'
             act = self.recentMenu.addAction(\
-                formatStr % (idx, 
+                formatStr.format(idx, 
                     Utilities.compactPath(rs, self.ui.maxMenuFilePathLen)))
             act.setData(rs)
             act.setEnabled(QFileInfo(rs).exists())
@@ -4366,9 +4366,9 @@
         for filename in sorted(filenames):
             editor = self.getOpenEditor(filename)
             for bookmark in editor.getBookmarks():
-                bmSuffix = " : %d" % bookmark
+                bmSuffix = " : {0:d}".format(bookmark)
                 act = self.bookmarksMenu.addAction(
-                    "%s%s" % (
+                    "{0}{1}".format(
                         Utilities.compactPath(
                             filename,
                             self.ui.maxMenuFilePathLen - len(bmSuffix)), 
@@ -4905,7 +4905,7 @@
         if self.activeWindow() is not None and \
            self.activeWindow().getFileName():
             ext = os.path.splitext(self.activeWindow().getFileName())[1]
-            rx = QRegExp(".*\*\.%s[ )].*" % ext[1:])
+            rx = QRegExp(".*\*\.{0}[ )].*".format(ext[1:]))
             filters = QScintilla.Lexers.getOpenFileFiltersList()
             index = -1
             for i in range(len(filters)):

eric ide

mercurial