Skip to content

Instantly share code, notes, and snippets.

@priyadarshan
Created April 24, 2014 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save priyadarshan/11262430 to your computer and use it in GitHub Desktop.
Save priyadarshan/11262430 to your computer and use it in GitHub Desktop.
import os
import re
import shutil
import sys
TITLE_RE = re.compile(r"^\s*#\+TITLE:\s*([^\n]+)\n")
PROPERTIES_RE = re.compile(r"^\n?[ \t]*:PROPERTIES:[ \t]*\n", re.MULTILINE)
END_RE = re.compile(r"^[ \t]*:END:[ \t]*\n\n", re.MULTILINE)
PROPERTY_RE = re.compile(r"^[ \t]*:[\w\-]+:[^\n]*\n", re.MULTILINE)
ITALICS_RE = re.compile(r"^/([^\n]+)/", re.MULTILINE)
HASH_RE = re.compile(r"^#[^\n]+\n", re.MULTILINE)
VERSE_RE = re.compile(r"^#\+(?:BEGIN|END)_VERSE[ \t]*\n", re.MULTILINE)
INDEX_RE = re.compile(r"[\n]+\* Index\s+")
def plainify_dir(directory):
destDir = os.path.join(os.path.dirname(directory), os.path.basename(directory) + " plain")
if os.path.exists(destDir):
shutil.rmtree(destDir)
for root, dirs, files in os.walk(directory):
newDir = os.path.join(destDir, root[len(directory) + 1:])
if not os.path.isdir(newDir):
os.makedirs(newDir)
for file in files:
if file.endswith(".txt"):
plainify(os.path.join(root, file), os.path.join(newDir, file))
def plainify(source, dest):
print(source)
with open(source, "r", encoding="utf-8") as f:
text = f.read()
match = TITLE_RE.match(text)
if match:
title = match.group(1) + "\n\n\n"
else:
title = ""
newText = PROPERTIES_RE.sub("", text)
newText = END_RE.sub("", newText)
newText = PROPERTY_RE.sub("", newText)
newText = ITALICS_RE.sub(r"\1", newText)
newText = VERSE_RE.sub("", newText)
newText = HASH_RE.sub("", newText)
newText = INDEX_RE.sub("", newText)
with open(dest, "w", encoding="utf-8") as f:
f.write(title + newText)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("usage: plainify.py library-dir")
sys.exit(1)
else:
directory = sys.argv[1]
if not os.path.isdir(directory):
print("ERROR: No such directory '{0}'".format(directory))
sys.exit(1)
else:
plainify_dir(directory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment