Exemplo n.º 1
0
    def setup(self):
        self.r = Markdown(HtmlRenderer()).render

        tests_dir = path.dirname(__file__)
        for text_path in glob(path.join(tests_dir, self.suite, '*.text')):
            html_path = '%s.html' % path.splitext(text_path)[0]
            self._create_test(text_path, html_path)
Exemplo n.º 2
0
def description(job_id):
    # SELECT JOB FROM DATABASE
    job = select_job(job_id)
    # render descripton markdown to html
    render = HtmlRenderer()
    md = Markdown(render)
    job["description"] = Markup(md(job.get("description")))
    return render_template("description.html", job=job)
Exemplo n.º 3
0
    def block_code(self, text, lang):

        if lang == 'figure':
            #process figure block
            print("Found a figure!")
            return

        # pass through
        return HtmlRenderer.block_code(self, text, lang)
Exemplo n.º 4
0
def preview():
    from misaka import Markdown, HtmlRenderer
    if request.method == "POST":
        content = request.args.get('content')
        html = HtmlRenderer()
        markdown = Markdown(html)
        return Markup(markdown(content))
    else:
        abort(404)
Exemplo n.º 5
0
def read(request, slug):
    articles = get_list_or_404(Article, slug=slug, publie=True)
    article = articles[0]
    categories = [cat.nom for cat in article.categorie.all()]

    tiret = "-"
    categories = tiret.join(categories)

    # for some special posts, we use js code, so we use specific template
    retour = jump_special_view(request, locals())

    if retour:
        return retour

    url_article = '{}'.format(getattr(article, 'urlGitHub'))
    response = get_article_from_local(url_article)
    extension = url_article.split('.')[1]

    if response != 'Error':
        if extension == 'md':
            rndr = HtmlRenderer()
            md = Markdown(rndr, extensions=('fenced-code', 'math'))
            article_markdown = md(response)
            return render(
                request, 'markdown.html', {
                    'article': article,
                    'categories': categories,
                    'article_markdown': article_markdown,
                    'url_github': url_article
                })

        elif extension == 'ipynb':
            notebook = format_read(response, as_version=4)
            html_explorer = HTMLExporter()
            html_explorer.template_file = 'basic'
            (body, _) = html_explorer.from_notebook_node(notebook)

            return render(
                request, 'lire_ipynb.html', {
                    'article': article,
                    'ipynb': body,
                    'categories': categories,
                    'url_github': url_article
                })

    else:
        article_markdown = ('Error reading this article!')
        return render(
            request, 'markdown.html', {
                'article': article,
                'categories': categories,
                'article_markdown': article_markdown,
                'url_github': url_article
            })
Exemplo n.º 6
0
def preview():
    if request.method == "POST":
        from misaka import Markdown, HtmlRenderer
        choice = request.values.get('choice')
        content = request.values.get('content')
        if choice == 'Default':
            return safe_clean(content)
        else:
            html = HtmlRenderer()
            markdown = Markdown(html)
            return Markup(markdown(content))
    else:
        abort(404)
Exemplo n.º 7
0
def story(content_uri):
    """Return the text referenced by content_uri. If uri can not be
    resolved it is returned as is. Current allowed scheme is 'git'. The
    netloc 'yaj-dir' resolves to the local source tree.

    The buffer get processed by mako and rendered as markdown.
    """
    fullpath = uri.resolve_to_path(content_uri)
    buf0 = fetch.read(fullpath)
    # markdown
    rndr = HtmlRenderer()
    md = Markdown(rndr)
    return md(buf0)
Exemplo n.º 8
0
def index():
    """Present readme.md"""
    # Open readme.md file
    with open(os.path.dirname(app.root_path) + '/app/readme.md',
              'r') as markdown_file:
        print('os.path.dirname(app.root_path)', os.path.dirname(app.root_path))
        # Read the content of the file
        content = markdown_file.read()

        rndr = HtmlRenderer()
        md = Markdown(rndr)

        # Convert it to HTML
        return md(content)
Exemplo n.º 9
0
def get_text_from_markdown(markdown_text):
	renderer = HtmlRenderer()
	markdown = Markdown(renderer, extensions=('tables', 'autolink', 'strikethrough', 'quote', 'superscript', 'fenced-code'))
	html = markdown(markdown_text)
	parsed_html = fromstring(html)
	
	# remove quoted text
	[x.getparent().remove(x) for x in parsed_html.xpath('//blockquote')]
	
	# remove automatically added links 
	for link in parsed_html.xpath('//a'):
		if link.text_content() == link.get('href'):			 
			link.getparent().remove(link)
	
	text = ''.join(parsed_html.text_content()).strip()
	return text
