Function to launch the editor for the purposes of getting new text content
authorAndrew Nicols <andrew@nicols.co.uk>
Fri, 26 Dec 2014 07:03:48 +0000 (15:03 +0800)
committerAndrew Nicols <andrew@nicols.co.uk>
Fri, 26 Dec 2014 07:26:50 +0000 (15:26 +0800)
mdk/tools.py

index e277113..6133053 100644 (file)
@@ -117,6 +117,28 @@ def launchEditor(filepath=None, suffix='.tmp'):
     return tmpfile.name
 
 
+def getText(suffix='.md', currenttext=None):
+    success = None
+    with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmpfile:
+        if currenttext:
+            tmpfile.write(currenttext)
+            tmpfile.flush()
+        while True:
+            tmpfile = launchEditor(suffix=suffix, filepath=tmpfile.name)
+            text = None
+            with open(tmpfile, 'r') as f:
+                text = f.read()
+                f.close()
+
+            if text == '':
+                logging.error('I could not detect any file content. Did you save properly?')
+                if yesOrNo('Would you like to continue editing? If not the changes will be discarded.'):
+                    continue
+                else:
+                    return
+            else:
+                return text
+
 def md5file(filepath):
     """Return the md5 sum of a file
     This is terribly memory inefficient!"""