예제 #1
0
    def markdown_to_html(self, text):
        # 扩展用法
        key = ["+", ">"]  # 添加换行
        for k in key:
            text = text.replace("\n" + k, "\n\n" + k)

        html = markdown.markdown(
            text,
            output_format='html5',
            extensions=[
                MathExtension(enable_dollar_delimiter=True),
                'markdown.extensions.toc',
                WikiLinkExtension(base_url='https://en.wikipedia.org/wiki/',
                                  end_url='#Hyperlinks_in_wikis'),
                'markdown.extensions.sane_lists',
                'markdown.extensions.codehilite', 'markdown.extensions.abbr',
                'markdown.extensions.attr_list',
                'markdown.extensions.def_list',
                'markdown.extensions.fenced_code',
                'markdown.extensions.footnotes', 'markdown.extensions.meta',
                'markdown.extensions.nl2br', 'markdown.extensions.tables'
            ])
        html = html.replace(
            "<table>", "<table border='1' cellpadding='2' cellspacing='0'>")
        html_head_file = open("html_head.txt", "r", encoding='utf-8')
        html_head = html_head_file.read()
        html_head_file.close()
        html_tail = "\n</body>\n</html>"
        html = html_head + html + html_tail
        # print(html)
        # html_file = open("file.html", "w", encoding='utf-8')
        # html_file.write(html)
        # html_file.close()

        return html
예제 #2
0
def parse(md_text) -> str:
    lines = md_text.splitlines()
    ret = []
    md_wiki_ext = WikiLinkExtension(base_url='/cookbook/', end_url='')
    for (buf, status) in rest_graph(lines):
        if status == NORMAL:
            plain_text = '\n'.join(buf)
            html_text = markdown.markdown(
                plain_text,
                extensions=[
                    'markdown.extensions.fenced_code',
                    'markdown.extensions.nl2br',
                    'markdown.extensions.sane_lists',
                    md_wiki_ext,
                    'markdown.extensions.toc',
                ])
        elif status == PANEL:
            html_text = panel(
                title=buf[0].split('`')[1],
                items=[(lambda name: PanelItem(
                    text=name, href=f'/cookbook/{"-".join(name.split())}'))(
                        name=line.split('[[')[-1].split(']]')[0])
                       for line in buf[1:]],
            ).dumps()
        else:
            raise NotImplementedError

        ret.append(html_text)

    return '\n'.join(ret)
예제 #3
0
def markdown2html(value):
    return markdown.markdown(value,
                             extensions=[
                                 'gfm',
                                 WikiLinkExtension(base_url='../'),
                             ],
                             output_format='html5')
예제 #4
0
파일: posts.py 프로젝트: kvfi/tir
    def parse(self):
        try:
            with open(self.path, 'r') as f:
                self.raw = f.read()
            if not self.raw:
                return
            md = markdown.Markdown(extensions=[
                'markdown.extensions.meta', 'markdown.extensions.toc',
                'markdown.extensions.footnotes',
                'markdown.extensions.def_list', 'markdown.extensions.tables',
                WikiLinkExtension(base_url='https://en.wikipedia.org/wiki/',
                                  end_url=''),
                BoxExtension()
            ])

            self.content = md.convert(self.raw)
            if hasattr(md,
                       'Meta') and md.Meta and self.file_base_name != 'index':
                meta = md.Meta
                meta = remove_list_meta(meta)
                if 'online' in meta and meta['online'] == 'false':
                    pass
                if hasattr(md, 'toc'):
                    meta['contents'] = md.toc
                self.meta = meta
        except FileNotFoundError as fnf:
            raise fnf
예제 #5
0
 def setup_markdown(self):
     return markdown.Markdown(extensions=[
         WikiLinkExtension(base_url='',
                           end_url='.wiki.' + self.language + '.html',
                           build_url=self.build_url),
         FigureFromTitleExtension(), 'meta', 'admonition', 'tables',
         'attr_list'
     ])
예제 #6
0
파일: fit.py 프로젝트: kodokse/fit
 def _encode_wiki(self, txt):
     # for now...
     return "{}".format(
         markdown.markdown(
             txt,
             extensions=[
                 WikiLinkExtension(base_url='http://localhost/wiki/')
             ]))
