Example #1
0
    def convert(self, source, **context):
        """ Converts the source file and saves to the destination """
        with codecs.open(source, encoding='utf-8') as src:
            lines = src.readlines()

        # Parse metadata first so we can get theme extensions
        md = Markdown()
        lines = MetaPreprocessor(md).run(lines)

        Meta = md.Meta
        meta = {k: ' '.join(v) for k, v in Meta.items()}

        # Load theme from meta data if set
        theme = meta.get('theme', 'default')

        exts = self.config.theme_get(theme, 'markdown_extensions', [
            'codehilite(css_class=syntax,guess_lang=False)'])
        exts = filter(None, exts)  # Removes empty lines

        md = Markdown(extensions=exts)
        md.Meta = meta  # restore already parsed meta data

        content = md.convert(''.join(lines))

        context['Meta'] = Meta
        context['meta'] = meta

        return self.config.render_template(theme, content, **context)
Example #2
0
def parse_markdown_file(md_file, output_extension=''):
    md = Markdown(extensions=['extra', 'meta', 'nl2br', 'sane_lists'])
    html = md.convert(codecs.open(md_file, 'r', 'utf-8').read())
    slug, _ = os.path.splitext(os.path.basename(md_file))

    if not hasattr(md, 'Meta'):
        md.Meta = {}

    data = {}
    data.update(md.Meta)

    date = datetime.fromtimestamp(os.path.getmtime(md_file))
    if md.Meta.get('date'):
        date = dateutil.parser.parse(md.Meta.get('date')[0])
    data.update({
        'title':
        md.Meta.get('title', [''])[0]
        or slug.replace('-', ' ').replace('_', ' ').title(),
        'date':
        date,
        'html':
        html,
        'slug':
        slug,
        'source':
        md_file,
        'link':
        os.path.splitext(md_file)[0] + output_extension
    })
    return data
Example #3
0
    def __init__(self, request, path, parent=None):
        super(BlogEntry, self).__init__(request, path, parent=parent)
        self.base_name, self.ext = os.path.splitext(path)
        assert self.ext.lower() in self.EXT, " %s is not a markdown file" % path
        m = Markdown(extensions=md_extensions)
        m.Meta = {}
        body = cStringIO.StringIO()
        m.convertFile(input=open(self.path), output=body)
        self.body = body.getvalue()
        body.close()

        for k, v in m.Meta.items():
            setattr(self, k, " ".join(v))
        self.page = BlogPage(request, "%s.html" % self.base_name, self)
Example #4
0
File: utils.py Project: saimn/sigal
def read_markdown(filename):
    """Reads markdown file, converts output and fetches title and meta-data for
    further processing.
    """
    global MD
    # Use utf-8-sig codec to remove BOM if it is present. This is only possible
    # this way prior to feeding the text to the markdown parser (which would
    # also default to pure utf-8)
    with open(filename, encoding='utf-8-sig') as f:
        text = f.read()

    if MD is None:
        MD = Markdown(
            extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.meta',
                'markdown.extensions.tables',
            ],
            output_format='html5',
        )
    else:
        MD.reset()
        # When https://github.com/Python-Markdown/markdown/pull/672
        # will be available, this can be removed.
        MD.Meta = {}

    # Mark HTML with Markup to prevent jinja2 autoescaping
    output = {'description': Markup(MD.convert(text))}

    try:
        meta = MD.Meta.copy()
    except AttributeError:
        pass
    else:
        output['meta'] = meta
        try:
            output['title'] = MD.Meta['title'][0]
        except KeyError:
            pass

    return output
Example #5
0
File: utils.py Project: saimn/sigal
def read_markdown(filename):
    """Reads markdown file, converts output and fetches title and meta-data for
    further processing.
    """
    global MD
    # Use utf-8-sig codec to remove BOM if it is present. This is only possible
    # this way prior to feeding the text to the markdown parser (which would
    # also default to pure utf-8)
    with open(filename, 'r', encoding='utf-8-sig') as f:
        text = f.read()

    if MD is None:
        MD = Markdown(extensions=['markdown.extensions.meta',
                                  'markdown.extensions.tables'],
                      output_format='html5')
    else:
        MD.reset()
        # When https://github.com/Python-Markdown/markdown/pull/672
        # will be available, this can be removed.
        MD.Meta = {}

    # Mark HTML with Markup to prevent jinja2 autoescaping
    output = {'description': Markup(MD.convert(text))}

    try:
        meta = MD.Meta.copy()
    except AttributeError:
        pass
    else:
        output['meta'] = meta
        try:
            output['title'] = MD.Meta['title'][0]
        except KeyError:
            pass

    return output
 def extendMarkdown(self, md: markdown.Markdown, *args, **kwargs):
     md.Meta = None
     md.preprocessors.register(FullYamlMetadataPreprocessor(md),
                               "full_yaml_metadata", 1)