How to use the mistune.BlockGrammar function in mistune

To help you get started, we’ve selected a few mistune 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 miyakogi / m2r / m2r.py View on Github external
parser.add_argument('--parse-relative-links', action='store_true',
                    default=False,
                    help='parse relative links into ref or doc directives')
parser.add_argument('--anonymous-references', action='store_true',
                    default=False,
                    help='use anonymous references in generated rst')
parser.add_argument('--disable-inline-math', action='store_true',
                    default=False,
                    help='disable parsing inline math')


def parse_options():
    parser.parse_known_args(namespace=options)


class RestBlockGrammar(mistune.BlockGrammar):
    directive = re.compile(
            r'^( *\.\..*?)\n(?=\S)',
            re.DOTALL | re.MULTILINE,
        )
    oneline_directive = re.compile(
            r'^( *\.\..*?)$',
            re.DOTALL | re.MULTILINE,
        )
    rest_code_block = re.compile(
            r'^::\s*$',
            re.DOTALL | re.MULTILINE,
        )


class RestBlockLexer(mistune.BlockLexer):
    grammar_class = RestBlockGrammar
github cuthbertLab / music21 / music21 / ext / nbconvert / filters / markdown_mistune.py View on Github external
import re
import cgi

import mistune

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments.util import ClassNotFound

from nbconvert.filters.strings import add_anchor
from nbconvert.utils.exceptions import ConversionException


class MathBlockGrammar(mistune.BlockGrammar):
    block_math = re.compile(r"^\$\$(.*?)\$\$", re.DOTALL)
    latex_environment = re.compile(r"^\\begin\{([a-z]*\*?)\}(.*?)\\end\{\1\}",
                                                re.DOTALL)

class MathBlockLexer(mistune.BlockLexer):
    default_rules = ['block_math', 'latex_environment'] + mistune.BlockLexer.default_rules

    def __init__(self, rules=None, **kwargs):
        if rules is None:
            rules = MathBlockGrammar()
        super(MathBlockLexer, self).__init__(rules, **kwargs)

    def parse_block_math(self, m):
        """Parse a $$math$$ block"""
        self.tokens.append({
            'type': 'block_math',
github ocf / ocfweb / ocfweb / component / markdown.py View on Github external
HtmlCommentsLexerMixin,
):
    pass


_renderer = OcfMarkdownRenderer(
    escape=True,
    hard_wrap=False,
)

_inline = OcfMarkdownInlineLexer(_renderer)
_inline.enable_html_comments()
_inline.enable_django_links()
_inline.enable_backslash_line_breaks()

_block = OcfMarkdownBlockLexer(mistune.BlockGrammar())
_block.enable_html_comments()

_markdown = mistune.Markdown(
    renderer=_renderer,
    inline=_inline,
    block=_block,
)


def markdown(text: str) -> mistune.Markdown:
    _renderer.reset_toc()
    return _markdown(text)


def text_and_meta(f: Any) -> Tuple[str, Any]:
    """Return tuple (text, meta dict) for the given file.
github chriskuehl / fluffy / fluffy / component / markdown.py View on Github external
class FluffyMarkdownBlockLexer(
    mistune.BlockLexer,
    HtmlCommentsBlockLexerMixin,
):
    pass


_renderer = FluffyMarkdownRenderer(
    escape=True,
    hard_wrap=False,
)

_inline = FluffyMarkdownInlineLexer(_renderer)
_inline.enable_html_comments()

_block = FluffyMarkdownBlockLexer(mistune.BlockGrammar())
_block.enable_html_comments()


@app.template_filter()
def markdown(text):
    return mistune.Markdown(
        renderer=_renderer,
        inline=_inline,
        block=_block,
    )(text)
github lepture / mistune / mistune.py View on Github external
else:
            kwargs.update(renderer.options)

        self.renderer = renderer

        if inline and inspect.isclass(inline):
            inline = inline(renderer, **kwargs)
        if block and inspect.isclass(block):
            block = block(**kwargs)

        if inline:
            self.inline = inline
        else:
            self.inline = InlineLexer(renderer, **kwargs)

        self.block = block or BlockLexer(BlockGrammar())
        self.footnotes = []
        self.tokens = []

        # detect if it should parse text in block html
        self._parse_block_html = kwargs.get('parse_block_html')
github canonical-web-and-design / snapcraft.io / webapp / markdown.py View on Github external
from mistune import (
    BlockGrammar,
    BlockLexer,
    InlineGrammar,
    Renderer,
    Markdown,
    _pure_pattern,
    InlineLexer,
)
import re


class DescriptionBlockGrammar(BlockGrammar):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # This is an extention of the list block rule written in BlockGrammar
        # of mistune library:
        # https://github.com/lepture/mistune/blob/master/mistune.py#L120-L141
        # We want to support the • as a tag for lists in markdown.
        # To do this this [*+-•] is the list of supported tags
        self.list_block = re.compile(
            r"^( *)(?=[•*+-]|\d+\.)(([•*+-])?(?:\d+\.)?) [\s\S]+?"
            r"(?:"
            r"\n+(?=\1?(?:[-*_] *){3,}(?:\n+|$))"  # hrule
            r"|\n+(?=%s)"  # def links
            r"|\n+(?=%s)"  # def footnotes\
            r"|\n+(?=\1(?(3)\d+\.|[•*+-]) )"  # heterogeneous bullet
            r"|\n{2,}"
github sobhe / moratab / moratab / math.py View on Github external
# coding: utf-8

"""
	Support Math features for mistune.

	:copyright: (c) 2014 by Hsiaoming Yang.
"""

import re, mistune


class MathBlockGrammar(mistune.BlockGrammar):
	block_math = re.compile(r"^\$\$(.*?)\$\$", re.DOTALL)
	latex_environment = re.compile(r"^\\begin\{([a-z]*\*?)\}(.*?)\\end\{\1\}", re.DOTALL)

class MathBlockLexer(mistune.BlockLexer):
	default_rules = ['block_math', 'latex_environment'] + mistune.BlockLexer.default_rules

	def __init__(self, rules=None, **kwargs):
		if rules is None:
			rules = MathBlockGrammar()
		super(MathBlockLexer, self).__init__(rules, **kwargs)

	def parse_block_math(self, m):
		"""Parse a $$math$$ block"""
		self.tokens.append({
			'type': 'block_math',
			'text': m.group(1)
github ipython / ipython / IPython / nbconvert / filters / markdown_mistune.py View on Github external
import re

import mistune

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments.util import ClassNotFound

from IPython.nbconvert.filters.strings import add_anchor
from IPython.nbconvert.utils.exceptions import ConversionException
from IPython.utils.decorators import undoc


@undoc
class MathBlockGrammar(mistune.BlockGrammar):
    block_math = re.compile(r"^\$\$(.*?)\$\$", re.DOTALL)
    latex_environment = re.compile(r"^\\begin\{([a-z]*\*?)\}(.*?)\\end\{\1\}",
                                                re.DOTALL)

@undoc
class MathBlockLexer(mistune.BlockLexer):
    default_rules = ['block_math', 'latex_environment'] + mistune.BlockLexer.default_rules

    def __init__(self, rules=None, **kwargs):
        if rules is None:
            rules = MathBlockGrammar()
        super(MathBlockLexer, self).__init__(rules, **kwargs)

    def parse_block_math(self, m):
        """Parse a $$math$$ block"""
        self.tokens.append({