src/eric7/Utilities/__init__.py

branch
eric7-maintenance
changeset 10460
3b34efa2857c
parent 10349
df7edc29cbfb
parent 10439
21c28b0f9e41
child 10534
783d835d7fe4
--- a/src/eric7/Utilities/__init__.py	Sun Dec 03 14:54:00 2023 +0100
+++ b/src/eric7/Utilities/__init__.py	Mon Jan 01 11:10:45 2024 +0100
@@ -1,6 +1,6 @@
 # -*- coding: utf-8 -*-
 
-# Copyright (c) 2003 - 2023 Detlev Offenbach <detlev@die-offenbachs.de>
+# Copyright (c) 2003 - 2024 Detlev Offenbach <detlev@die-offenbachs.de>
 #
 
 """
@@ -46,12 +46,18 @@
     Module function to raise a SyntaxError for a SyntaxWarning.
 
     @param message warning object
+    @type Class
     @param category type object of the warning
-    @param filename name of the file causing the warning (string)
-    @param lineno line number causing the warning (integer)
+    @type SyntaxWarning
+    @param filename name of the file causing the warning
+    @type str
+    @param lineno line number causing the warning
+    @type int
     @param file file to write the warning message to (ignored)
+    @type file
     @param line line causing the warning (ignored)
-    @raise err exception of type SyntaxError
+    @type int
+    @exception err exception of type SyntaxError
     """
     if category is SyntaxWarning:
         err = SyntaxError(str(message))
@@ -172,7 +178,8 @@
         """
         Constructor
 
-        @param coding coding to include in the message (string)
+        @param coding coding to include in the message
+        @type str
         """
         self.errorMessage = QCoreApplication.translate(
             "CodingError", "The coding '{0}' is wrong for the given text."
@@ -183,6 +190,7 @@
         Special method returning a representation of the exception.
 
         @return string representing the error message
+        @rtype str
         """
         return str(self.errorMessage)
 
@@ -191,6 +199,7 @@
         Special method returning a string representation of the exception.
 
         @return string representing the error message
+        @rtype str
         """
         return str(self.errorMessage)
 
@@ -199,8 +208,10 @@
     """
     Function to get the coding of a bytes text.
 
-    @param text bytes text to inspect (bytes)
+    @param text bytes text to inspect
+    @type bytes
     @return coding string
+    @rtype str
     """
     lines = text.splitlines()
     for coding in codingBytes_regexps:
@@ -217,8 +228,10 @@
     """
     Function to get the coding of a text.
 
-    @param text text to inspect (string)
+    @param text text to inspect
+    @type str
     @return coding string
+    @rtype str
     """
     lines = text.splitlines()
     for coding in coding_regexps:
@@ -235,8 +248,10 @@
     """
     Function to read a file and decode its contents into proper text.
 
-    @param filename name of the file to read (string)
-    @return tuple of decoded text and encoding (string, string)
+    @param filename name of the file to read
+    @type str
+    @return tuple of decoded text and encoding
+    @rtype tuple of (str, str)
     """
     with open(filename, "rb") as f:
         text = f.read()
@@ -248,9 +263,10 @@
     Function to read a file, calculate a hash value and decode its contents
     into proper text.
 
-    @param filename name of the file to read (string)
-    @return tuple of decoded text, encoding and hash value (string, string,
-        string)
+    @param filename name of the file to read
+    @type str
+    @return tuple of decoded text, encoding and hash value
+    @rtype tuple of (str, str, str)
     """
     with open(filename, "rb") as f:
         text = f.read()
@@ -267,8 +283,10 @@
     """
     Function to decode some byte text into a string.
 
-    @param text byte text to decode (bytes)
-    @return tuple of decoded text and encoding (string, string)
+    @param text byte text to decode
+    @type bytes
+    @return tuple of decoded text and encoding
+    @rtype tuple of (str, str)
     """
     with contextlib.suppress(UnicodeError, LookupError):
         if text.startswith(BOM_UTF8):
@@ -324,9 +342,12 @@
     """
     Function to read a file and decode its contents into proper text.
 
-    @param filename name of the file to read (string)
-    @param encoding encoding to be used to read the file (string)
-    @return tuple of decoded text and encoding (string, string)
+    @param filename name of the file to read
+    @type str
+    @param encoding encoding to be used to read the file
+    @type str
+    @return tuple of decoded text and encoding
+    @rtype tuple of (str, str)
     """
     with open(filename, "rb") as f:
         text = f.read()
@@ -438,8 +459,10 @@
     """
     Function to decode a string containing Unicode encoded characters.
 
-    @param text text containing encoded chars (string)
-    @return decoded text (string)
+    @param text text containing encoded chars
+    @type str
+    @return decoded text
+    @rtype str
     """
     buf = b""
     index = 0
@@ -459,8 +482,10 @@
     """
     Function to decode some byte text into a string.
 
-    @param buffer byte buffer to decode (bytes)
-    @return decoded text (string)
+    @param buffer byte buffer to decode
+    @type bytes
+    @return decoded text
+    @rtype str
     """
     # try UTF with BOM
     with contextlib.suppress(UnicodeError, LookupError):
@@ -496,8 +521,10 @@
     """
     Module function to read a string from the given stream.
 
-    @param stream data stream opened for reading (QDataStream)
-    @return string read from the stream (string)
+    @param stream data stream opened for reading
+    @type QDataStream
+    @return string read from the stream
+    @rtype str
     """
     data = stream.readString()
     if data is None:
@@ -509,8 +536,10 @@
     """
     Function to normalize the given code.
 
-    @param codestring code to be normalized (string)
-    @return normalized code (string)
+    @param codestring code to be normalized
+    @type str
+    @return normalized code
+    @rtype str
     """
     codestring = codestring.replace("\r\n", "\n").replace("\r", "\n")
 
@@ -536,8 +565,11 @@
     Function to encode html entities.
 
     @param m the match object
+    @type re.Match
     @param escmap the map of entities to encode
-    @return the converted text (string)
+    @type dict
+    @return the converted text
+    @rtype str
     """
     char = m.group()
     text = escmap.get(char)
@@ -550,9 +582,12 @@
     """
     Function to correctly encode a text for html.
 
-    @param text text to be encoded (string)
-    @param pattern search pattern for text to be encoded (string)
-    @return the encoded text (string)
+    @param text text to be encoded
+    @type str
+    @param pattern search pattern for text to be encoded
+    @type str
+    @return the encoded text
+    @rtype str
     """
     if not text:
         return ""
@@ -568,7 +603,9 @@
     Function to encode html entities.
 
     @param m the match object
-    @return the converted text (string)
+    @type re.Match
+    @return the converted text
+    @rtype str
     """
     char = m.group()
     text = "&#{0:d};".format(ord(char))
@@ -579,9 +616,12 @@
     """
     Function to correctly encode a unicode text for html.
 
-    @param text text to be encoded (string)
-    @param pattern search pattern for text to be encoded (string)
-    @return the encoded text (string)
+    @param text text to be encoded
+    @type str
+    @param pattern search pattern for text to be encoded
+    @type str
+    @return the encoded text
+    @rtype str
     """
     if not text:
         return ""
@@ -597,7 +637,9 @@
     Function to decode html entities.
 
     @param m the match object
-    @return the converted text (string)
+    @type re.Match
+    @return the converted text
+    @rtype str
     """
     char = m.group()
     ordinal = int(char[2:-1])
@@ -608,9 +650,12 @@
     """
     Function to correctly decode a html text to a unicode text.
 
-    @param text text to be decoded (string)
-    @param pattern search pattern for text to be decoded (string)
-    @return the decoded text (string)
+    @param text text to be decoded
+    @type str
+    @param pattern search pattern for text to be decoded
+    @type str
+    @return the decoded text
+    @rtype str
     """
     if not text:
         return ""
@@ -622,9 +667,12 @@
     """
     Function to convert the end of line characters.
 
-    @param text text to be converted (string)
-    @param eol new eol setting (string)
-    @return text with converted eols (string)
+    @param text text to be converted
+    @type str
+    @param eol new eol setting
+    @type str
+    @return text with converted eols
+    @rtype str
     """
     if eol == "\r\n":
         regexp = re.compile(r"""(\r(?!\n)|(?<!\r)\n)""")
@@ -643,7 +691,8 @@
     """
     Function to return the line separator used by the editor.
 
-    @return line separator used by the editor (string)
+    @return line separator used by the editor
+    @rtype str
     """
     eolMode = Preferences.getEditor("EOLMode")
     if eolMode == QsciScintilla.EolMode.EolUnix:
@@ -666,8 +715,10 @@
     at the very end of a file. The search is ended, if a line without
     the 'eflag:' marker is found.
 
-    @param text text to be scanned (string)
+    @param text text to be scanned
+    @type str
     @return dictionary of string, boolean, complex, float and int
+    @rtype dict
     """
     flags = {}
     lines = text.rstrip().splitlines() if isinstance(text, str) else text
@@ -713,8 +764,10 @@
     """
     Function to extract eric specific flags out of the given file.
 
-    @param filename name of the file to be scanned (string)
+    @param filename name of the file to be scanned
+    @type str
     @return dictionary of string, boolean, complex, float and int
+    @rtype dict
     """
     try:
         source, encoding = readEncodedFile(filename)
@@ -729,11 +782,16 @@
     Function to extract flags starting and ending with '__' from a line
     comment.
 
-    @param line line to extract flags from (string)
-    @param startComment string identifying the start of the comment (string)
-    @param endComment string identifying the end of a comment (string)
-    @param flagsLine flag indicating to check for a flags only line (bool)
-    @return list containing the extracted flags (list of strings)
+    @param line line to extract flags from
+    @type str
+    @param startComment string identifying the start of the comment
+    @type str
+    @param endComment string identifying the end of a comment
+    @type str
+    @param flagsLine flag indicating to check for a flags only line
+    @type bool
+    @return list containing the extracted flags
+    @rtype list of str
     """
     flags = []
 
@@ -987,7 +1045,8 @@
     """
     Function to get the help text for the supported %-codes.
 
-    @returns help text (string)
+    @return help text
+    @rtype str
     """
     return QCoreApplication.translate(
         "Utilities",
@@ -1029,6 +1088,100 @@
         return match.start()
 
 
+def unslash(txt):
+    """
+    Function to convert a string containing escape codes to an escaped string.
+
+    @param txt string to be converted
+    @type str
+    @return converted string containing escape codes
+    @rtype str
+    """
+    s = []
+    index = 0
+    while index < len(txt):
+        c = txt[index]
+        if c == "\\" and index + 1 < len(txt):
+            index += 1
+            c = txt[index]
+            if c == "a":
+                o = "\a"
+            elif c == "b":
+                o = "\b"
+            elif c == "f":
+                o = "\f"
+            elif c == "n":
+                o = "\n"
+            elif c == "r":
+                o = "\r"
+            elif c == "t":
+                o = "\t"
+            elif c == "v":
+                o = "\v"
+            elif c in "01234567":
+                # octal
+                oc = c
+                if index + 1 < len(txt) and txt[index + 1] in "01234567":
+                    index += 1
+                    oc += txt[index]
+                    if index + 1 < len(txt) and txt[index + 1] in "01234567":
+                        index += 1
+                        oc += txt[index]
+                o = chr(int(oc, base=8))
+            elif c.lower() == "x":
+                val = 0
+                if index + 1 < len(txt) and txt[index + 1] in "0123456789abcdefABCDEF":
+                    index += 1
+                    hx = txt[index]
+                    if (
+                        index + 1 < len(txt)
+                        and txt[index + 1] in "0123456789abcdefABCDEF"
+                    ):
+                        index += 1
+                        hx += txt[index]
+                    val = int(hx, base=16)
+                o = chr(val)
+            else:
+                o = c
+        else:
+            o = c
+
+        s.append(o)
+        index += 1
+
+    return "".join(s)
+
+
+_slashmap = {i: hex(i).replace("0x", "\\x") for i in range(7)}
+_slashmap.update(
+    {
+        7: "\\a",
+        8: "\\b",
+        9: "\\t",
+        10: "\\n",
+        11: "\\v",
+        12: "\\f",
+        13: "\\r",
+    }
+)
+_slashmap.update({i: hex(i).replace("0x", "\\x") for i in range(14, 32)})
+_slashmap.update({i: hex(i).replace("0x", "\\x") for i in range(127, 160)})
+
+
+def slash(txt):
+    """
+    Function to convert an escaped string to a string containing escape codes.
+
+    Note: This is the reverse of 'unslash()'.
+
+    @param txt string to be converted
+    @type str
+    @return converted string containing escaped escape codes
+    @rtype str
+    """
+    return txt.translate(_slashmap)
+
+
 ###############################################################################
 ## Other utility functions below
 ###############################################################################
@@ -1118,7 +1271,7 @@
                 versions[pinfo["module_name"]] = pinfo["version"]
 
             info.append("Plugins Version Numbers:")
-            for pluginModuleName in sorted(versions.keys()):
+            for pluginModuleName in sorted(versions):
                 info.append(
                     "  {0} {1}".format(pluginModuleName, versions[pluginModuleName])
                 )

eric ide

mercurial