How to use the mistune.Renderer 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 thoppe / miniprez / block_custom_parser.py View on Github external
import copy, re
from mistune import Renderer, InlineGrammar, InlineLexer, Markdown
from mistune import BlockGrammar, BlockLexer, Markdown


def get_classnames(class_string):
    s = " ".join(class_string.strip().lstrip(".").split("."))
    return s if s else None


class DivClassRenderer(Renderer):
    def OpenBlockClass(self, names):
        return f"<div class="{names}">"

    def CloseBlockClass(self):
        return f"</div>"

    def LineBlockClass(self, names, remaining):
        remaining = remaining.lstrip()
        return f"<div class="{names}">{remaining}</div>"


class DivClassInlineLexer(InlineLexer):

    rule_num = 0

    def enable(self):
github coogger / coogger / core / cooggerapp / models.py View on Github external
def marktohtml(marktext):
        renderer = Renderer(escape=False, parse_block_html=True)
        markdown = Markdown(renderer=renderer)
        return BeautifulSoup(markdown(marktext), "html.parser")
github demisto / dockerfiles / docker / sane-doc-reports / src / sane_doc_reports / transform / markdown / md_helpers.py View on Github external
def markdown_convert(markdown_string) -&gt; str:
    def _get_contents(text):
        try:
            contents = json.loads(text).get('message', '')
        except json.decoder.JSONDecodeError:
            contents = text
        except AttributeError:
            contents = text

        return contents

    class ButtonRenderer(mistune.Renderer):
        '''
        Syntax for MD buttons
            %%%{JSON.message}%%%
        For example:
            %%%%{"message": "Something here"}%%%%
        Output:
            Something here
        '''

        def paragraph(self, text):
            text = _get_contents(text)
            return f'<p>{text}</p>'

    class ButtonInlineLexer(mistune.InlineLexer):
        def enable_md_button(self):
            self.rules.md_button = re.compile(r'%%%(.*?)%%%')
github xalanq / ITree / imarkdown.py View on Github external
class MarkdownWithMath(mistune.Markdown):
	def __init__(self, renderer, **kwargs):
		if 'inline' not in kwargs:
			kwargs['inline'] = MathInlineLexer
		if 'block' not in kwargs:
			kwargs['block'] = MathBlockLexer
		super(MarkdownWithMath, self).__init__(renderer, **kwargs)

	def output_block_math(self):
		return self.renderer.block_math(self.token['text'])

	def output_latex_environment(self):
		return self.renderer.latex_environment(self.token['name'], self.token['text'])


class IMarkdownRenderer(mistune.Renderer):
	""" renderer of markdown """
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)

	def link(self, link, title, text):
		"""
		<a title="xxx">xxx</a>
		"""
		link = mistune.escape(link.replace('"', '"')) if link else ''
		text = mistune.escape(text) if text else ''
		title = mistune.escape(title.replace('"', '"')) if title else ''
		# print('<a title="{}" href="{}">{}</a>'.format(link, title, text))

		return '<a title="{}" href="{}">{}</a>'.format(link, title, text)

	def block_code(self, code, lang=None):
github chris104957 / maildown / maildown / renderer.py View on Github external
import os
from typing import Optional
import jinja2
import mistune
import pygments
from pygments import lexers
from pygments.formatters import html
import premailer


class HighlightRenderer(mistune.Renderer):
    """
    This highlight renderer improves the way code blocks are handled
    """

    @staticmethod
    def block_code(code, lang=None):
        if not lang:
            return "\n<pre><code>%s</code></pre>\n" % mistune.escape(code)
        lexer = lexers.get_lexer_by_name(lang, stripall=True)
        formatter = html.HtmlFormatter()
        return pygments.highlight(code, lexer, formatter)


def generate_content(
    md_content: str, theme: Optional[str] = None, context: Optional[dict] = None
):
github common-workflow-language / common-workflow-language / reference / cwltool / avro_ld / makedoc.py View on Github external
def has_types(items):
    r = []
    if isinstance(items, dict):
        for n in ("type", "items", "values"):
            if n in items:
                r.extend(has_types(items[n]))
        return r
    if isinstance(items, list):
        for i in items:
            r.extend(has_types(i))
        return r
    if isinstance(items, basestring):
        return [items]
    return []

class MyRenderer(mistune.Renderer):
    def header(self, text, level, raw=None):
        return """<h1 id="%s">%s</h1>""" % (to_id(text), text)

def to_id(text):
    textid = text
    if text[0] in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"):
        try:
            textid = text[text.index(" ")+1:]
        except ValueError:
            pass
    textid = textid.lower().replace(" ", "_")
    return textid

class ToC(object):
    def __init__(self):
        self.first_toc_entry = True
github crossbario / crossbar / docs-old / markdown.py View on Github external
def link(self, link, title, content):
      if not (link.startswith('http') or link.startswith('/') or link.startswith('#')):
         if self._prefix:
            link = "{}/{}/".format(self._prefix, link.replace(' ', '-'))
         else:
            link = "{}/".format(link.replace(' ', '-'))

      if self.debug:
         print("link", link, title, content)
      return mistune.Renderer.link(self, link, title, content)
github common-workflow-language / cwltool / cwltool / schemas / draft-3 / salad / schema_salad / makedoc.py View on Github external
if n in items:
                r.extend(has_types(items[n]))
        return r
    if isinstance(items, MutableSequence):
        for i in items:
            r.extend(has_types(i))
        return r
    if isinstance(items, basestring):
        return [items]
    return []

def linkto(item):
    _, frg = urlparse.urldefrag(item)
    return "[%s](#%s)" % (frg, to_id(frg))

class MyRenderer(mistune.Renderer):
    def header(self, text, level, raw=None):
        return """%s""" % (level, to_id(text), text)

def to_id(text):
    textid = text
    if text[0] in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"):
        try:
            textid = text[text.index(" ")+1:]
        except ValueError:
            pass
    textid = textid.replace(" ", "_")
    return textid

class ToC(object):
    def __init__(self):
        self.first_toc_entry = True
github f1nnix / magplan / xmd / renderer.py View on Github external
import typing as tp

from mistune import Renderer


class XMDRenderer(Renderer):
    def __init__(self, image_mapper: tp.Callable, attachments: tp.List = None, *args, **kwargs):
        self.attachments = attachments or []
        self.image_mapper = image_mapper

        super(XMDRenderer, self).__init__(*args, **kwargs)

    def image(self, src, title, alt_text):
        # Map human-readable filename to urlencoded one
        urlencoded_filename = self.image_mapper(src, self.attachments)

        html = (
            '<figure>'
            '<img alt="%s" src="%s">'
            '<figcaption>%s</figcaption>'
            '</figure>'
        )
github mrjbq7 / ta-lib / docs / generate_html_pages.py View on Github external
def _get_markdown_renderer():
    """Returns a function to convert a Markdown string into pygments-highlighted HTML"""
    class PygmentsHighlighter(mistune.Renderer):
        def block_code(self, code, lang=None):
            if not lang:
                return '\n<pre><code>%s</code></pre>\n' % mistune.escape(code)
            lexer = get_lexer_by_name(lang, stripall=True)
            formatter = HtmlFormatter(classprefix='highlight ')
            return highlight(code, lexer, formatter)
    return mistune.Markdown(renderer=PygmentsHighlighter())