Exemplo n.º 10
0
    def setup(self):
        pants = SmartyPants()

        self.r = {
            HTML_SKIP_HTML: HtmlRenderer(HTML_SKIP_HTML),
            HTML_SKIP_IMAGES: HtmlRenderer(HTML_SKIP_IMAGES),
            HTML_SKIP_LINKS: HtmlRenderer(HTML_SKIP_LINKS),
            HTML_SAFELINK: HtmlRenderer(HTML_SAFELINK),
            HTML_ESCAPE: HtmlRenderer(HTML_ESCAPE),
            HTML_HARD_WRAP: HtmlRenderer(HTML_HARD_WRAP)
        }
Exemplo n.º 11
0
def create():
    md = Markdown(HtmlRenderer())
    form = PostForm()
    post = Post()
    if form.validate_on_submit():
        post.title = form.title.data
        post.body = form.body.data
        post.body_html = md(post.body)
        post.outline = form.outline.data
        post.created = datetime.now()
        db.session.add(post)
        return redirect(url_for('main.admin'))
    try:
        db.session.commit()
    except ImportError:
        db.session.rollback
    return render_template('create_post.html', form=form)
Exemplo n.º 12
0
def post_content(slug):
    login = session.get("logged_in")
    post = db.session.query(Posts).filter(Posts.slug == slug).first()
    if not post:
        return abort(404)
    render = HtmlRenderer()
    md = Markdown(render)
    session['post_id'] = post.id

    user_id = session.get("user_id")
    username = session.get("username")
    post.content = Markup(md(post.content))

    return render_template("post/post-content.html",
                           login=login,
                           post=post,
                           user=username)
Exemplo n.º 13
0
def convert_to_html(filename, input_encoding='UTF-8'):
    """
    Convert a file with Markdown or reStructuredText markup to HTML.

    :param filename: The filename of the text file to convert (a string).
    :param encoding: The encoding of the text file (a string).
    :returns: A tuple of two strings:
              1. The HTML to embed in the ``<head>``.
              2. The HTML to embed in the ``<body>``.
    """
    # Determine the filename extension.
    basename, extension = os.path.splitext(filename)
    extension = extension.lower()
    # Read the input file into a Unicode string.
    with codecs.open(filename, encoding=input_encoding) as handle:
        text = handle.read()
    # Convert the input file.
    timer = Timer()
    if extension in MARKDOWN_EXTENSIONS:
        logger.debug(
            "Filename extension of input file (%s) indicates Markdown.",
            extension)
        converter = Markdown(HtmlRenderer())
        head = ''
        body = converter.render(text)
    elif extension in RESTRUCTUREDTEXT_EXTENSIONS:
        logger.debug(
            "Filename extension of input file (%s) indicates reStructuredText.",
            extension)
        parts = publish_parts(source=text,
                              writer_name='html',
                              settings_overrides=dict(doctitle_xform=False))
        head = parts['stylesheet']
        body = parts['html_body']
    else:
        msg = "Input file not supported! (filename extension %s not recognized)"
        raise ValueError(msg % extension)
    logger.debug("Converted %s input text to %s HTML in %s.",
                 format_size(len(text)), format_size(len(head) + len(body)),
                 timer)
    return head, body
