Python markdown2.markdown() Examples

The following are 30 code examples of markdown2.markdown(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module markdown2 , or try the search function .
Example #1
Source File: markdown.py    From FIR with GNU General Public License v3.0 7 votes vote down vote up
def rich_edit_static(context):

    files = [
        "<link href=\"%s\" rel=\"stylesheet\"/>" % static(
            "simplemde/simplemde.min.css"),
        "<link href=\"%s\" rel=\"stylesheet\"/>" % static(
            "font-awesome/css/font-awesome.min.css"),
        "<script type=\"text/javascript\" src=\"%s\"></script>" % static(
            "simplemde/marked.min.js"),
        "<script type=\"text/javascript\" src=\"%s\"></script>" % static(
            "simplemde/simplemde.min.js"),
        "<script type=\"text/javascript\" src=\"%s\"></script>" % static(
            "simplemde/inline-attachment.min.js"),
        "<script type=\"text/javascript\" src=\"%s\"></script>" % static(
            "simplemde/codemirror.inline-attachment.js"),
        "<script type=\"text/javascript\" src=\"%s\"></script>" % static(
            "simplemde/markdown.js")
    ]
    return mark_safe("\n".join(files)) 
Example #2
Source File: convert-readme.py    From chinese-support-redux with GNU General Public License v3.0 7 votes vote down vote up
def main():
    """Covert GitHub mardown to AnkiWeb HTML."""
    # permitted tags: img, a, b, i, code, ul, ol, li

    translate = [
        (r'<h1>([^<]+)</h1>', r''),
        (r'<h2>([^<]+)</h2>', r'<b><i>\1</i></b>\n\n'),
        (r'<h3>([^<]+)</h3>', r'<b>\1</b>\n\n'),
        (r'<strong>([^<]+)</strong>', r'<b>\1</b>'),
        (r'<em>([^<]+)</em>', r'<i>\1</i>'),
        (r'<kbd>([^<]+)</kbd>', r'<code><b>\1</b></code>'),
        (r'</a></p>', r'</a></p>\n'),
        (r'<p>', r''),
        (r'</p>', r'\n\n'),
        (r'</(ol|ul)>(?!</(li|[ou]l)>)', r'</\1>\n'),
    ]

    with open('README.md', encoding='utf-8') as f:
        html = ''.join(filter(None, markdown(f.read()).split('\n')))

    for a, b in translate:
        html = sub(a, b, html)

    with open('README.html', 'w', encoding='utf-8') as f:
        f.write(html.strip()) 
Example #3
Source File: jabber.py    From FIR with GNU General Public License v3.0 7 votes vote down vote up
def send(self, event, users, instance, paths):
        if not self._ensure_connection():
            print("Cannot contact the XMPP server")
            return
        for user, templates in users.items():
            jid = self._get_jid(user)
            if not self.enabled(event, user, paths) or jid is None:
                continue
            template = self._get_template(templates)
            if template is None:
                continue
            params = self.prepare(template, instance)
            message = xmpp.protocol.Message(jid, body=params['short_description'].encode('utf-8'),
                                            subject=params['subject'].encode('utf-8'), typ='chat')
            html = xmpp.Node('html', {'xmlns': 'http://jabber.org/protocol/xhtml-im'})
            text = u"<body xmlns='http://www.w3.org/1999/xhtml'>" + markdown2.markdown(params['short_description'],
                                                                                       extras=["link-patterns"],
                                                                                       link_patterns=link_registry.link_patterns(
                                                                                           request),
                                                                                       safe_mode=True) + u"</body>"
            html.addChild(node=xmpp.simplexml.XML2Node(text.encode('utf-8')))
            message.addChild(node=html)

            self.client.send(message)
        self.client.disconnected() 
Example #4
Source File: markdown_to_pdf.py    From recordexpungPDX with MIT License 7 votes vote down vote up
def to_pdf(title: str, markdown_source: str) -> bytes:
        html_style = MarkdownToPDF.css()
        html_body = markdown2.markdown(markdown_source)
        html = f"""
        <html>
        <head>
            <meta charset="utf-8">
            <title>{title}</title>
            <style>
                {html_style}
            </style>
        </head>
        <body class="markdown-body">
            {html_body}
        </body>
        </html>
        """
        return pdfkit.from_string(html, False, options={"quiet": ""}) 
Example #5
Source File: handlers.py    From Preeminent with MIT License 6 votes vote down vote up
def get_blog(id, request):
    blog = yield from Blog.find(id)  # 通过id从数据库中拉去博客信息
    # 从数据库拉取指定blog的全部评论,按时间降序排序,即最新的排在最前
    comments = yield from Comment.findAll('blog_id=?', [id], orderBy='created_at desc')
    # 将每条评论都转化成html格式
    for c in comments:
        c.html_content = text2html(c.content)
    # blog也是markdown格式,将其转化成html格式
    blog.html_content = markdown2.markdown(blog.content)
    return {
        '__template__': 'blog.html',
        'blog': blog,
          '__user__':request.__user__,
        'comments': comments
    }


# day10中定义
# 页面:注册页面 
Example #6
Source File: real_time_analysis.py    From jd_analysis with GNU Lesser General Public License v3.0 6 votes vote down vote up
def record_result(self, result, color = 'default', font_size = 16, strong = False, type = 'word',
                      br = True, default = False, new_line = False):
        self.full_result = ''
        if type == 'word' and default == False:
            if strong:
                result = '<strong style="color: %s; font-size: %spx;">%s</strong>' % (color, font_size, result)
            else:
                result = '<span style="color: %s; font-size: %spx;">%s</span>' % (color, font_size, result)
        elif type == 'image':
            result = markdown2.markdown(result)

        self.full_result += result

        if br:
            self.full_result += '<br>'
        if new_line:
            self.full_result += '\n'

        utils.push_redis(guid = self.guid, product_id = self.product_id, info = self.full_result, type = type)

    # 提取商品的基本信息 
Example #7
Source File: views.py    From jd_analysis with GNU Lesser General Public License v3.0 6 votes vote down vote up
def get(self, request, param):
        print('path:%s param:%s' % (request.path, param))
        try:
            article = JDCommentAnalysis.objects.filter(Q(guid__iexact = param) | Q(product_id__iexact = param)).first()
            article.content = markdown2.markdown(text = article.content, extras = {
                'tables': True,
                'wiki-tables': True,
                'fenced-code-blocks': True,
            })

            context = {
                'article': article
            }

            return render(request, 'full_result.html', context = context)
        except:
            return render(request, '404.html') 
Example #8
Source File: metadata.py    From backtrader_plotting with GNU General Public License v3.0 6 votes vote down vote up
def get_metadata_div(strategy: bt.Strategy) -> str:
    md = ""

    md += _get_strategy(strategy)
    md += '* * *'
    md += _get_datas(strategy)
    md += '* * *'
    md += _get_observers(strategy)
    md += '* * *'
    md += _get_analyzers(strategy)
    md += '* * *'

    css_classes = {'table': 'metaDataTable'}

    html = markdown2.markdown(md, extras={
        'fenced-code-blocks': None,
        'tables': None,
        'html-classes': css_classes
    })
    return html 
Example #9
Source File: build.py    From TiLogCatcher with MIT License 6 votes vote down vote up
def generate_doc(config):
	docdir = os.path.join(cwd,'documentation')
	if not os.path.exists(docdir):
		warn("Couldn't find documentation file at: %s" % docdir)
		return None

	try:
		import markdown2 as markdown
	except ImportError:
		import markdown
	documentation = []
	for file in os.listdir(docdir):
		if file in ignoreFiles or os.path.isdir(os.path.join(docdir, file)):
			continue
		md = open(os.path.join(docdir,file)).read()
		html = markdown.markdown(md)
		documentation.append({file:html});
	return documentation 
Example #10
Source File: controllers.py    From sample-platform with ISC License 6 votes vote down vote up
def get_html_issue_body(title, author, body, issue_number, url) -> Any:
    """
    Curate a HTML formatted body for the issue mail.

    :param title: title of the issue
    :type title: str
    :param author: author of the issue
    :type author: str
    :param body: content of the issue
    :type body: str
    :param issue_number: issue number
    :type issue_number: int
    :param url: link to the issue
    :type url: str
    :return: email body in html format
    :rtype: str
    """
    from run import app

    html_issue_body = markdown(body, extras=["target-blank-links", "task_list", "code-friendly"])
    template = app.jinja_env.get_or_select_template("email/new_issue.txt")
    html_email_body = template.render(title=title, author=author, body=html_issue_body, url=url)
    return html_email_body 
Example #11
Source File: converters.py    From pyLanguagetool with MIT License 6 votes vote down vote up
def markdown2html(markdown):
    """
    convert Markdown to HTML via ``markdown2``

    Args:
        markdown (str):
            Markdown text

    Returns:
        str: HTML
    """
    try:
        import markdown2
    except ImportError:
        notinstalled("markdown2", "markdown", "HTML")
        sys.exit(4)

    return markdown2.markdown(markdown) 
Example #12
Source File: MarkdownView.py    From pythonista-scripts with MIT License 6 votes vote down vote up
def to_html(self, md = None, scroll_pos = -1, content_only = False):
		md = md or self.markup.text
		result = markdown(md, extras=self.extras)
		if not content_only:
			intro = Template(self.htmlIntro.safe_substitute(css = self.css))
			(font_name, font_size) = self.font
			result = intro.safe_substitute(
				background_color = self.to_css_rgba(self.markup.background_color), 
				text_color = self.to_css_rgba(self.markup.text_color),
				font_family = font_name,
				text_align = self.to_css_alignment(),
				font_size = str(font_size)+'px',
				init_postfix = self.init_postfix,
				link_prefix = self.link_prefix,
				debug_prefix = self.debug_prefix,
				scroll_pos = scroll_pos
			) + result + self.htmlOutro
		return result 
Example #13
Source File: MarkdownView.py    From pythonista-scripts with MIT License 6 votes vote down vote up
def preferred_size(self, using='current', min_width=None, max_width=None, min_height=None, max_height=None):
		
		if using=='current':
			using = 'markdown' if self.editing else 'html'
				
		if using=='markdown':
			self.markup_ghost.text = self.markup.text
			view = self.markup_ghost
		else:
			view = self.web_ghost
		
		view.size_to_fit()
		if max_width and view.width > max_width:
			view.width = max_width
			view.size_to_fit()
		if max_width and view.width > max_width:
			view.width = max_width
		if min_width and view.width < min_width:
			view.width = min_width
		if max_height and view.height > max_height:
			view.height = max_height
		if min_height and view.height < min_height:
			view.height = min_height

		return (view.width, view.height) 
Example #14
Source File: converters.py    From pyLanguagetool with MIT License 6 votes vote down vote up
def ipynb2markdown(ipynb):
    """
    Extract Markdown cells from iPython Notebook

    Args:
        ipynb (str):
            iPython notebook JSON file

    Returns:
        str: Markdown
    """
    j = json.loads(ipynb)
    markdown = ""
    for cell in j["cells"]:
        if cell["cell_type"] == "markdown":
            markdown += "".join(cell["source"]) + "\n"
    return markdown 
Example #15
Source File: TestMarkdown.py    From sample-platform with ISC License 5 votes vote down vote up
def test_italics_text(self):
        """
        test conversion of markdown italics to html
        """
        mkdown_test1 = "*I'm a emphasized text*"
        expected_test1 = "<p><em>I'm a emphasized text</em></p>\n"

        html_test1 = markdown(mkdown_test1)

        assert expected_test1 == html_test1, "wrong conversion for italics text" 
Example #16
Source File: TestMarkdown.py    From sample-platform with ISC License 5 votes vote down vote up
def test_strong_text(self):
        """
        test conversion of markdown bold to html
        """
        mkdown_test1 = "**I'm a strong text**"
        expected_test1 = "<p><strong>I'm a strong text</strong></p>\n"

        html_test1 = markdown(mkdown_test1)

        assert expected_test1 == html_test1, "wrong conversion for bold text" 
Example #17
Source File: urls.py    From awesome-python3-webapp with GNU General Public License v2.0 5 votes vote down vote up
def api_get_blogs():
    format = ctx.request.get('format', '')
    blogs, page = _get_blogs_by_page() 
    if format=='html':
        for blog in blogs:
            blog.content = markdown2.markdown(blog.content,extras=["code-friendly","fenced-code-blocks"])
    return dict(blogs=blogs, page=page) 
Example #18
Source File: TestMarkdown.py    From sample-platform with ISC License 5 votes vote down vote up
def test_heading(self):
        """
        test conversion of markdown heading to html
        """
        mkdown_test1 = "# I'm a heading"
        expected_test1 = "<h1>I'm a heading</h1>\n"

        mkdown_test2 = "## I'm a heading"
        expected_test2 = "<h2>I'm a heading</h2>\n"

        html_test1 = markdown(mkdown_test1)
        html_test2 = markdown(mkdown_test2)

        assert expected_test1 == html_test1, "wrong conversion for heading 1"
        assert expected_test2 == html_test2, "wrong conversion for heading 2" 
Example #19
Source File: markdown_to_pdf.py    From recordexpungPDX with MIT License 5 votes vote down vote up
def css():
        response = requests.get(
            "https://raw.githubusercontent.com/sindresorhus/github-markdown-css/gh-pages/github-markdown.css"
        )
        return response.text 
Example #20
Source File: formatter.py    From slack-export-viewer with MIT License 5 votes vote down vote up
def render_text(self, message, process_markdown=True):
        message = message.replace("<!channel>", "@channel")
        message = message.replace("<!channel|@channel>", "@channel")
        message = message.replace("<!here>", "@here")
        message = message.replace("<!here|@here>", "@here")
        message = message.replace("<!everyone>", "@everyone")
        message = message.replace("<!everyone|@everyone>", "@everyone")
        message = self._slack_to_accepted_emoji(message)

        # Handle mentions of users, channels and bots (e.g "<@U0BM1CGQY|calvinchanubc> has joined the channel")
        message = self._MENTION_PAT.sub(self._sub_annotated_mention, message)
        # Handle links
        message = self._LINK_PAT.sub(self._sub_hyperlink, message)
        # Handle hashtags (that are meant to be hashtags and not headings)
        message = self._HASHTAG_PAT.sub(self._sub_hashtag, message)

        # Introduce unicode emoji
        message = emoji.emojize(message, use_aliases=True)

        if process_markdown:
            # Handle bold (convert * * to ** **)
            message = re.sub(r'\*', "**", message)

            message = markdown2.markdown(
                message,
                extras=[
                    "cuddled-lists",
                    # This gives us <pre> and <code> tags for ```-fenced blocks
                    "fenced-code-blocks",
                    "pyshell"
                ]
            ).strip()

        # Special handling cases for lists
        message = message.replace("\n\n<ul>", "<ul>")
        message = message.replace("\n<li>", "<li>")

        return message 
Example #21
Source File: TestMarkdown.py    From sample-platform with ISC License 5 votes vote down vote up
def test_link_text(self):
        """
        test conversion of markdown hyperlinks to html
        """
        mkdown_test1 = "[i'm a hyperlink](www.example.com)"
        expected_test1 = """<p><a href="www.example.com">i'm a hyperlink</a></p>\n"""

        html_test1 = markdown(mkdown_test1)

        assert expected_test1 == html_test1, "wrong conversion for hyperlink text" 
Example #22
Source File: TestMarkdown.py    From sample-platform with ISC License 5 votes vote down vote up
def test_list_text(self):
        """
        test conversion of markdown list to html
        """
        mkdown_test1 = "- i'm a list text"
        expected_test1 = "<ul>\n<li>i'm a list text</li>\n</ul>\n"

        html_test1 = markdown(mkdown_test1)

        assert expected_test1 == html_test1, "wrong conversion for list text" 
Example #23
Source File: TestMarkdown.py    From sample-platform with ISC License 5 votes vote down vote up
def test_quote_text(self):
        """
        test conversion of markdown quote text to html
        """
        mkdown_test1 = "> i'm a quote"
        expected_test1 = "<blockquote>\n  <p>i'm a quote</p>\n</blockquote>\n"

        html_test1 = markdown(mkdown_test1)

        assert expected_test1 == html_test1, "wrong conversion for quote text" 
Example #24
Source File: TestMarkdown.py    From sample-platform with ISC License 5 votes vote down vote up
def test_extra_link_new_tab(self):
        """
        test addition of target="_blank" attribute to anchor tags
        """
        mkdown_test1 = "[I'll open in new tab](www.example.com)"
        expected_test1 = """<p><a target="_blank" href="www.example.com">I'll open in new tab</a></p>\n"""

        html_test1 = markdown(mkdown_test1, extras=["target-blank-links"])

        assert expected_test1 == html_test1, "no target attribute added to anchor tag" 
Example #25
Source File: TestMarkdown.py    From sample-platform with ISC License 5 votes vote down vote up
def test_extra_task_list(self):
        """
        test addition of target="_blank" attribute to anchor tags
        """
        mkdown_test1 = "- [x] I'm a task"
        expected_test1 = ("""<ul>\n<li><input type="checkbox" class="task-list-item-checkbox" checked disabled> """
                          """I'm a task</li>\n</ul>\n""")

        html_test1 = markdown(mkdown_test1, extras=["task_list"])

        assert expected_test1 == html_test1, "no target attribute added to anchor tag" 
Example #26
Source File: TestMarkdown.py    From sample-platform with ISC License 5 votes vote down vote up
def test_extra_code_friendliness(self):
        """
        test no conversion of markdown code style bold and italics to html
        """
        mkdown_test1 = "__I'm not a strong text__"
        expected_test1 = "<p>__I'm not a strong text__</p>\n"

        mkdown_test2 = "_I'm not an italics text_"
        expected_test2 = "<p>_I'm not an italics text_</p>\n"

        html_test1 = markdown(mkdown_test1, extras=["code-friendly"])
        html_test2 = markdown(mkdown_test2, extras=["code-friendly"])

        assert expected_test1 == html_test1, "wrong conversion for code-style bold text"
        assert expected_test2 == html_test2, "wrong conversion for code-style italics text" 
Example #27
Source File: services.py    From junction with MIT License 5 votes vote down vote up
def markdown_to_html(md):
    """
    Convert given markdown to html.
    :param md: string
    :return: string - converted html
    """
    return markdown(md) 
Example #28
Source File: markdown_tags.py    From mitoc-trips with GNU General Public License v3.0 5 votes vote down vote up
def markdown_filter(text):
    return mark_safe(markdown2.markdown(text, safe_mode="escape")) 
Example #29
Source File: md2html.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def main():
    text = None
    label = 'Shared text'
    if appex.is_running_extension():
        text = appex.get_text()
    if not text:
        try:
            import editor
            editor_file = editor.get_path()
            if editor_file:
                sel = console.alert('Editor or clipboard?', button1='Editor', button2='Clipboard')
                if sel == 1:
                    editor_text = editor.get_text()
                    sel_st, sel_end = editor.get_selection()
                    label = os.path.basename(editor_file)
                    if sel_end != sel_st:
                        text = editor_text[sel_st:sel_end]
                    elif editor_text:
                        text = editor_text
        except ImportError:
            pass
    if not text:
        label = 'Clipboard'
        text = clipboard.get().strip()
    if text:
        converted = markdown(text)
        html = TEMPLATE.replace('{{CONTENT}}', converted)

        clip = console.alert('Replace clipboard?', button1='Yes', button2='No', hide_cancel_button=True)
        if clip ==1:
            clipboard.set(html)
            console.hud_alert('HTML copied to clipboard.')
        wv = MyWebView(name='Markdown - %s' % label)
        wv.load_html(html)
        wv.present('full_screen')
    else:
        console.hud_alert('No text found.')
        appex.finish() 
Example #30
Source File: feeds.py    From community with GNU Affero General Public License v3.0 5 votes vote down vote up
def item_description(self, item):
        desc = item['description']
        if item['external_url']:
            desc += '\n\nExternal URL: [{url}]({url})'.format(
                url=item['external_url'])
        return markdown2.markdown(desc)