Commits

Henning Schröder committed 5bfef5c

better loading/saving

Comments (0)

Files changed (3)

codeaide/fileio.py

+# -*- coding: utf-8 -*-
+import os
+import re
+
+
+DEFFAULT_ENCODING = "utf-8"
+
+
+class FileIO(object):
+
+
+    def __init__(self, backups=True, 
+              strip_blank_lines=True, 
+              untabify=True, 
+              tab_width=4,
+              encoding=DEFAULT_ENCODING):
+        self.settings = dict(
+            backups=backups, 
+            strip_blank_lines=True,
+            untabify=True,
+            tab_width=4,
+            encoding=encoding,
+            backup_name="%s~",
+            autosave_name="#%s#",
+          )
+          
+
+    def guess_encoding(self, text):
+        lines = text.splitlines()
+        enc_match = re.compile("#\s*-\*-\s*coding:\s*(.*?)\s*-\*-").match
+        
+        if filename.startswith(".py"):
+            encoding = self.settings["encoding"]
+            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 encoding
+
+
+    def load(self, filename, encoding=None):
+        # XXX: check if autosave filename is newer
+        # XXX: check size below sensible limit 
+        f = open(filename)
+        text = f.read()
+        f.close()
+        encoding = encoding or self.guess_encoding(text)
+        return text.decode(encoding)
+
+
+    def save(self, filename, text, **settings):
+        settings = dict(self.settings, **settings)
+        tab = " " * setting["tab_width"]
+        lines = text.splitlines()
+        out = []
+        for l in lines:
+            if settings["strip_blank_lines"] and len(l.strip()) == 0:
+                l = ""
+            elif settings["untabify"]:
+                l = l.replace(l, tab)
+            out.append(out)
+        text = "\n".join(out).encode(encoding)
+        
+        if settings["backups"]:
+            path, name = os.path.split(filename)
+            backup_fn = os.path.join(path, settings["backup_name"] % name)
+            if os.path.exists(filename):
+                if os.path.exists(backup_fn):
+                    os.remove(backup_fn)
+                os.rename(filename, backup_fn)
+            
+        f = open(filename, "w")
+        f.write(text)
+        f.close()
+    
+        # remove autosaved file
+        path, name = os.path.split(filename)
+        if name.startswith("#") and name.endswith("#"):
+            return
+        afilename = os.path.join(path, self.settings["autosave_name"] % name)
+        if os.path.exists(afilename):
+            os.remove(afilename)
+
+        return text
+    
+
+    def autosave(self, filename, text, **settings):
+        asettings = dict(self.settings)
+        asettings.update(            
+            strip_blank_lines=False
+            untabify=False)
+        asettings.update(settings)
+        path, name = os.path.split(filename)
+        afilename = os.path.join(path, "#%s#" % name)
+        return self.save(afilename, text, backups=False, **settings)

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)
-
-
     QAbstractSlider, QScrollBar,
     QMenu)
 
+
 from codeaide.base import ModeBase, TextCursor
 from codeaide.utils import jdict
+from codeaide.fileio import FileIO
 
 
 class ScrollBar(QScrollBar):
     killring = []
     registers = []
     instances =  []
-
+    file_io = None
 
     @classmethod
     def get(cls, idx):
         if isinstance(idx, basestring):
             for buf in cls.instances:
                 if buf.filename == idx:
-                    return bux
+                    return buf
         return cls.instances[idx]
 
 
         QTextDocument.__init__(self)
         Hookable.__init__(self)
         Configurable.__init__(self)
+        if not self.__class__.file_io:
+            self.__class__.file_io = FileIO()
+
         self.filename = filename
         if text is None and filename and os.path.exists(filename):
-            text = open(filename).read()
+            text = self.file_io.load(filename)
         self.plain_text_layout = QPlainTextDocumentLayout(self)
         self.setDocumentLayout(self.plain_text_layout)
         if text:
         self.setup_hooks()
         #self.install("Autosave")
 
-        
+
+
     def document(self):
         return self # work-around...
 
         return doc
 
     
+    def save_buffer(self, filename=None):
+        doc = self.document()
+        filename = filename or doc.filename
+        doc.file_io.save(filename, unicode(doc.toPlainText()))
+
+    
     def switch_buffer(self, num):
         doc = Buffer[num]
         self.setDocument(doc)