Edgewall Software

TracWiki: markdown2trac.py

File markdown2trac.py, 1.5 KB (added by ben@…, 6 years ago)

The beginnings of a script to convert from Markdown wiki syntax to Trac's wiki syntax. Perhaps a better option would be to write a script to convert from HTML to Trac's wiki syntax?

Line 
1#!/usr/bin/env python
2
3import sys
4import re
5
6lheader = re.compile('\A\s*(?P<hashes>\#+)')
7rheader = re.compile('(?P<hashes>\#+)\s*\Z')
8litalics = re.compile('_(?P<keep>[\W])')
9ritalics = re.compile('(?P<keep>[\W])_')
10numbered = re.compile('^1\.')
11
12def translate_line(line):
13    # Substitute # for = in the headers
14    for header in [lheader, rheader]:
15        if header.search(line):
16            nhashes = len(header.search(line).group('hashes'))
17            line = header.sub('=' * nhashes, line)
18
19    # Change delimiters for bold
20    line = line.replace('**', "'''")
21
22    # Change delimiters for italics. This elaborate way of doing it ensures
23    # that a variable or function name separated by underscores, such as
24    # foo_bar, doesn't get italicized.
25    line = litalics.sub(r"''\g<keep>", line)
26    line = ritalics.sub(r"\g<keep>''", line)
27
28    # Add a space before numbered lists
29    line = numbered.sub(' 1.', line)
30
31    # Return with any trailing newline removed
32    return line.rstrip()
33
34def main():
35    if len(sys.argv) != 2:
36        print "Usage: python markdown2trac <filename>"
37        return
38   
39    delim = '{{{'
40    for line in file(sys.argv[1]):
41        line = translate_line(line)
42
43        # Change code marking from `code` to {{{code}}}
44        ix = line.find('`')
45        while ix != -1:
46            line = line[:ix] + delim + line[ix+1:]
47            if delim == '{{{':
48                delim = '}}}'
49            else:
50                delim = '{{{'
51            ix = line.find('`', ix + 1)
52       
53        print line
54
55if __name__ == "__main__":
56    main()
57