def save_model(self, request, obj, form, change): obj.owner = request.user obj.html = markdown.markdown(obj.source, output_format="html5", extensions=[ EscapeHtml(), codehilite.CodeHiliteExtension(), fenced_code.FencedCodeExtension(), ]) super().save_model(request, obj, form, change)
def _md(x): o = markdown.markdown( x, extensions=[ tables.TableExtension(), fenced_code.FencedCodeExtension(), sane_lists.SaneListExtension(), markdown_math.MathExtension(), ], ) return o
def build_html_output(content, node): return markdown.markdown( content, extensions=[ wikilinks.WikiLinkExtension( configs=[('base_url', ''), ( 'end_url', ''), ('build_url', functools.partial(build_wiki_url, node))]), fenced_code.FencedCodeExtension(), codehilite.CodeHiliteExtension([('css_class', 'highlight')]) ])
def render_content(content, node): html_output = markdown.markdown( content, extensions=[ wikilinks.WikiLinkExtension( configs=[('base_url', ''), ( 'end_url', ''), ('build_url', functools.partial(build_wiki_url, node))]), fenced_code.FencedCodeExtension(), codehilite.CodeHiliteExtension([('css_class', 'highlight')]) ]) # linkify gets called after santize, because we're adding rel="nofollow" # to <a> elements - but don't want to allow them for other elements. sanitized_content = sanitize(html_output, **settings.WIKI_WHITELIST) return sanitized_content
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')
class ExtendedLinkExtension(markdown.Extension): def extendMarkdown(self, md, md_globals): md.inlinePatterns['link'] = ExtendedLinkPattern( inlinepatterns.LINK_RE, md) md.parser.blockprocessors['hashheader'] = SpacedHashHeaderProcessor( md.parser) markdown_extensions = [ magiclink.MagiclinkExtension(), nl2br.Nl2BrExtension(), ExtendedLinkExtension(), sane_lists.SaneListExtension(), fenced_code.FencedCodeExtension(), CuddledListExtension(), UnimojiExtension() ] content_allowed_tags = ( # text 'p', 'em', 'strong', 'br', 'a', 'img', 'sub', 'sup', # citation
def main(md=None, filename=None, cols=None, theme=None, c_theme=None, bg=None, c_no_guess=None, display_links=None, from_txt=None, do_html=None, no_colors=None, **kw): """ md is markdown string. alternatively we use filename and read """ args = locals() if not md: if not filename: print 'Using sample markdown:' make_sample() md = args['md'] = md_sample print md print print 'Styling Result' else: with open(filename) as f: md = f.read() global term_columns # style rolers requested? if c_theme == 'all' or theme == 'all': args.pop('kw') themes = read_themes() for k, v in themes.items(): if not filename: yl = 'You like *%s*, *%s*?' % (k, v['name']) args['md'] = md_sample.replace(you_like, yl) print col('%s%s%s' % ('\n\n', '=' * term_columns, '\n'), L) # should really create an iterator here: if theme == 'all': args['theme'] = k else: args['c_theme'] = k print main(**args) return '' if cols: term_columns = int(cols) global show_links show_links = display_links if bg and bg == 'light': # not in use rite now: global background, color background = BGL color = T set_theme(theme) global guess_lexer guess_lexer = not c_no_guess if not c_theme: c_theme = theme or 'default' if c_theme == 'None': c_theme = None if c_theme: set_theme(c_theme, for_code=1) if c_theme or c_guess: # info: if not have_pygments: print col('No pygments, can not analyze code for hilite', R) # Create an instance of the Markdown class with the new extension MD = markdown.Markdown(extensions=[ AnsiPrintExtension(), TableExtension(), fenced_code.FencedCodeExtension() ]) # html? the_html = MD.convert(md) if do_html: return the_html # who wants html, here is our result: try: ansi = MD.ansi except: if html: # can this happen? At least show: print "we have markdown result but no ansi." print html else: ansi = 'n.a. (no parsing result)' # The RAW html within source, incl. fenced code blocks: # phs are numbered like this in the md, we replace back: PH = markdown.util.HTML_PLACEHOLDER stash = MD.htmlStash nr = -1 tags = Tags() for ph in stash.rawHtmlBlocks: nr += 1 raw = html_parser.unescape(ph[0]) pre = '<pre><code' if raw.startswith(pre): pre, raw = raw.split(pre, 1) raw = raw.split('>', 1)[1].rsplit('</code>', 1)[0] if 'class="' in pre: # language: lang = pre.split('class="', 1)[1].split('"')[0] else: lang = '' raw = tags.code(raw.strip(), from_fenced_block=1, lang=lang) ansi = ansi.replace(PH % nr, raw) # don't want these: gone through the extension now: # ansi = ansi.replace('```', '') # sub part display (the -f feature) if from_txt: if not from_txt.split(':', 1)[0] in ansi: # display from top then: from_txt = ansi.strip()[1] from_txt, mon_lines = (from_txt + ':%s' % (term_rows - 6)).split(':')[:2] mon_lines = int(mon_lines) pre, post = ansi.split(from_txt, 1) post = '\n'.join(post.split('\n')[:mon_lines]) ansi = '\n(...)%s%s%s' % ('\n'.join(pre.rsplit( '\n', 2)[-2:]), from_txt, post) ansi = set_hr_widths(ansi) + '\n' if no_colors: return clean_ansi(ansi) return ansi + '\n'
def main(md=None, filename=None, cols=None, theme=None, c_theme=None, bg=None, c_no_guess=None, display_links=None, link_style=None, from_txt=None, do_html=None, code_hilite=None, c_def_lexer=None, theme_info=None, no_colors=None, tab_length=4, no_change_defenc=False, header_nrs=False, **kw): """ md is markdown string. alternatively we use filename and read """ # fmt: on # if I don't do this here, then I'll get probs when being # used as a lib: # https://github.com/axiros/terminal_markdown_viewer/issues/39 # If you hate it then switch it off but don't blame me on unicode errs. True if no_change_defenc else fix_py2_default_encoding() parse_header_nrs(header_nrs) tab_length = tab_length or 4 global def_lexer if c_def_lexer: def_lexer = c_def_lexer py_config_file = os.path.expanduser("~/.mdv.py") if os.path.exists(py_config_file): exec_globals = {} exec(io.open(py_config_file, encoding="utf-8").read(), exec_globals) globals().update(exec_globals) args = locals() if not md: if not filename: print("Using sample markdown:") make_sample() md = args["md"] = md_sample print(md) print print("Styling Result") else: if filename == "-": md = sys.stdin.read() else: with open(filename) as f: md = f.read() # style rolers requested? global term_columns if cols: term_columns = int(cols) if c_theme == "all" or theme == "all": if c_theme == "all": os.environ["AXC_CODE_THEME"] = os.environ["MDV_CODE_THEME"] = "" if theme == "all": os.environ["AXC_THEME"] = os.environ["MDV_THEME"] = "" args.pop("kw") themes = read_themes() for k, v in list(themes.items()): if not filename: yl = "You like *%s*, *%s*?" % (k, v["name"]) args["md"] = md_sample.replace(you_like, yl) print(col("%s%s%s" % ("\n\n", "=" * term_columns, "\n"), L)) # should really create an iterator here: if theme == "all": args["theme"] = k else: args["c_theme"] = k print(main(**args)) return "" global show_links if display_links: show_links = "i" if link_style: # rules show_links = link_style if bg and bg == "light": # not in use rite now: global background, color background = BGL color = T set_theme(theme, theme_info=theme_info) global guess_lexer guess_lexer = not c_no_guess if not c_theme: c_theme = theme or "default" if c_theme == "None": c_theme = None if c_theme: set_theme(c_theme, for_code=1, theme_info=theme_info) if c_theme: # info: if not have_pygments: errout(col("No pygments, can not analyze code for hilite", R)) # Create an instance of the Markdown class with the new extension MD = markdown.Markdown( tab_length=int(tab_length), extensions=[ AnsiPrintExtension(), TableExtension(), fenced_code.FencedCodeExtension(), ], ) if code_hilite: md = do_code_hilite(md, code_hilite) the_html = MD.convert(md) reset_cur_header_state() # print the_html # html? if do_html: return the_html # who wants html, here is our result: ansi = MD.ansi # The RAW html within source, incl. fenced code blocks: # phs are numbered like this in the md, we replace back: PH = markdown.util.HTML_PLACEHOLDER stash = MD.htmlStash nr = -1 tags = Tags() for ph in stash.rawHtmlBlocks: nr += 1 raw = unescape(ph) if raw[:3].lower() == "<br": raw = "\n" pre = "<pre><code" if raw.startswith(pre): _, raw = raw.split(pre, 1) if 'class="' in raw: # language: lang = raw.split('class="', 1)[1].split('"')[0] else: lang = "" raw = raw.split(">", 1)[1].rsplit("</code>", 1)[0] raw = tags.code(raw.strip(), from_fenced_block=1, lang=lang) ansi = ansi.replace(PH % nr, raw) # don't want these: gone through the extension now: # ansi = ansi.replace('```', '') # sub part display (the -f feature) if from_txt: if not from_txt.split(":", 1)[0] in ansi: # display from top then: from_txt = ansi.strip()[1] from_txt, mon_lines = (from_txt + ":%s" % (term_rows - 6)).split(":")[:2] mon_lines = int(mon_lines) pre, post = ansi.split(from_txt, 1) post = "\n".join(post.split("\n")[:mon_lines]) ansi = "\n(...)%s%s%s" % ( "\n".join(pre.rsplit("\n", 2)[-2:]), from_txt, post, ) ansi = set_hr_widths(ansi) + "\n" if no_colors: return clean_ansi(ansi) return ansi + "\n"
def pre_save_note(sender, instance, *args, **kwargs): instance.slug = slugify(instance.title) instance.content_html = markdown( instance.content_markdown, extensions=[fenced_code.FencedCodeExtension()], safe_mode='escape')
def main(md=None, filename=None, cols=None, theme=None, c_theme=None, bg=None, c_no_guess=None, display_links=None, link_style=None, from_txt=None, do_html=None, code_hilite=None, c_def_lexer=None, theme_info=None, no_colors=None, tab_length=4, no_change_defenc=False, **kw): """ md is markdown string. alternatively we use filename and read """ if sys.version_info[0] == 2 and not no_change_defenc: # if I don't do this here, then I'll get probs when being # used as a lib: # https://github.com/axiros/terminal_markdown_viewer/issues/39 # If you hate it then switch it off but don't blame me on unicode errs. fix_py2_default_encoding() tab_length = tab_length or 4 global def_lexer if c_def_lexer: def_lexer = c_def_lexer py_config_file = os.path.expanduser("~/.mdv.py") if os.path.exists(py_config_file): exec_globals = {} exec(io.open(py_config_file, encoding='utf-8').read(), exec_globals) globals().update(exec_globals) args = locals() if not md: if not filename: print('Using sample markdown:') make_sample() md = args['md'] = md_sample print(md) print print('Styling Result') else: if filename == '-': md = sys.stdin.read() else: with open(filename) as f: md = f.read() # style rolers requested? global term_columns if cols: term_columns = int(cols) if c_theme == 'all' or theme == 'all': if c_theme == 'all': os.environ['AXC_CODE_THEME'] = os.environ['MDV_CODE_THEME'] = '' if theme == 'all': os.environ['AXC_THEME'] = os.environ['MDV_THEME'] = '' args.pop('kw') themes = read_themes() for k, v in list(themes.items()): if not filename: yl = 'You like *%s*, *%s*?' % (k, v['name']) args['md'] = md_sample.replace(you_like, yl) print(col('%s%s%s' % ('\n\n', '=' * term_columns, '\n'), L)) # should really create an iterator here: if theme == 'all': args['theme'] = k else: args['c_theme'] = k import pdb pdb.set_trace() print(main(**args)) return '' global show_links if display_links: show_links = 'i' if link_style: # rules show_links = link_style if bg and bg == 'light': # not in use rite now: global background, color background = BGL color = T set_theme(theme, theme_info=theme_info) global guess_lexer guess_lexer = not c_no_guess if not c_theme: c_theme = theme or 'default' if c_theme == 'None': c_theme = None if c_theme: set_theme(c_theme, for_code=1, theme_info=theme_info) if c_theme: # info: if not have_pygments: print(col('No pygments, can not analyze code for hilite', R)) # Create an instance of the Markdown class with the new extension MD = markdown.Markdown(tab_length=int(tab_length), extensions=[ AnsiPrintExtension(), TableExtension(), fenced_code.FencedCodeExtension() ]) if code_hilite: md = do_code_hilite(md, code_hilite) the_html = MD.convert(md) #print the_html # html? if do_html: return the_html # who wants html, here is our result: try: ansi = MD.ansi except: if the_html: # can this happen? At least show: print("we have markdown result but no ansi.") print(the_html) else: ansi = 'n.a. (no parsing result)' # The RAW html within source, incl. fenced code blocks: # phs are numbered like this in the md, we replace back: PH = markdown.util.HTML_PLACEHOLDER stash = MD.htmlStash nr = -1 tags = Tags() for ph in stash.rawHtmlBlocks: nr += 1 raw = html_parser.unescape(ph[0]) if raw[:3].lower() == '<br': raw = '\n' pre = '<pre><code' if raw.startswith(pre): _, raw = raw.split(pre, 1) if 'class="' in raw: # language: lang = raw.split('class="', 1)[1].split('"')[0] else: lang = '' raw = raw.split('>', 1)[1].rsplit('</code>', 1)[0] raw = tags.code(raw.strip(), from_fenced_block=1, lang=lang) ansi = ansi.replace(PH % nr, raw) # don't want these: gone through the extension now: # ansi = ansi.replace('```', '') # sub part display (the -f feature) if from_txt: if not from_txt.split(':', 1)[0] in ansi: # display from top then: from_txt = ansi.strip()[1] from_txt, mon_lines = (from_txt + ':%s' % (term_rows - 6)).split(':')[:2] mon_lines = int(mon_lines) pre, post = ansi.split(from_txt, 1) post = '\n'.join(post.split('\n')[:mon_lines]) ansi = '\n(...)%s%s%s' % ('\n'.join(pre.rsplit( '\n', 2)[-2:]), from_txt, post) ansi = set_hr_widths(ansi) + '\n' if no_colors: return clean_ansi(ansi) return ansi + '\n'