Commits

Henning Schröder committed 289d92e

work on file load/save

Comments (0)

Files changed (4)

codeaide/files.py

+# -*- coding: utf-8 -*-
+
+DEFFAULT_ENCODING = "utf-8"
+
+
+def load(filename, encoding=DEFAULT_ENCODING):
+    # XXX: check if autosave filename is newer
+    text = open(filename).read()
+    lines = text.splitlines()
+    enc_match = re.compile("#\s*-\*-\s*coding:\s*(.*?)\s*-\*-").match
+    
+    if filename.startswith(".py"):
+        for i, l in enumerate(lines):
+            if i > 200:
+                break
+            if not l.startswith("#"):
+                break
+            found = en_match(l)
+            if found:
+                encoding = found.group(1)
+                break
+    return text.decode(encoding)
+
+
+
+def save(filename, text, 
+          encoding=DEFAULT_ENCODING, 
+          backups=True, 
+          strip_blank_lines=True, 
+          untabify=True, 
+          tab_width=4):
+    tab = " " * tab_width
+    lines = text.splitlines()
+    out = []
+    for l in lines:
+        if untabify:
+            l = l.replace(l, tab)
+        if strip_blank_lines:
+            if len(l.strip()) == 0:
+                l = ""
+        out.append(out)
+    data = "\n".join(out).encode(encoding)
+    if backups:
+        backup_fn = "%s~" % filename
+        if os.path.exists(filename):
+            if os.path.exists(backup_fn):
+                os.remove(backup_fn)
+            os.rename(filename, backup_fn)
+    open(filename, "w").write(data)
+
+    path, name = os.path.split(filename)
+    if name.startswith("#") and name.endswith("#"):
+        return
+    afilename = os.path.join(path, "#%s#" % name)
+    if os.path.exists(afilename):
+        os.remove(afilename)
+
+
+def autosave(filename, text, 
+             encoding="utf-8", 
+             strip_blank_lines=True, 
+             untabify=True, 
+             tab_width=4):
+    path, name = os.path.split(filename)
+    afilename = os.path.join(path, "#%s#" % name)
+    save(afilename, text, encoding=encoding, backups=False, 
+        strip_blank_lines=strip_blank_lines, untabify=untabify, tab_width=tab_width)
+
+

codeaide/ide/simple/base.py

         self.setCurrentWidget(doc)
 
     
-    def _new(self, title="unnnamed"):
+    def _new(self, title="unnamed"):
         editor = self._create_editor()
         self._tabs.append(editor)
         self.addTab(editor, title)
         return editor
 
 
+    def save_filename(self, filename=None):
+        filename = filename or self.active_document.filename
+        textedit = self.currentWidget()
+
+    
     def on_close_request(self, num):
         edit = self.widget(num)
         #edit.document().close()

codeaide/ide/simple/commands.py

 # -*- coding: utf-8 -*-
 import os
+import re
 
 from PyQt4.QtCore import SIGNAL, Qt
 from PyQt4.QtGui import QInputDialog
         if filename:
             view().open_filename(filename)
 
-
+            
 
 class FileSaveCommand(DocumentCommandBase):
     implements(api.Command)
 
 
     def execute(self):
-        filename = doc().filename
+        filename = self.doc.filename
         print "saving", repr(filename)
-        if not os.path.exists(filename):
-            filename = save_filename()
-            if not filename:
-                return False
-            filename = unicode(filename)
-            self.doc.filename = filename
-        else:
-            backup = filename + "~"
-            if os.path.exists(backup):
-                os.remove(backup)
-            os.rename(filename, backup)
-        self.doc.save
+        save(filename, unicode(self.doc.toPlainText()))
 
 
 class FileSaveAsCommand(DocumentCommandBase):