Exemplo n.º 14
0
{payload_hash}"""
_AUTH_ALGORITHM = 'AWS4-HMAC-SHA256'
_CREDENTIAL_SCOPE = '{date_stamp}/{region}/{service}/{auth_request}'
_STRING_TO_SIGN = """\
{algorithm}
{x_amz_date}
{credential_scope}
{canonical_request_hash}"""
_AUTH_HEADER = (
    '{algorithm} Credential={access_key}/{credential_scope},SignedHeaders={signed_headers},Signature={signature}'
)

flags = ('hard-wrap', )
extensions = ('no-intra-emphasis', )
safe_markdown = Markdown(
    HtmlRenderer(flags=flags),  # maybe should use SaferHtmlRenderer
    extensions=extensions)
DEBUG_PRINT_REGEX = re.compile(r'{{ ?__debug_context__ ?}}')


class UserEmail(NamedTuple):
    id: int
    ctx: Dict[str, Any] = {}
    ticket_id: int = None


class BaseEmailActor(BaseActor):
    def __init__(self, *, http_client=None, **kwargs):
        super().__init__(**kwargs)
        self.client = http_client or ClientSession(
            timeout=ClientTimeout(total=10), loop=self.loop)
Exemplo n.º 15
0
#!/usr/bin/env python3

import os
import sys

from datetime import datetime
from misaka import HtmlRenderer, Markdown
from multiprocessing import Pool
from utils import ABS, has_extension, MarkdownHeader, NULL_MARKDOWN_HEADER, parse_header, parse_post, READ, WRITE

# https://misaka.readthedocs.io/en/latest/ or https://docs.rs/hoedown/6.0.0/hoedown/
POST_RENDERER_FLAGS = []
POST_RENDERER = HtmlRenderer(POST_RENDERER_FLAGS)

POST_PARSER_EXTENSIONS = [
    'autolink', 'fenced-code', 'footnotes', 'highlight', 'no-intra-emphasis',
    'quote', 'space-headers', 'strikethrough', 'superscript', 'tables'
]
POST_PARSER = Markdown(POST_RENDERER, POST_PARSER_EXTENSIONS)

PLACEHOLDERS = {
    'TITLE': 'TITLE',
    'CONTENT': 'PLACEHOLDER',
    'LIST_ITEM': 'LIST_ITEM',
    'POST_ID': 'SLUG',
    'POST_TITLE': 'TITLE',
    'POST_DYNAMIC_LINK': 'DYNAMIC_LINK',
    'POST_STATIC_LINK': 'STATIC_LINK',
    'POST_CONTENT': 'PLACEHOLDER',
    'POST_DATE': 'PUBLISH_DATE',
    'POST_EDIT_DATE': 'EDIT_DATE',
Exemplo n.º 16
0
from elements import link, article, social, Post
from flask import Flask, render_template, jsonify, send_from_directory, abort
import random
from misaka import Markdown, HtmlRenderer
import os

renderer = HtmlRenderer()
md = Markdown(renderer, extensions=("fenced-code", ))
blogpath = "blog"

app = Flask(__name__)


@app.errorhandler(404)
def resource_not_found(e):
    return jsonify(error=str(e)), 404


socials_left = [
    social(
        "https://twitter.com/malpractitioner",
        "twitter",
        "Me on Twitter",
        "I'm probably the most active here",
    ),
    social(
        "https://instagram.com/malpractitioner_",
        "instagram",
        "Me on Instagram",
        "Primarily for food, music and keyboard stories",
    ),
Exemplo n.º 17
0
def main():
    rndr = HtmlRenderer()
    md = Markdown(rndr)
    print md('some text')

    print m.html('some other text')
Exemplo n.º 18
0
def markdown(text, clean=True):
    renderer = HtmlRenderer()
    md = Markdown(renderer, extensions=('fenced-code', ))
    if clean:
        return Markup(safe_clean(md(text)))
    return Markup(md(text))
 def __init__(self, markdownDoc):
     self.document = "markdown/" + markdownDoc
     self.tocRen = HtmlTocRenderer(3)
     self.docRen = HtmlRenderer(0, 3)
Exemplo n.º 20
0
# coding: utf-8

from warnings import warn

from misaka import Markdown, HtmlRenderer
from BeautifulSoup import BeautifulSoup

rndr = HtmlRenderer()
md = Markdown(rndr)

VALID_TAGS = [
    'div',
    'h2',
    'h3',
    'span',
    'a',
    'p',
    'br',
    'img',
    'center',
    'b',
    'strong',
    'em',
    'i',
    'ol',
    'ul',
    'li',
    'dl',
    'dt',
    'dd',
    'table',
Exemplo n.º 21
0
def safe_markdown(text):
    from flask import Markup
    from misaka import Markdown, HtmlRenderer
    html = HtmlRenderer()
    markdown = Markdown(html)
    return Markup(markdown(text))
Exemplo n.º 22
0
# encoding: utf-8

from __future__ import unicode_literals

from misaka import Markdown, HtmlRenderer  # , SmartyPants
from misaka import HTML_ESCAPE, HTML_HARD_WRAP
from misaka import EXT_FENCED_CODE, EXT_NO_INTRA_EMPHASIS, EXT_AUTOLINK, EXT_SPACE_HEADERS, EXT_STRIKETHROUGH, EXT_SUPERSCRIPT

from .string import String
from ....schema.compat import unicode, py3


md = Markdown(
    HtmlRenderer(flags=HTML_ESCAPE | HTML_HARD_WRAP),
    extensions = EXT_FENCED_CODE | \
    EXT_NO_INTRA_EMPHASIS | \
    EXT_AUTOLINK | \
    EXT_SPACE_HEADERS | \
    EXT_STRIKETHROUGH | \
    EXT_SUPERSCRIPT
)


class MarkdownString(unicode):
    def __html__(self):
        return md(self)


class Markdown(String):
    def to_foreign(self, obj, name, value):  # pylint:disable=unused-argument
        if hasattr(value, '__markdown__'):
Exemplo n.º 23
0
from __future__ import unicode_literals

from django.db import models
from django.template import loader, Template
from misaka import Markdown, HtmlRenderer

markdown = Markdown(HtmlRenderer(), extensions=('fenced-code', ))

# Create your models here.


class Content(models.Model):
    content_name = models.CharField('Content Name', max_length=256)
    is_draft = models.BooleanField('Draft')
    last_updated = models.DateTimeField('Last Updated', auto_now=True)

    content_value = ''
    template = loader.get_template('basilica/text.html')

    def get_content(self):
        return self.content_value

    def render(self):
        return self.template.render({'content': self.get_content()})

    class Meta:
        abstract = True


class Text(Content):
    content_value = models.CharField('Content Value', max_length=256)
Exemplo n.º 24
0
import logging
import re
import secrets
from base64 import urlsafe_b64encode
from typing import Dict, NamedTuple

import chevron
import sass
from chevron import ChevronError
from misaka import HtmlRenderer, Markdown

markdown = Markdown(HtmlRenderer(flags=['hard-wrap']),
                    extensions=['no-intra-emphasis'])
logger = logging.getLogger('morpheus.render')


class MessageDef(NamedTuple):
    first_name: str
    last_name: str
    main_template: str
    mustache_partials: Dict[str, dict]
    macros: Dict[str, dict]
    subject_template: str
    context: dict
    headers: dict


class EmailInfo(NamedTuple):
    full_name: str
    subject: str
    html_body: str
Exemplo n.º 25
0
def markdown(text):
    renderer = HtmlRenderer()
    md = Markdown(renderer, extensions=('fenced-code', ))
    return Markup(md(text))
Exemplo n.º 26
0
 def md1(value):
     rndr = HtmlRenderer()
     md = Markdown(rndr)
     return md.render(value)
Exemplo n.º 27
0
 def __new__(cls, flags=0, **kwargs):
     return HtmlRenderer.__new__(cls, flags)
Exemplo n.º 28
0
 def render_with(self, text, flags=0, extensions=0):
     return Markdown(HtmlRenderer(), extensions).render(text)
Exemplo n.º 29
0
{payload_hash}"""
_AUTH_ALGORITHM = 'AWS4-HMAC-SHA256'
_CREDENTIAL_SCOPE = '{date_stamp}/{region}/{service}/{auth_request}'
_STRING_TO_SIGN = """\
{algorithm}
{x_amz_date}
{credential_scope}
{canonical_request_hash}"""
_AUTH_HEADER = (
    '{algorithm} Credential={access_key}/{credential_scope},SignedHeaders={signed_headers},Signature={signature}'
)

