view piecrust/formatting/markdownformatter.py @ 440:32c7c2d219d2

performance: Refactor how data is managed to reduce copying. * Make use of `collections.abc.Mapping` to better identify things that are supposed to look like dictionaries. * Instead of handling "overlay" of data in a dict tree in each different data object, make all objects `Mapping`s and handle merging at a higher level with the new `MergedMapping` object. * Since this new object is read-only, remove the need for deep-copying of app and page configurations. * Split data classes into separate modules.
author Ludovic Chabant <ludovic@chabant.com>
date Sun, 28 Jun 2015 08:22:39 -0700
parents e7b865f8f335
children 79f03b5c1b8f
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._formatter = None

    def render(self, format_name, txt):
        assert format_name in self.FORMAT_NAMES
        self._ensureInitialized()
        return self._formatter.reset().convert(txt)

    def _ensureInitialized(self):
        if self._formatter 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 = []
        if isinstance(extensions, str):
            extensions = [e.strip() for e in extensions.split(',')]
        # Compatibility with PieCrust 1.x
        if config.get('use_markdown_extra'):
            extensions.append('extra')

        self._formatter = Markdown(extensions=extensions)