Snippets

Denis Nelubin Markdown to HTML converter for Blogger

Created by Denis Nelubin
#!/usr/bin/python3

import sys
import codecs
import hoep
from pygments import highlight
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.formatters import HtmlFormatter
import pyperclip


class MyRenderer(hoep.Hoep):

    def __init__(self, extensions = 0, render_flags = 0):
        super(MyRenderer, self).__init__(extensions, render_flags)

    def paragraph(self, text):
        return '<div style="margin-top: 0.7em;">' + text + "</div>\n"

    def image(self, link, title, alt):
        return '<div style="text-align: center;"><img alt="{}" width="640" src="{}" /></div>'.format(alt, link)

    def codespan(self, text):
        return '<code style="background: #f5f5f5; border: 1px solid #ccc; border-radius: 3px; padding: 1px 3px;">' + \
               text + '</code>'

    def block_code(self, text, language):
        if language:
            lexer = get_lexer_by_name(language)
        elif text.startswith(':::'):
            (language, text) = text.split('\n', 1)
            language = language[3:]
            # text = language + '\n\n' + text
            lexer = get_lexer_by_name(language)
        else:
            lexer = guess_lexer(text)

        return '<pre style="background: #f5f5f5; border: 1px solid #ccc; border-radius: 3px; ' + \
               'overflow-x: auto; padding: 5px 10px; word-wrap: normal;">{}</pre>'.format(
                    highlight(text, lexer, HtmlFormatter(nowrap=True, noclasses=True)))


filename = sys.argv[1]
input_file = codecs.open(filename, mode="r", encoding="utf-8")
text = input_file.read()

extensions = hoep.EXT_FENCED_CODE + hoep.EXT_HIGHLIGHT
render_flags = 0
html = MyRenderer(extensions, render_flags).render(text)

pyperclip.copy(html)
print(filename, 'is converted to html and copied to clipboard')

Comments (0)