我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用markdown2.markdown()。
def checklistInENMLtoSoup(soup): ''' Transforms Evernote checklist elements to github `* [ ]` task list style ''' transform_tags = ['p','div'] # soup.select cant be used with dashes: https://bugs.launchpad.net/beautifulsoup/+bug/1276211 for todo in soup.find_all('en-todo'): parent = todo.parent transform = parent.find() == todo and parent.name in transform_tags checked = todo.attrs.get('checked',None) == "true" todo.replace_with("[x] " if checked else "[ ] ") # EN checklist can appear anywhere, but if they appear at the beggining # of a block element, transform it so it ressembles github markdown syntax if transform: content = ''.join(unicode(child) for child in parent.children if isinstance(child, NavigableString) ).strip() new_tag = soup.new_tag("li") new_tag.string = content parent.replace_with(new_tag)
def parse_xml(cls, node, runtime, keys, id_generator): """ Parses the source XML in a way that preserves indenting, needed for markdown. """ block = runtime.construct_xblock_from_class(cls, keys) # Load the data for name, value in node.items(): if name in block.fields: value = (block.fields[name]).from_string(value) setattr(block, name, value) # Load content text = node.text if text: # Fix up whitespace. if text[0] == "\n": text = text[1:] text.rstrip() text = textwrap.dedent(text) if text: block.content = text return block
def generate_doc(config): docdir = os.path.join(cwd,'documentation') if not os.path.exists(docdir): docdir = os.path.join(cwd,'..','documentation') if not os.path.exists(docdir): print "Couldn't find documentation file at: %s" % docdir return None try: import markdown2 as markdown except ImportError: import markdown documentation = [] for file in os.listdir(docdir): if file in ignoreFiles or os.path.isdir(os.path.join(docdir, file)): continue md = open(os.path.join(docdir,file)).read() html = markdown.markdown(md) documentation.append({file:html}); return documentation
def send(self, event, users, instance, paths): self.client.reconnectAndReauth() for user, templates in users.items(): jid = self._get_jid(user) if not self.enabled(event, user, paths) or jid is None: continue template = self._get_template(templates) if template is None: continue params = self.prepare(template, instance) message = xmpp.protocol.Message(jid, body=params['short_description'].encode('utf-8'), subject=params['subject'].encode('utf-8'), typ='chat') html = xmpp.Node('html', {'xmlns': 'http://jabber.org/protocol/xhtml-im'}) text = u"<body xmlns='http://www.w3.org/1999/xhtml'>" + markdown2.markdown(params['short_description'], extras=["link-patterns"], link_patterns=link_registry.link_patterns( request), safe_mode=True) + u"</body>" html.addChild(node=xmpp.simplexml.XML2Node(text.encode('utf-8'))) message.addChild(node=html) self.client.send(message) self.client.disconnected()
def get_blog(id, request): blog = yield from Blog.find(id) # ??id??????????? # ????????blog?????????????????????? comments = yield from Comment.findAll('blog_id=?', [id], orderBy='created_at desc') # ?????????html?? for c in comments: c.html_content = text2html(c.content) # blog??markdown????????html?? blog.html_content = markdown2.markdown(blog.content) return { '__template__': 'blog.html', 'blog': blog, '__user__':request.__user__, 'comments': comments } # day10??? # ???????
def parse_markdown(): text = request.args.get('text') if text is None: abort(404) highlight = request.args.get('word') if highlight is not None: text = text.replace(highlight, '**' + highlight + '**') # Anything that isn't a square closing bracket name_regex = "[^]]+" # http:// or https:// followed by anything but a closing paren url_regex = "http[s]?://[^)]+" markup_regex = '\[({0})]\(\s*({1})\s*\)'.format(name_regex, url_regex) for match in re.findall(markup_regex, text): print(match) print(match[0]) print(match[1]) text = text.replace("[" + match[0] + "](" + match[1] + ")", match[0]) processed = markdown2.markdown(text) return json.dumps({"result": processed})
def index(request, *, page='1'): user = request.__user__ cats = await Category.findAll(orderBy='created_at desc') page_index = Page.page2int(page) num = await Blog.findNumber('*') - 1 # ??__about__?? p = Page(num, page_index, item_page=configs.blog_item_page, page_show=configs.page_show) p.pagelist() if num == 0: blogs = [] else: blogs = await Blog.findAll(where='title<>?', args=['__about__'], orderBy='created_at desc', limit=(p.offset, p.limit)) for blog in blogs: blog.html_summary = markdown(blog.summary, extras=['code-friendly', 'fenced-code-blocks']) return { '__template__': 'index.html', 'web_meta': configs.web_meta, 'user': user, 'cats': cats, 'page': p, 'blogs': blogs, 'disqus': configs.use_disqus }
def get_blog(id, request): user = request.__user__ cats = await Category.findAll(orderBy='created_at desc') blog = await Blog.find(id) blog.view_count = blog.view_count + 1 await blog.update() comments = await Comment.findAll(where='blog_id=?', args=[id], orderBy='created_at desc') for c in comments: c.html_content = markdown(c.content, extras=['code-friendly', 'fenced-code-blocks']) blog.html_content = markdown(blog.content, extras=['code-friendly', 'fenced-code-blocks']) return { '__template__': 'blog.html', 'web_meta': configs.web_meta, 'user': user, 'cats': cats, 'blog': blog, 'comments': comments, 'disqus': configs.use_disqus }
def get_category(id, request, *, page='1'): user = request.__user__ cats = await Category.findAll(orderBy='created_at desc') category = await Category.find(id) page_index = Page.page2int(page) num = await Blog.findNumber('*', 'cat_id=?', [id]) p = Page(num, page_index, item_page=configs.blog_item_page, page_show=configs.page_show) p.pagelist() if num == 0: blogs = [] else: blogs = await Blog.findAll(where='cat_id=?', args=[id], orderBy='created_at desc', limit=(p.offset, p.limit)) for blog in blogs: blog.html_summary = markdown(blog.summary, extras=['code-friendly', 'fenced-code-blocks']) return { '__template__': 'category.html', 'web_meta': configs.web_meta, 'user': user, 'cats': cats, 'page': p, 'category': category, 'blogs': blogs, 'disqus': configs.use_disqus }
def to_html(self, md = None, scroll_pos = -1, content_only = False): md = md or self.markup.text result = markdown(md, extras=self.extras) if not content_only: intro = Template(self.htmlIntro.safe_substitute(css = self.css)) (font_name, font_size) = self.font result = intro.safe_substitute( background_color = self.to_css_rgba(self.markup.background_color), text_color = self.to_css_rgba(self.markup.text_color), font_family = font_name, text_align = self.to_css_alignment(), font_size = str(font_size)+'px', init_postfix = self.init_postfix, link_prefix = self.link_prefix, debug_prefix = self.debug_prefix, scroll_pos = scroll_pos ) + result + self.htmlOutro return result
def preferred_size(self, using='current', min_width=None, max_width=None, min_height=None, max_height=None): if using=='current': using = 'markdown' if self.editing else 'html' if using=='markdown': self.markup_ghost.text = self.markup.text view = self.markup_ghost else: view = self.web_ghost view.size_to_fit() if max_width and view.width > max_width: view.width = max_width view.size_to_fit() if max_width and view.width > max_width: view.width = max_width if min_width and view.width < min_width: view.width = min_width if max_height and view.height > max_height: view.height = max_height if min_height and view.height < min_height: view.height = min_height return (view.width, view.height)
def get(self, request, param): print('path:%s param:%s' % (request.path, param)) try: article = JDCommentAnalysis.objects.filter(Q(guid__iexact = param) | Q(product_id__iexact = param)).first() article.content = markdown2.markdown(text = article.content, extras = { 'tables': True, 'wiki-tables': True, 'fenced-code-blocks': True, }) context = { 'article': article } return render(request, 'full_result.html', context = context) except: return render(request, '404.html')
def record_result(self, result, color = 'default', font_size = 16, strong = False, type = 'word', br = True, default = False, new_line = False): self.full_result = '' if type == 'word' and default == False: if strong: result = '<strong style="color: %s; font-size: %spx;">%s</strong>' % (color, font_size, result) else: result = '<span style="color: %s; font-size: %spx;">%s</span>' % (color, font_size, result) elif type == 'image': result = markdown2.markdown(result) self.full_result += result if br: self.full_result += '<br>' if new_line: self.full_result += '\n' utils.push_redis(guid = self.guid, product_id = self.product_id, info = self.full_result, type = type) # ?????????
def __init__(self, content): if not isinstance(content, str): raise Exception("Note content must be an instance " "of string, '%s' given." % type(content)) (tempfileHandler, tempfileName) = tempfile.mkstemp(suffix=".markdown") os.write(tempfileHandler, self.ENMLtoText(content)) os.close(tempfileHandler) self.content = content self.tempfile = tempfileName
def student_view(self, context=None): """ The student view of the MarkdownXBlock. """ if self.filename: # These can only be imported when the XBlock is running on the LMS # or CMS. Do it at runtime so that the workbench is usable for # regular XML content. from xmodule.contentstore.content import StaticContent from xmodule.contentstore.django import contentstore from xmodule.exceptions import NotFoundError from opaque_keys import InvalidKeyError try: course_id = self.xmodule_runtime.course_id loc = StaticContent.compute_location(course_id, self.filename) asset = contentstore().find(loc) content = asset.data except (NotFoundError, InvalidKeyError): pass else: content = self.content html_content = "" if content: html_content = markdown2.markdown(content, extras=self.extras) # Render the HTML template context = {'content': html_content} html = loader.render_template('templates/main.html', context) frag = Fragment(html) if "fenced-code-blocks" in self.extras: frag.add_css_url(self.runtime.local_resource_url(self, 'public/css/pygments.css')) return frag
def __init__(self, source_data): import markdown2 if typepy.is_null_string(source_data): raise InvalidDataError super(MarkdownTableFormatter, self).__init__( markdown2.markdown(source_data, extras=["tables"]))
def get_incidents(repo, issues): # loop over all issues in the past 90 days to get current and past incidents incidents = [] collaborators = get_collaborators(repo=repo) for issue in issues: labels = issue.get_labels() affected_systems = sorted(iter_systems(labels)) severity = get_severity(labels) # make sure that non-labeled issues are not displayed if not affected_systems or severity is None: continue # make sure that the user that created the issue is a collaborator if issue.user.login not in collaborators: continue # create an incident incident = { "created": issue.created_at, "title": issue.title, "systems": affected_systems, "severity": severity, "closed": issue.state == "closed", "body": markdown2.markdown(issue.body), "updates": [] } for comment in issue.get_comments(): # add comments by collaborators only if comment.user.login in collaborators: incident["updates"].append({ "created": comment.created_at, "body": markdown2.markdown(comment.body) }) incidents.append(incident) # sort incidents by date return sorted(incidents, key=lambda i: i["created"], reverse=True)
def get_blog(id,request): blog = await Blog.find(id) comments = await Comment.findAll('blog_id=?',[id],orderBy='created_at desc') for c in comments: c.html_content = text2html(c.content) blog.html_content = markdown2.markdown(blog.content) return { '__template__' : 'blog.html', 'blog' : blog, 'comments' : comments, '__user__' : request.__user__ } # ????
def get_queryset(self): query_set = super(BlogListView, self).get_queryset().order_by("-ctime") if self.request.GET.get("search"): query_set = query_set.filter(title__contains=self.request.GET.get("search")) for each in query_set: each.digest = markdown2.markdown(each.digest) return query_set
def get_object(self, queryset=None): obj = get_object_or_404(Blog, id=self.kwargs.get("blog_id")) # obj.article = markdown2.markdown(obj.article) return obj
def block_code(self, code, lang): lang = CODE_LANG if not lang: return '\n<pre><code>%s</code></pre>\n' % \ mistune.escape(code) lexer = get_lexer_by_name(lang, stripall=True) formatter = html.HtmlFormatter() return highlight(code, lexer, formatter) # renderer = HighlightRenderer() # markdown = mistune.Markdown(renderer=renderer) # print(markdown('```python\nassert 1 == 1\n```'))
def md2html_by_markdown2(md_text): import markdown2 extras = ['code-friendly', 'fenced-code-blocks', 'footnotes'] html_text = markdown2.markdown(md_text, extras=extras) return html_text
def convert_md_file(argv): is_convert_html = True if len(sys.argv) >= 3: is_convert_html = False md_filename = argv[0] css_filename = os.path.join(getthispath(), 'default.css') # ??CSS????http://richleland.github.io/pygments-css/ html_filename = '%s.html' % (md_filename[:-3]) pdf_filename = '.'.join([md_filename.rsplit('.')[0], 'pdf']) css_text = None md_text = None with codecs.open(css_filename, mode='r', encoding='utf-8') as f: css_text = '<style type = "text/css">\n' + f.read() + "\n</style>\n" with codecs.open(md_filename, mode='r', encoding='utf-8') as f: md_text = f.read() # ?????????mistune if False: html_text = md2html_by_markdown2(md_text) else: global CODE_LANG CODE_LANG = 'java' markdown = mistune.Markdown(renderer=HighlightRenderer()) html_text = markdown(md_text) if is_convert_html: # save to html file #?windows?encoding?????gbk??????utf-8??????? with codecs.open(html_filename, 'w', encoding='gbk', errors='xmlcharrefreplace') as f: f.write(css_text + html_text) if os.path.exists(html_filename): os.popen(html_filename) else: # save to pdf file HTML(string=html_text).write_pdf(pdf_filename, stylesheets=[css_filename]) if os.path.exists(pdf_filename): os.popen(pdf_filename)
def send(self, event, users, instance, paths): from_address = settings.ASYNC_EMAIL_FROM reply_to = {} if hasattr(settings, 'ASYNC_EMAIL_REPLY_TO'): reply_to = {'Reply-To': settings.ASYNC_EMAIL_REPLY_TO, 'Return-Path': settings.ASYNC_EMAIL_REPLY_TO} messages = [] for user, templates in users.items(): if not self.enabled(event, user, paths) or not user.email: continue template = self._get_template(templates) if template is None: continue params = self.prepare(template, instance) e = mail.EmailMultiAlternatives( subject=params['subject'], body=params['description'], from_email=from_address, to=[user.email, ], headers=reply_to ) e.attach_alternative(markdown2.markdown(params['description'], extras=["link-patterns"], link_patterns=link_registry.link_patterns(request), safe_mode=True), 'text/html') messages.append(e) if len(messages): connection = mail.get_connection() connection.send_messages(messages)
def get_blog(id): blog = yield from Blog.find(id) if not blog: raise APIValueError('id', 'can not find blog id is :{}'.format(id)) comments = yield from Comment.find_all('blog_id=?', [id], order_by='created_at desc') for c in comments: c.html_content = text2html(c.content) blog.html_content = markdown2.markdown(blog.content) return { '__template__': 'blog.html', 'blog': blog, 'comments': comments }
def render(content): result = markdown(content, extras=["code-color"], safe_mode=False) return result
def parse(self, content): """Parse content to raw text. :param content: content to parse :type content: str :return: raw/plain content representation :rtype: str """ return BeautifulSoup(markdown2.markdown(content), 'lxml').get_text()
def blog(blog_id): blog = Blog.get(blog_id) if blog is None: raise notfound() blog.html_content = markdown2.markdown(blog.content) comments = Comment.find_by( 'where blog_id=? order by created_at desc limit 1000', blog_id) return dict(blog=blog, comments=comments, user=ctx.request.user)
def api_get_blogs(): format = ctx.request.get('format', '') blogs, page = _get_blogs_by_page() if format == 'html': for blog in blogs: blog.content = markdown2.markdown(blog.content) return dict(blogs=blogs, page=page)
def save_model(self, request, obj, form, change): """ ????????? """ if settings.MARKDOWN: obj.body = markdown2.markdown(obj.text, extras=['fenced-code-blocks'], ) # ??markdown?? else: obj.body = obj.text obj.description = obj.description or markdown2.markdown(obj.text[:140], extras=['fenced-code-blocks'], ) # ?? obj.author = request.user # ??????? obj.save()
def get_readme(self): readme = self.get_file('README.md') if readme: with open(readme, 'r') as f: readme = markdown(f.read(), extras=["code-friendly"]) return readme
def desc_html(self): if self.description_is_markdown: fmt = markdown2.markdown(self.description, extras=["footnotes", "fenced-code-blocks"]) return mark_safe(fmt) else: return self.description
def get_context_data(self, **kwargs): document = kwargs.pop('legal') with open('/home/lex/projects/osedev/osedev/legal/{}.md'.format(document), 'r') as md: return super().get_context_data( legal=markdown(md.read(), extras=[ 'tables', 'cuddled-lists', 'break-on-newline', 'header-ids' ]), **kwargs )
def custom_markdown(value): return mark_safe(markdown2.markdown(force_text(value), extras=["fenced-code-blocks", "cuddled-lists", "metadata", "tables", "spoiler"]))
def markdown_to_html(self, content): return markdown2.markdown(content).encode("utf-8").decode()
def get_releases(self): res = requests.get( 'https://api.github.com/repos/OGKevin/combunqwebapp/releases') \ .json() try: data = res[:7] except TypeError as e: logging.error(e) return None else: for x in data: x['created_at'] = arrow.get(x['created_at']).format('Do MMM') x['body'] = markdown2.markdown(x['body']) return data
def about(self): """About page, content of it is configurable in settings""" about_page = markdown2.markdown(self.core.config.get("about_page")) return self.render('about.html', about_page=about_page)
def save(self, *args, **kwargs): self.slug = slugify(unidecode(self.title)) if not self.body and self.md_file: self.body = self.md_file.read() html = markdown2.markdown(self.body,extras=["fenced-code-blocks", "tables"]) self.html_file.save(self.title + '.html',ContentFile(html.encode('utf-8')), save=False) self.html_file.close() super().save(*args, **kwargs)