| 1 | #!/usr/bin/env python |
|---|
| 2 | |
|---|
| 3 | import sys |
|---|
| 4 | import re |
|---|
| 5 | |
|---|
| 6 | lheader = re.compile('\A\s*(?P<hashes>\#+)') |
|---|
| 7 | rheader = re.compile('(?P<hashes>\#+)\s*\Z') |
|---|
| 8 | litalics = re.compile('_(?P<keep>[\W])') |
|---|
| 9 | ritalics = re.compile('(?P<keep>[\W])_') |
|---|
| 10 | numbered = re.compile('^1\.') |
|---|
| 11 | |
|---|
| 12 | def 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 | |
|---|
| 34 | def 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 | |
|---|
| 55 | if __name__ == "__main__": |
|---|
| 56 | main() |
|---|
| 57 | |
|---|