flags = ('hard-wrap', )
extensions = ('no-intra-emphasis', )
safe_markdown = Markdown(
    HtmlRenderer(flags=flags),
    extensions=extensions)  # maybe should use SaferHtmlRenderer
DEBUG_PRINT_REGEX = re.compile(r'{{ ?__debug_context__ ?}}')


class UserEmail(NamedTuple):
    id: int
    ctx: Dict[str, Any] = {}
    ticket_id: int = None


class BaseEmailActor(BaseActor):
    def __init__(self, *, http_client=None, **kwargs):
        super().__init__(**kwargs)
        self.client = http_client or ClientSession(
            timeout=ClientTimeout(total=10), loop=self.loop)
Exemplo n.º 30
0
 def setup(self):
     self.r = Markdown(HtmlRenderer()).render
Exemplo n.º 31
0
 def safe_markdown(text):
     html = HtmlRenderer()
     markdown = Markdown(html)
     return Markup(markdown(text))
Exemplo n.º 32
0
# _bergi's custom tags

import misaka
from misaka import HtmlRenderer

import datetime

from django import template
from django.utils.dateformat import format

register = template.Library()

renderer = HtmlRenderer(misaka.HTML_ESCAPE)
md = misaka.Markdown(renderer,
                     extensions=misaka.EXT_FENCED_CODE
                     | misaka.EXT_NO_INTRA_EMPHASIS | misaka.EXT_TABLES
                     | misaka.EXT_AUTOLINK | misaka.EXT_SPACE_HEADERS
                     | misaka.EXT_STRIKETHROUGH | misaka.EXT_SUPERSCRIPT)


@register.filter
def markdown(text):
    return md(text)


# only show past years
@register.filter
def datefmt(date):
    now = datetime.datetime.now()
    if date.year == now.year:
        return format(date, "j F")
Exemplo n.º 33
0
 def __init__(self, flags):
     HtmlRenderer.__init__(self, flags)
     self.doc_info = {}