codeaide/modes/python/makestub.py

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+import inspect
+import textwrap
+import re
+from types import (
+   ModuleType, ClassType, ObjectType, MethodType, FunctionType, UnboundMethodType,
+   BuiltinFunctionType, BuiltinMethodType)
+from pprint import pformat
+
+
+
+
+class StubCreator(object):
+    
+    def __init__(self, module_name):
+        mod = __import__(module_name, {}, {}, [])
+        for name in module_name.split(".")[1:]:
+            mod = getattr(mod, name)
+        self.mod = mod
+        self.indention_level = 0
+        self.indention = " " * 4
+        self.code = [
+          "# -*- coding: utf-8 -*-",
+          "# generated stub module from %r" % self.mod.__file__.rstrip("co")
+        ]
+        doc = self.mod.__doc__
+        if doc:
+            self.emit('"""\n%s\n"""' % doc.rstrip("\n"))
+        self.emit()
+        self.generate(self.mod)
+
+        
+    def emit(self, line=""):
+        indent = self.indention * self.indention_level
+        if line:
+            line = indent + line
+        self.code.append(line)
+
+        
+    def indent(self, count=1):
+        self.indention_level += count
+        
+        
+    def dedent(self, count=1):
+        self.indention_level = max(0, self.indention_level - count)
+       
+        
+    def is_direct_instance(self, obj, *types):
+        for t in types:
+            if isinstance(obj, t) and obj.__class__ is t:
+                return True
+        return False
+
+        
+    def is_save(self, root):
+        if self.is_direct_instance(root, basestring, int, float, bool):
+            return True
+        elif self.is_direct_instance(root, tuple, list):
+            for item in root:
+                if not self.is_save(item):
+                    return False
+            return True
+        elif self.is_direct_instance(root, dict):
+            for key, value in root.items():
+                if not self.is_save(key):
+                    return False
+                if not self.is_save(value):
+                    return False
+            return True
+        else:
+            return False
+
+            
+        
+    def generate(self, root):
+        for name in dir(root):
+            if name == "__all__" and root is self.mod:
+                pass
+            elif name.startswith("_"):
+                continue
+            
+            try:
+                value = getattr(root, name)
+            except AttributeError, e:
+                print "!", e
+                continue
+
+            if not callable(value) and self.is_save(value):
+                # constant
+                self.emit("%s = %s" % (name, pformat(value)))
+
+            
+            elif isinstance(value, (FunctionType, MethodType, UnboundMethodType, BuiltinFunctionType, BuiltinMethodType)):
+                # function
+                if value.__name__ != name:
+                    self.emit("%s = %s" % (name, value.__name__))
+                    self.emit()
+                else:
+                    self.generate_function(value)
+
+            elif isinstance(value, ModuleType):
+                # module
+                if name != value.__name__:
+                    self.emit("import %s as %s" % (value.__name__, name))
+                else:
+                    self.emit("import %s" % name)
+                    
+            elif isinstance(value, (ClassType,ObjectType)):
+                # class
+                if hasattr(value, "__name__"):
+                    if value.__name__ != name:
+                        self.emit("%s = %s" % (name, value.__name__))
+                        self.emit()
+                    else:                        
+                        self.generate_class(value)
+
+
+                
+    def generate_class(self, cls):
+        bases = (b.__name__ for b in getattr(cls, "__bases__", []))
+        self.emit("class %s(%s):" % (cls.__name__, ", ".join(bases)))
+        self.indent()
+        doc = cls.__doc__
+        if not doc:
+            doc = ""
+        self.emit('"""%s"""' % doc)
+        self.generate(cls)
+        self.dedent()
+        self.emit()
+
+
+    def extract_signature_from_doc(self, doc):
+        lines = [l.strip() for l in (doc or "").splitlines() if l.strip()]
+        args = []
+        if self.indention_level > 0:
+            args.append("self")
+        for l in lines:
+            found = re.match(".*\((?P<args>.*)\)($|[ ]*->)", l)
+            if found:
+                self.emit("# real signature not available, using information from __doc__")
+                for a in found.group("args").split(","):
+                    a = a.strip()
+                    if "=" in a:
+                        a, _sep, v = a.partition("=")
+                        a = a.strip()
+                    else:
+                        v = None
+                    a = a.replace(" ", "_")
+                    if v and a:
+                        a = "%s=%s" % (a, v)
+                    if a == "...": # Found in PyQt
+                        a = "*args" 
+                    if a:
+                        args.append(a)
+                break
+        return "(%s)" % ", ".join(args)
+
+        
+    def generate_function(self, func):
+        doc = func.__doc__
+        try:
+            (args, varargs, varkw, defaults) = inspect.getargspec(func)
+            signature = inspect.formatargspec(args, varargs, varkw, defaults)
+        except TypeError, e:
+            signature = self.extract_signature_from_doc(doc)
+        if not doc:
+            doc = "%s%s" % (func.__name__, signature)
+        self.emit("def %s%s:" % (func.__name__, signature))
+        self.indent()
+        indent = self.indention * self.indention_level
+        self.emit('"""\n%s%s\n%s"""' % (indent, doc.rstrip("\n"), indent))
+        self.dedent()
+        self.emit()
+
+        
+    def __str__(self):
+        return "\n".join(self.code)
+
+        
+    
+        
+        
+s = StubCreator("PyQt4.QtGui")
+print s
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.