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)
python类markdown()的实例源码
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 __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__
}
# ????