예제 #7
0
 def testLinkText(self):
     """Test [[link-text|linked-resource]]"""
     from markdown_gollum.wikilinks import WikiLinkExtension
     md = markdown.Markdown(extensions=[
         WikiLinkExtension(base_url='', end_url='', html_class='')
     ])
     text = "[[link-text|linked-resource]]"
     html = '<p><a href="linked-resource">link-text</a></p>'
     self.assertEqual(md.convert(text), html)
예제 #8
0
def markdown2html(markdown_text):
    html = markdown.markdown(markdown_text,
                             extensions=[WikiLinkExtension(base_url='/wiki/', end_url=''),
                                         'markdown.extensions.extra',
                                         'markdown.extensions.toc',
                                         'markdown.extensions.codehilite',
                                         'markdown.extensions.meta',
                                         ])
    return tornado.escape.xhtml_escape(html)
예제 #9
0
파일: service.py 프로젝트: anler/taiga-back
def _make_extensions_list(wikilinks_config=None):
    return [AutolinkExtension(),
            AutomailExtension(),
            SemiSaneListExtension(),
            SpacedLinkExtension(),
            StrikethroughExtension(),
            WikiLinkExtension(wikilinks_config),
            "extra",
            "codehilite"]
예제 #10
0
파일: source.py 프로젝트: Svetlana-T/cms7
 def render(self, gs):
     md = Markdown(extensions=[
         MetaExtension(),
         TableExtension(),
         WikiLinkExtension(),
         CMS7Extension(gs, baselevel=2),
         TocExtension()
     ],
                   output_format='html5')
     return Markup(md.convert(self.text))
예제 #11
0
 def render(self, gs, *, baselevel=2, hyphenate=False, paragraphs=None):
     md = Markdown(extensions=[
             MetaExtension(),
             TableExtension(),
             WikiLinkExtension(),
             CMS7Extension(gs, path=self.source, baselevel=baselevel, hyphenate=hyphenate, paragraphs=paragraphs),
             TocExtension(anchorlink=True)
         ],
         output_format='html5')
     return Markup(md.convert(self.text))
예제 #12
0
파일: markdown.py 프로젝트: getskua/skua
 def preprocess(self, input_file):
     file = frontmatter.load(input_file)
     content = markdown.markdown(file.content,
                                 extensions=[
                                     WikiLinkExtension(
                                         base_url=self.site_url,
                                         end_url="." + self.extension)
                                 ])
     file = dict(file)
     file['content'] = content
     return file
예제 #13
0
 def testMoreUnicode(self):
     from markdown_gollum.wikilinks import WikiLinkExtension
     md = markdown.Markdown(extensions=[
         WikiLinkExtension(base_url='', end_url='', html_class='')
     ])
     text = "[[Вопрос к жителям города или отдыхающим «в теме». Ребенку скоро 14 лет." + \
         "|facebook-1945869095704578]]"
     html = '<p><a href="facebook-1945869095704578">' + \
         'Вопрос к жителям города или отдыхающим «в теме». Ребенку скоро 14 лет.' + \
         '</a></p>'
     self.assertEqual(md.convert(text), html)
예제 #14
0
    def testURLCallback(self):
        """ Test used of a custom URL builder. """

        from markdown.extensions.wikilinks import WikiLinkExtension

        def my_url_builder(label, base, end):
            return '/bar/'

        md = markdown.Markdown(
            extensions=[WikiLinkExtension(build_url=my_url_builder)])
        self.assertEqual(md.convert('[[foo]]'),
                         '<p><a class="wikilink" href="/bar/">foo</a></p>')
예제 #15
0
파일: xitypes.py 프로젝트: Nomicoin/viki
    def generateHtml(self):
        try:
            extensions = [
                TableExtension(),
                WikiLinkExtension(html_class='internal', build_url=urlBuilder)
            ]
            source = self.blob.data.decode('utf-8')
            html = markdown.markdown(source, extensions=extensions)

            self.metadata['as'] = {'html': html}
        except Exception, e:
            print "markdown processing failed on", self.name, str(e)
