#!/usr/bin/env python
"""Provides basic markdown integrated with various extensions as well as basic
templating so that a document can be converted to a full html file.
This module requires the python markdown script provided at:
Currently designed to be compatible with markdown 1.6+ (1.7 especially).
Called mkdn so as to not cause import conflicts with markdown itself.
"""
import optparse
import sys
import os
import re
import markdown
def convert(infile):
"""Convert a markdown file to html.
"""
indata = infile.read()
if not isinstance(indata, unicode):
indata = indata.decode('utf8')
indata = indata.replace(r'\\', r'\\\\')
indata = re.sub(r'\\([^\\`*_#+-.!])', r'\\\\\1', indata)
md = markdown.Markdown(None,
extensions=['footnotes'],
)
html = md.convert(indata)
html = re.sub(r'([ \w])--([ \w])', r'\1–\2', html)
html = html.encode('utf8')
return html
html_template = \
'''
%(title)s
%(body)s
'''
def template(infile, **kwargs):
"""Convert a markdown file to html file (complete with header etc.
"""
out = convert(infile)
kwargs['body'] = out
out = html_template % kwargs
return out
def convert_for_1_dot_5(infile):
"""Convert a markdown file to html
"""
md = markdown.Markdown()
footnoteExtension.extendMarkdown(md)
indata = infile.read()
indata = indata.replace(r'\\', r'\\\\')
indata = re.sub(r'\\([^\\`*_#+-.!])', r'\\\\\1', indata)
md.source = indata
out = str(md)
out = re.sub(r'([ \w])--([ \w])', r'\1–\2', out)
return out
if __name__ == '__main__':
usage = \
'''usage: %prog [options]
Given a file path, process it using markdown, put it in an html template and
print the result on stdout
'''
parser = optparse.OptionParser(usage)
parser.add_option('-t', '--title', dest='title',
help='html title', default='')
parser.add_option('-r', '--raw', dest='raw',
action='store_true', help='do not put in a template',
default=False)
(options, args) = parser.parse_args()
if not len(args) > 0:
parser.print_help()
sys.exit(1)
inpath = args[0]
infile = file(inpath)
if options.raw:
out = convert(infile)
print out
else:
title = options.title
if not options.title:
filename = os.path.basename(inpath)
base = os.path.splitext(filename)[0]
tstr = base.replace('_', ' ')
tstr = tstr.title()
title = tstr
out = template(infile, title=title)
infile.close()
print out