Ejemplo n.º 1
0
def markdown(text,
             heading_baselevel=1,
             filter_tags=True,
             truncate=False,
             disable_tags="",
             plain_preview=False,
             preset=None,
             plain=False):
    def wrap(result):
        if plain or plain_preview:
            return result
        else:
            script = """
            <script type='text/markdown' data-original-content>{}</script>
            """.format(json.dumps(html.escape(text)))
            return "<div>{}{}</div>".format(script, result)

    extensions = tuple(core_markdown.markdown_extensions) + (toc.TocExtension(
        baselevel=heading_baselevel, marker='[INHALT]'), )
    result = python_markdown.markdown(text, extensions=extensions)
    if preset == 'linkonly':
        result = bleach(result, disable_tags='all', except_for=('a', ))
    elif filter_tags:
        disabled_tags = tuple(disable_tags.split(","))
        result = bleach(result, disabled_tags)
    if truncate:
        result = defaultfilters.truncatewords_html(result, truncate)
    if plain_preview:
        result = bleach(result, disable_tags="all")
        result = defaultfilters.truncatewords(result, plain_preview)
        result = django_html.conditional_escape(result)

    return safestring.mark_safe(wrap(result))
def write_output(args):
    converter = markdown.Markdown(
        extensions=[
            mdx_tables.TableExtension(),
            mdx_sane_lists.SaneListExtension(),
            mdx_smarty.SmartyExtension(),
            mdx_toc.TocExtension(),
        ],
        output_format='html5',
    )
    with args.input_path.open(encoding=args.encoding) as src_file:
        body = converter.convert(src_file.read())
    with tempfile.NamedTemporaryFile(
            'w',
            encoding=args.encoding,
            dir=args.git_output.dir_path.as_posix(),
            suffix='.html',
            delete=False,
    ) as tmp_out:
        try:
            tmp_out.write(TEMPLATE_HEADER)
            tmp_out.write(body)
            tmp_out.write(TEMPLATE_FOOTER)
            tmp_out.flush()
            os.rename(tmp_out.name, str(args.output_file_path))
        except BaseException:
            os.unlink(tmp_out.name)
            raise
    if args.output_link_path.is_symlink():
        args.output_link_path.unlink()
    args.output_link_path.symlink_to(args.output_file_path.name)
Ejemplo n.º 3
0
 def html(self):
   val = self.body
   if val is not None:
     extensions = [
       tables.TableExtension(),
       toc.TocExtension(),
       markdown_extensions.CodeBlockExtension(),
       markdown_extensions.IncludeExtension(self.doc.pod),
       markdown_extensions.UrlExtension(self.doc.pod),
     ]
     val = markdown.markdown(val.decode('utf-8'), extensions=extensions)
   return val
Ejemplo n.º 4
0
 def render_to_html_string(self):
     """
     Render the watched document to html, returning the html string
     :return: The rendered HTML of the markdown file
     """
     self.logger.debug('Rendering markdown (%s)', self.filename)
     fake_file = BytesIO()
     markdown.markdownFromFile(input=self.filename,
                               output=fake_file,
                               extensions=[abbr.AbbrExtension(), admonition.AdmonitionExtension(),
                                           attr_list.AttrListExtension(), codehilite.CodeHiliteExtension(),
                                           def_list.DefListExtension(), extra.ExtraExtension(),
                                           fenced_code.FencedCodeExtension(), footnotes.FootnoteExtension(),
                                           legacy_attrs.LegacyAttrExtension(), legacy_em.LegacyEmExtension(),
                                           meta.MetaExtension(), nl2br.Nl2BrExtension(),
                                           sane_lists.SaneListExtension(), smarty.SmartyExtension(),
                                           tables.TableExtension(), toc.TocExtension(),
                                           wikilinks.WikiLinkExtension()])
     fake_file.seek(0)
     return str(fake_file.read(), 'utf-8')
