How to use the markdown.Extension function in Markdown

To help you get started, we’ve selected a few Markdown examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github airbnb / knowledge-repo / knowledge_repo / converters / html.py View on Github external
'footnotes',
                       'tables',
                       'admonition',
                       codehilite.CodeHiliteExtension(guess_lang=False),
                       'meta',
                       'sane_lists',
                       'smarty',
                       toc.TocExtension(baselevel=1),
                       'wikilinks',
                       'knowledge_repo.converters.html:KnowledgeMetaExtension',
                       'knowledge_repo.converters.html:MathJaxExtension',
                       'knowledge_repo.converters.html:IndentsAsCellOutput',
                       'knowledge_repo.converters.html:InlineSpanStyles']


class InlineSpanStyles(Extension):

    SPAN_PATTERN = r'\[([\s\S]*?)\]\{((?:\ ?.[^\,\}]+?)*?)\}'

    class SpanMatchHandler(Pattern):
        def handleMatch(self, m):
            # Extract information from markdown tag
            text = m.group(2)

            ids = [
                id
                for id in m.group(3).split(',')
                if id.startswith('#')
            ]
            id = ids[0] if ids else None

            class_names = [
github aniket-deole / notes / lib / evernote / lib / markdown / extensions / nl2br.py View on Github external
<p>line 1<br>
    line 2</p>

Copyright 2011 [Brian Neal](http://deathofagremmie.com/)

Dependencies:
* [Python 2.4+](http://python.org)
* [Markdown 2.1+](http://www.freewisdom.org/projects/python-markdown/)

"""

import markdown

BR_RE = r'\n'

class Nl2BrExtension(markdown.Extension):

    def extendMarkdown(self, md, md_globals):
        br_tag = markdown.inlinepatterns.SubstituteTagPattern(BR_RE, 'br')
        md.inlinePatterns.add('nl', br_tag, '_end')


def makeExtension(configs=None):
    return Nl2BrExtension(configs)
github lucuma / Clay / clay / libs / md_superscript.py View on Github external
class SuperscriptPattern(markdown.inlinepatterns.Pattern):
    """ Return a superscript Element (`word^2^`). """

    def handleMatch(self, m):
        supr = m.group(3)
        
        text = supr
        
        el = markdown.etree.Element("sup")
        el.text = markdown.AtomicString(text)
        return el


class SuperscriptExtension(markdown.Extension):
    """ Superscript Extension for Python-Markdown. """

    def extendMarkdown(self, md, md_globals):
        """ Replace superscript with SuperscriptPattern """
        md.inlinePatterns['superscript'] = SuperscriptPattern(SUPERSCRIPT_RE, md)


def makeExtension(configs={}):
    return SuperscriptExtension(configs=configs)
github frnsys / nom / nom / md2html.py View on Github external
class FigureCaptionExtension(markdown.Extension):
    def extendMarkdown(self, md, md_globals):
        """ Add an instance of FigcaptionProcessor to BlockParser. """
        md.parser.blockprocessors.add('figureAltcaption',
                                      FigureCaptionProcessor(md.parser),
                                      '
BLOCK_RE = re.compile(
    r'^\{% (?P\w+)\s+(?P[^\s]+)\s*\n(?P<content>.*?)%}\s*$',
    re.MULTILINE | re.DOTALL)
SUPPORTED_COMMAMDS = ['dot', 'neato', 'fdp', 'sfdp', 'twopi', 'circo']


class InlineGraphvizExtension(markdown.Extension):
    def extendMarkdown(self, md, md_globals):
        """ Add InlineGraphvizPreprocessor to the Markdown instance. """
        md.preprocessors.add('graphviz_block',
                             InlineGraphvizPreprocessor(md), '_begin')

class InlineGraphvizPreprocessor(Preprocessor):
    def __init__(self, md):
        super(InlineGraphvizPreprocessor, self).__init__(md)

    def run(self, lines):
        """ Match and generate dot code blocks."""

        text = "\n".join(lines)
        while 1:
            m = BLOCK_RE.search(text)
            if m:</content>
github yosupo06 / library-checker-problems / htmlgen.py View on Github external
self.url = url[0]

    def run(self, lines):
        new_lines = []
        for line in lines:
            new_lines.append(line)
        if self.url:
            new_lines.append('')
            new_lines.append('---')
            new_lines.append('')
            new_lines.append(self.forum_template.format(url=self.url))
            new_lines.append('')
        return new_lines


class ForumExtension(Extension):
    def __init__(self, **kwargs):
        self.config = {
            'url': ['dummy issue URL', 'URL'],
        }
        super(ForumExtension, self).__init__(**kwargs)

    def extendMarkdown(self, md):
        md.preprocessors.register(ForumExpander(
            self.config['url']), 'forum', 101)


class ToHTMLConverter:
    header = '''


github jpfleury / gedit-markdown / python-markdown / extensions / headerid.py View on Github external
level = int(self.md.Meta['header_level'][0]) - 1
            if self.md.Meta.has_key('header_forceid'): 
                force = self._str2bool(self.md.Meta['header_forceid'][0])
        return level, force

    def _str2bool(self, s, default=False):
        """ Convert a string to a booleen value. """
        s = str(s)
        if s.lower() in ['0', 'f', 'false', 'off', 'no', 'n']:
            return False
        elif s.lower() in ['1', 't', 'true', 'on', 'yes', 'y']:
            return True
        return default


class HeaderIdExtension (markdown.Extension):
    def __init__(self, configs):
        # set defaults
        self.config = {
                'level' : ['1', 'Base level for headers.'],
                'forceid' : ['True', 'Force all headers to have an id.'],
                'separator' : ['-', 'Word separator.'],
                'slugify' : [slugify, 'Callable to generate anchors'], 
            }

        for key, value in configs:
            self.setConfig(key, value)

    def extendMarkdown(self, md, md_globals):
        md.registerExtension(self)
        self.processor = HeaderIdTreeprocessor()
        self.processor.md = md
github django-wiki / django-wiki / src / wiki / plugins / macros / mdx / toc.py View on Github external
self.add_anchor(c, elem_id)

        if marker_found:
            toc_list_nested = order_toc_list(toc_list)
            self.build_toc_etree(div, toc_list_nested)
            # serialize and attach to markdown instance.
            prettify = self.markdown.treeprocessors.get('prettify')
            if prettify:
                prettify.run(div)
            toc = self.markdown.serializer(div)
            for pp in self.markdown.postprocessors.values():
                toc = pp.run(toc)
            self.markdown.toc = toc


class TocExtension(markdown.Extension):

    TreeProcessorClass = TocTreeprocessor

    def __init__(self, configs=[]):
        self.config = {
            "marker": [
                "[TOC]", "Text to find and replace with Table of Contents -"
                "Defaults to \"[TOC]\""], "slugify": [
                slugify, "Function to generate anchors based on header text-"
                "Defaults to the headerid ext's slugify function."], "title": [
                None, "Title to insert into TOC <div> - "
                "Defaults to None"], "anchorlink": [
                    0, "1 if header should be a self link"
                    "Defaults to 0"]}

        for key, value in configs:</div>
github PageBot / PageBot / Lib / pagebot / contributions / markdown / footnotes.py View on Github external
import re
from collections import OrderedDict
from markdown import Extension
from markdown.preprocessors import Preprocessor
from markdown.inlinepatterns import Pattern
from markdown.treeprocessors import Treeprocessor
from markdown.postprocessors import Postprocessor
from markdown.util import etree, text_type

FN_BACKLINK_TEXT = "zz1337820767766393qq"
NBSP_PLACEHOLDER = "qq3936677670287331zz"
DEF_RE = re.compile(r'[ ]{0,3}\[\^([^\]]*)\]:\s*(.*)')
TABBED_RE = re.compile(r'((\t)|(    ))(.*)')


class FootnoteExtension(Extension):
    """ Footnote Extension. """

    def __init__(self, *args, **kwargs):
        """ Setup configs. """

        self.config = {
            'PLACE_MARKER':
                ["///Footnotes Go Here///",
                 "The text string that marks where the footnotes go"],
            'UNIQUE_IDS':
                [False,
                 "Avoid name collisions across "
                 "multiple calls to reset()."],
            "BACKLINK_TEXT":
                ["&#8617;",
                 "The text string that links from the footnote "
github frnsys / nom / nom / md2html.py View on Github external
md.inlinePatterns.add('iframe_link', url_pattern, '_begin')


"""
from 
"""
class MathJaxPattern(markdown.inlinepatterns.Pattern):
    def __init__(self):
        markdown.inlinepatterns.Pattern.__init__(self, r'(?).)+)--&gt;', re.DOTALL)
    def run(self, text):
        return self.COMMENTS_RE.sub(self.compile_comment, text)

    def compile_comment(self, match):
        text = match.group(1)
github lucuma / Clay / clay / libs / md_toc.py View on Github external
pass
        
        # searialize and attach to markdown instance.
        ul = div.find('ul')
        if not ul:
            self.markdown.toc = ''
            return
        
        ul.attrib["class"] = "toc"
        toc = self.markdown.serializer(ul)
        for pp in self.markdown.postprocessors.values():
            toc = pp.run(toc)
        self.markdown.toc = toc


class TocExtension(markdown.Extension):

    def __init__(self, **configs):
        self.config = {
            "slugify" : [slugify,
                "Function to generate anchors based on header text-"
                "Defaults to the headerid ext's slugify function."
            ],
            "anchorlink" : [True,
                "True if header should be a self link"
                "Defaults to 0"
            ],
        }
        for key, value in configs:
            self.setConfig(key, value)

    def extendMarkdown(self, md, md_globals):