view piecrust/formatting/markdownformatter.py @ 182:a54d3c0b5f4a

tests: Patch `os.path.exists` and improve patching for `open`. You can specify additional modules for which to patch `open`. Also, it was incorrectly updating the opened file, even when it was opened for read only. Now it only updates the contents if the file was opened for write, and supports appending to the end. Last, it supports opening text files in binary mode.
author Ludovic Chabant <ludovic@chabant.com>
date Sun, 04 Jan 2015 14:55:41 -0800
parents fdb08d986384
children cd049786c008
line wrap: on
line source

from markdown import markdown
from piecrust.formatting.base import Formatter


class MarkdownFormatter(Formatter):
    FORMAT_NAMES = ['markdown', 'mdown', 'md']
    OUTPUT_FORMAT = 'html'

    def __init__(self):
        super(MarkdownFormatter, self).__init__()
        self._extensions = None

    def render(self, format_name, txt):
        assert format_name in self.FORMAT_NAMES
        self._ensureInitialized()
        return markdown(txt, extensions=self._extensions)

    def _ensureInitialized(self):
        if self._extensions is not None:
            return

        config = self.app.config.get('markdown')
        if config is None:
            config = {}
        elif not isinstance(config, dict):
            raise Exception("The `markdown` configuration setting must be "
                            "a dictionary.")

        extensions = config.get('extensions')
        if extensions is None:
            extensions = []
        # Compatibility with PieCrust 1.x
        if config.get('use_markdown_extra'):
            extensions.append('extra')
        self._extensions = extensions