예제 #16
0
파일: tools.py 프로젝트: 662d7/TorCMS
def markdown2html(markdown_text):
    html = markdown.markdown(markdown_text,
                             extensions=[
                                 WikiLinkExtension(base_url='/wiki/',
                                                   end_url=''),
                                 'markdown.extensions.extra',
                                 'markdown.extensions.toc',
                                 'markdown.extensions.codehilite',
                                 'markdown.extensions.meta',
                             ])
    han_biaodians = ['。', ',', ';', '、', '!', '?']
    for han_biaodian in han_biaodians:
        html = html.replace(han_biaodian + '\n', han_biaodian)
    return tornado.escape.xhtml_escape(html)
예제 #17
0
def markdown2html(markdown_text):
    '''
    Convert markdown text to HTML. with extensions.
    :param markdown_text:   The markdown text.
    :return:  The HTML text.
    '''
    html = markdown.markdown(markdown_text,
                             extensions=[
                                 WikiLinkExtension(base_url='/wiki/',
                                                   end_url=''),
                                 'markdown.extensions.extra',
                                 'markdown.extensions.toc',
                                 'markdown.extensions.codehilite',
                                 'markdown.extensions.meta'
                             ])
    han_biaodians = ['。', ',', ';', '、', '!', '?']
    for han_biaodian in han_biaodians:
        html = html.replace(han_biaodian + '\n', han_biaodian)
    return tornado.escape.xhtml_escape(html)
예제 #18
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY='dev', )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # Add blueprints here.
    from . import agora
    app.register_blueprint(agora.bp)
    app.add_url_rule('/', endpoint='index')

    # Jinja2 extensions.
    Markdown(app,
             tab_length=2,
             extensions=[
                 "sane_lists",
                 WikiLinkExtension(build_url=wikilink_to_url)
             ])

    @app.template_filter('linkify')
    def linkify(s):
        return bleach.linkify(s)

    return app
예제 #19
0
파일: md2web.py 프로젝트: mijara/md2web
    def convert(self, file_to_convert):
        # read the file and add the content table.
        source_file = codecs.open(file_to_convert, mode="r", encoding="utf-8")
        text = "[TOC]\n" + source_file.read()
        source_file.close()

        # convert it to html with the extensions given, this could raise an exception, but this
        # method is supposed to live inside a try / except.
        html = markdown.markdown(text, encoding="utf-8", extensions=[WikiLinkExtension(end_url='.html', base_url="", build_url=format_url), 'markdown.extensions.tables', 'markdown.extensions.toc', 'markdown.extensions.nl2br'])

        # try to find a "template.html" in the working directory, if we can't find one, use the one
        # packed with this program.
        if os.path.isfile("template.html"):
            # template defined by the user.
            template_path = "template.html"
        else:
            # default template.
            template_path = self.default_template_path

        # read the template file.
        template_file = codecs.open(template_path, mode="r", encoding="utf-8")
        template = template_file.read()
        template_file.close()

        # this is the name of the temp file.
        file_target_name = file_to_convert + ".html"

        # get the base name to work as the title of the temp file, write the html in it with the
        # title and content and finish.
        base_name = os.path.basename(os.path.splitext(file_to_convert)[0])
        write_file = codecs.open(file_target_name, "w", encoding="utf-8",
                errors="xmlcharrefreplace")
        write_file.write(template % (base_name, html))
        write_file.close()

        return file_target_name
예제 #20
0
REDIS = redis.StrictRedis.from_url(REDIS_URL)

# how many seconds to set the expires and max_age headers
HTTP_CACHE_TIMEOUT = config('HTTP_CACHE_TIMEOUT', 60 * 60, cast=int)

FLATPAGES_ABOUT_ROOT = '../docs/about'
FLATPAGES_ABOUT_EXTENSION = FLATPAGES_NEWS_EXTENSION = ['.md']
FLATPAGES_NEWS_MARKDOWN_EXTENSIONS = [
    'codehilite',
    'fenced_code',
    'footnotes',
    'admonition',
    'tables',
    'abbr',
    'smarty',
    WikiLinkExtension(base_url='/about/', end_url='', html_class=''),
]
FLATPAGES_ABOUT_MARKDOWN_EXTENSIONS = FLATPAGES_NEWS_MARKDOWN_EXTENSIONS + [
    TocExtension(permalink=True),
]

FLATPAGES_ABOUT_HTML_RENDERER = FLATPAGES_NEWS_HTML_RENDERER = \
    smart_pygmented_markdown

FLATPAGES_NEWS_ROOT = '../docs/news'