Ejemplo n.º 5
0
    def __init__(self, main_window):
        """
		desc:
			Constructor.

		arguments:
			main_window:	The main-window object.
		"""

        self.setup(main_window)
        self.css = u'<style type="text/css">'
        with safe_open(self.main_window.theme.resource(u'markdown.css')) as fd:
            self.css += fd.read() % {u'background_image' : \
             os.path.abspath(self.main_window.theme.resource(
             u'background.png'))}
        if highlight is not None:
            self.traceback_lexer = TracebackLexer()
            self.python_lexer = PythonLexer()
            self.html_formatter = HtmlFormatter()
            self.css += self.html_formatter.get_style_defs(u'.highlight')
            self.re_script = re.compile(
                r'^~~~\s*.(?P<syntax>\w+)(?P<script>.*?)^~~~', re.S | re.M)
        self.css += u'</style>'
        if markdown is not None:
            self.ext = [
                attr_list.AttrListExtension(),
                extra.ExtraExtension(),
                toc.TocExtension(title=u'Overview'),
                u'markdown.extensions.tables'
            ]
        self.footer = u'''
<p>
<a class="dismiss-button" href="opensesame://action.close_current_tab">%s</a>
</p>

<div class="footer">
OpenSesame %s %s —
Copyright <a href="http://www.cogsci.nl/smathot">Sebastiaan Mathôt</a> 2010-2018
</div>
''' % (_(u'Dismiss this message'), metadata.__version__, metadata.codename)
Ejemplo n.º 6
0
from flask import url_for
from jinja2 import Template
from knowledge_repo.post import KnowledgePost
from markdown.extensions import toc
import markdown
import pygments

MARKDOWN_EXTENSIONS = [
    'extra', 'abbr', 'attr_list', 'def_list', 'fenced_code', 'footnotes',
    'tables', 'admonition', 'codehilite', 'meta', 'sane_lists', 'smarty',
    toc.TocExtension(baselevel=1), 'wikilinks', 'nl2br'
]


def render_post_tldr(post):
    if isinstance(post, KnowledgePost):
        return markdown.Markdown(extensions=MARKDOWN_EXTENSIONS).convert(
            post.headers.get('tldr').strip())
    else:
        return markdown.Markdown(extensions=MARKDOWN_EXTENSIONS).convert(
            post.tldr.strip())


def render_post_header(post):

    header_template = Template("""
    <div class='metadata'>
    <span class='title'>{{title}}</span>
    {% if subtitle %}<span class='subtitle'>{{subtitle}}</span>{% endif %}
    <span class='authors'>{{authors}}</span>
    <span class='date_created'>{{date_created}}</span>
Ejemplo n.º 7
0
import markdown
import mimetypes

MARKDOWN_EXTENSIONS = ['extra',
                       'abbr',
                       'attr_list',
                       'def_list',
                       'fenced_code',
                       '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)
Ejemplo n.º 8
0
import markdown.extensions.toc as toc

import warnings
import os

content_path = 'content/'

app = flask.Flask(__name__)
db_login = {
    'host': 'db',  # host ip address
    'port': 6379,
    # 'password': '******'
    'decode_responses': True
}

toc_extension = toc.TocExtension(baselevel=2)
markdown_parser = markdown.Markdown(
    extensions=[toc_extension, 'markdown.extensions.smarty'],
    output_format='html5')


@app.route('/articles/<name>')
def show_article(name):
    db = get_db()
    title, author = db.hmget(name + ':metadata', 'title', 'author')
    text = db.get(name + ':text')
    return flask.render_template('article_layout.html',
                                 title=title,
                                 author=author,
                                 text=text)
Ejemplo n.º 9
0
from flask_login import login_required

from dli_app import db
from dli_app import mail
from dli_app import flash_form_errors

from dli_app.mod_wiki.models import WikiPage

from dli_app.mod_wiki.forms import EditWikiPageForm
from dli_app.mod_wiki.forms import SearchForm
from dli_app.mod_wiki.forms import AskQuestionForm

EXTENSIONS = [
    extra.ExtraExtension(),
    nl2br.Nl2BrExtension(),
    toc.TocExtension(),
    wikilinks.WikiLinkExtension(base_url='/wiki/'),
]

MD = Markdown(extensions=EXTENSIONS)

# Create a blueprint for this module
mod_wiki = Blueprint('wiki', __name__, url_prefix='/wiki')


# Set all routing for the module
@mod_wiki.route('/', methods=['GET'])
@mod_wiki.route('/home', methods=['GET'])
@mod_wiki.route('/home/', methods=['GET'])
def home():
    """Render the wiki homepage"""
Ejemplo n.º 10
0
def load_markdown():
    ext_toc = toc.TocExtension(marker=None)
    ext_github = github.GithubExtension(no_nl2br=True)
    extensions = [ext_github, 'markdown.extensions.codehilite', ext_toc]

    return markdown.Markdown(extensions=extensions)