@ 8659ef2c4757

Replace /markdown/_preview/ URL pattern with simpler /preview/ pattern. Wrap
default "file" web command with one that redirects to markdown view for .md
and .markdown files. Dynamically rebase img links to /rawfile to allow images
to be embedded.
author Chris Eldredge <>
date Mon, 13 Aug 2012 18:33:12 +0100
parents 299ff954bfa8
children (none)
import markdown

class UrlRebaseExtension(markdown.Extension):
	def __init__ (self, configs):
		# set extension defaults
		self.config = {
			'rebase' : [None, 'Callable to rebase elementes with custom logic.'],
			'base_url' : ['/', 'String to append to beginning or URL.'],

		# Override defaults with user settings
		for key, value in configs :
			self.setConfig(key, value)		

	def extendMarkdown(self, md, md_globals):
		""" Add pieces to Markdown. """
		md.treeprocessors.add("urlrebase", UrlRebaseTreeprocessor(self.getConfigs()), "_end")
class UrlRebaseTreeprocessor(markdown.treeprocessors.Treeprocessor):
	def __init__ (self, config):
		self.config = config
	def run(self, root):
		rebase = self.rebase_element
		if "rebase" in self.config:
			rebase = self.config["rebase"]
		for a in root.findall(".//a"):
			rebase(self, a, 'href')
		for i in root.findall(".//img"):
			rebase(self, i, 'src')
		return root

	def rebase_element(self, also_self, e, attr):
		uri = e.get(attr, '')
		if '://' in uri or uri.startswith('/'):
		e.set(attr, self.rebase(uri))

	def rebase(self, base, uri):
		if base[0] and not base.endswith('/'):
			base = base + '/'
		return base + uri

def makeExtension(configs=None) :
	return UrlRebaseExtension(configs=configs)