# Set these values in the .env file or env vars
GITHUB_CLIENT_ID = config('GITHUB_CLIENT_ID', '')
GITHUB_CLIENT_SECRET = config('GITHUB_CLIENT_SECRET', '')
GITHUB_ORG_ID = config('GITHUB_ORG_ID', 'jazzband')
GITHUB_SCOPE = config('GITHUB_SCOPE', 'read:org,user:email')
예제 #21
0
파일: mark.py 프로젝트: cabalamat/meowcat2
#---------------------------------------------------------------------

markdownProcessor = markdown.Markdown(extensions=[
    'extra',
    'toc',
    'sane_lists',
    'codehilite',
])

markdownWikiProcessor = markdown.Markdown(extensions=[
    'extra',
    'toc',
    'sane_lists',
    'codehilite',
    WikiLinkExtension(base_url="", end_url=""),
])


def render(s: str, wikiExt: bool = False) -> Tuple[str, List[str]]:
    """ Render markup into HTML, also return tags
    @param wiki = True if it should be rendered with the WikiLinkExtension
    @return (h,tags) where:
       h:str = rendered html
       tags:List[str] = canonicalised hashtags
    """
    s2 = encloseHashtagAtStart(s)
    s3, tags = GetHashtags(s2).calc()
    dpr("s3=%s", s3)
    if wikiExt:
        markdownWikiProcessor.reset()
예제 #22
0
MAIL_USE_TLS = config("MAIL_USE_TLS", False, cast=bool)

# how many seconds to set the expires and max_age headers
HTTP_CACHE_TIMEOUT = config("HTTP_CACHE_TIMEOUT", 60 * 60, cast=int)

FLATPAGES_ABOUT_ROOT = "../docs/about"
FLATPAGES_ABOUT_EXTENSION = FLATPAGES_NEWS_EXTENSION = [".md"]
FLATPAGES_NEWS_MARKDOWN_EXTENSIONS = [
    "codehilite",
    "fenced_code",
    "footnotes",
    "admonition",
    "tables",
    "abbr",
    "smarty",
    WikiLinkExtension(base_url="/about/", end_url="", html_class=""),
]
FLATPAGES_ABOUT_MARKDOWN_EXTENSIONS = FLATPAGES_NEWS_MARKDOWN_EXTENSIONS + [
    TocExtension(permalink=True)
]

FLATPAGES_ABOUT_HTML_RENDERER = FLATPAGES_NEWS_HTML_RENDERER = smart_pygmented_markdown

FLATPAGES_NEWS_ROOT = "../docs/news"

# Set these values in the .env file or env vars
GITHUB_OAUTH_CLIENT_ID = config("GITHUB_CLIENT_ID", "")
GITHUB_OAUTH_CLIENT_SECRET = config("GITHUB_CLIENT_SECRET", "")
GITHUB_ORG_NAME = config("GITHUB_ORG_NAME", "jazzband")
GITHUB_SCOPE = config("GITHUB_SCOPE", "read:org,user:email")
GITHUB_MEMBERS_TEAM_SLUG = config("GITHUB_MEMBERS_TEAM_SLUG", "members")
예제 #23
0
 def __init__ (self):
     import markdown
     from markdown.extensions.wikilinks import WikiLinkExtension
     self._md = markdown.Markdown(extensions=[WikiLinkExtension(base_url='/', end_url='', html_class='localLink')])
예제 #24
0
 def as_html(self):
     return markdown.markdown(
         self.md,
         extensions=[WikiLinkExtension(base_url='/lexicon/', end_url='')])
예제 #25
0
#   License for the specific language governing permissions and limitations
#   under the License.

from flask_security import Security
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_flatpages import FlatPages
from flask_moment import Moment
from flask_wtf.csrf import CSRFProtect
from flask_migrate import Migrate

from markdown.extensions.tables import TableExtension
from markdown.extensions.footnotes import FootnoteExtension
from markdown.extensions.fenced_code import FencedCodeExtension
from markdown.extensions.wikilinks import WikiLinkExtension

db = SQLAlchemy()
security = Security()
bootstrap = Bootstrap()
mail = Mail()
pages = FlatPages()
moment = Moment()
csrf = CSRFProtect()
migrate = Migrate()

tables = TableExtension()
footnotes = FootnoteExtension()
fenced_code = FencedCodeExtension()
wikilinks = WikiLinkExtension()