summaryrefslogtreecommitdiff
path: root/docs/users_guide_2_src/latex2rst.py
blob: 80f9a1d92ba8363f46d31792f91084ed71b1ce86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python
"""Convert files from LaTeX format to ReStructured Text.

   This converter is meant only for saving keystrokes.  It won't catch
   everything and it may misformat stuff, so proofread the file after
   processing.

   "Verbatim" blocks are not converted due to the difficulty in placing the
   preceding colon(s) and indenting every line.
"""
import os, re, shutil, sys

def convert(filename):
    print "Processing file", filename
    backup = filename + ".bak"
    shutil.copy2(filename, backup)
    f = open(filename, 'r+')
    text = f.read()
    text = re.sub( R"%%%+", R"", text)
    text = re.sub( R"\\section\{(.*?)\}",    R"\1\n" + ("=" * 40), text)
    text = re.sub( R"\\subsection\{(.*?)\}", R"\1\n" + ("-" * 40), text)
    text = re.sub( R"\\label\{(.*?)\}",      R"\n..\n    :label: \1", text)
    text = re.sub( R"``|''",                 R'"',      text)
    text = re.sub( R"(?s)\{\\em (.*?)\}",    R"*\1*", text)
    text = re.sub( R"(?s)\{\\bf (.*?)\}",    R"**\1**", text)
    text = re.sub( R"(?s)\\code\{(.*?)\}",   R"``\1``", text)
    text = re.sub( R"\\(begin|end)\{(itemize|enumerate)\}\n", R"", text)
    text = re.sub( R"\\item ",                R"* ", text)
    #text = re.sub( 
    #    R"(?sm)(\w):\n\s*^\\begin\{verbatim\}\s*(.*?)\\end\{verbatim\}", 
    #    R"\1::\n\n\2", text)
    f.seek(0)
    f.write(text)
    f.truncate()
    f.close()


def main():
    if len(sys.argv) < 2:
        prog = os.path.basename(sys.argv[0])
        raise SystemExit("usage: %s FILENAMES ..." % prog)
    for filename in sys.argv[1:]:
        convert(filename)

if __name__ == "__main__":  main()