Utilities/__init__.py

branch
Py2 comp.
changeset 3484
645c12de6b0c
parent 3456
96232974dcdb
parent 3446
5a670e55adbb
child 3515
1b8381afe38f
--- a/Utilities/__init__.py	Sun Mar 30 22:00:14 2014 +0200
+++ b/Utilities/__init__.py	Thu Apr 03 23:05:31 2014 +0200
@@ -9,7 +9,7 @@
 
 from __future__ import unicode_literals
 try:
-    str = unicode   # __IGNORE_WARNING__
+    str = unicode
     import urllib
 
     def quote(url):
@@ -20,7 +20,7 @@
         @return quoted url (string)
         """
         return urllib.quote(url.encode('utf-8'))
-except (NameError):
+except NameError:
     basestring = str
     from urllib.parse import quote    # __IGNORE_WARNING__
 
@@ -71,7 +71,8 @@
 from UI.Info import Program, Version
 
 import Preferences
-from Plugins.CheckerPlugins.SyntaxChecker.SyntaxCheck import normalizeCode
+from Plugins.CheckerPlugins.SyntaxChecker.SyntaxCheck import (  # __IGNORE_WARNING__
+    normalizeCode)
 
 from eric5config import getConfig
 
@@ -269,6 +270,34 @@
     return str(text, "utf-8", "ignore"), 'utf-8-ignore'
 
 
+def readEncodedFileWithEncoding(filename, encoding):
+    """
+    Function to read a file and decode its contents into proper text.
+    
+    @param filename name of the file to read (string)
+    @keyparam encoding encoding to be used to read the file (string)
+    @return tuple of decoded text and encoding (string, string)
+    """
+    f = open(filename, "rb")
+    text = f.read()
+    f.close()
+    if encoding:
+        try:
+            return str(text, encoding), '{0}-selected'.format(encoding)
+        except (UnicodeError, LookupError):
+            pass
+        # Try default encoding
+        try:
+            codec = Preferences.getEditor("DefaultEncoding")
+            return str(text, codec), '{0}-default'.format(codec)
+        except (UnicodeError, LookupError):
+            pass
+        # Assume UTF-8 loosing information
+        return str(text, "utf-8", "ignore"), 'utf-8-ignore'
+    else:
+        return decode(text)
+
+
 def writeEncodedFile(filename, text, orig_coding):
     """
     Function to write a file with properly encoded text.
@@ -1298,11 +1327,12 @@
 
 def determinePythonVersion(filename, source, editor=None):
     """
-    Determine the python version of a given file.
+    Function to determine the python version of a given file.
     
     @param filename name of the file with extension (str)
     @param source of the file (str)
-    @keyparam editor if the file is opened already (Editor object)
+    @keyparam editor reference to the editor, if the file is opened
+        already (Editor object)
     @return Python version if file is Python2 or Python3 (int)
     """
     pyAssignment = {"Python": 2, "Python2": 2, "Python3": 3}
@@ -1355,6 +1385,7 @@
     
     if editor and pyVer:
         editor.filetype = "Python{0}".format(pyVer)
+    
     return pyVer
 
 
@@ -1705,3 +1736,46 @@
     nameBuffer = ctypes.create_unicode_buffer(size.contents.value)
     GetUserNameEx(NameDisplay, nameBuffer, size)
     return nameBuffer.value
+
+###############################################################################
+# Javascript related functions below
+###############################################################################
+
+
+def jsCheckSyntax(file, codestring=""):
+    """
+    Function to check a Javascript source file for syntax errors.
+    
+    @param file source filename (string)
+    @param codestring string containing the code to check (string)
+    @return A tuple indicating status (True = an error was found), the
+        file name, the line number and the error message (boolean, string,
+        string, string). The values are only valid, if the status is True.
+    """
+    import jasy.js.parse.Parser as jsParser
+    import jasy.js.tokenize.Tokenizer as jsTokenizer
+    
+    if not codestring:
+        try:
+            codestring = readEncodedFile(file)[0]
+        except (UnicodeDecodeError, IOError):
+            return (False, None, None, None)
+    
+    # normalize line endings
+    codestring = codestring.replace("\r\n", "\n")
+    codestring = codestring.replace("\r", "\n")
+    
+    # ensure source ends with an eol
+    if codestring and codestring[-1] != '\n':
+        codestring = codestring + '\n'
+    
+    try:
+        jsParser.parse(codestring, file)
+    except (jsParser.SyntaxError, jsTokenizer.ParseError) as exc:
+        details = exc.args[0]
+        error, details = details.splitlines()
+        fn, line = details.strip().rsplit(":", 1)
+        error = error.split(":", 1)[1].strip()
+        return (True, fn, line, error)
+    
+    return (False, None, None, None)

eric ide

mercurial