Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def testBaseExtention(self):
""" Test that the base Extension class will raise NotImplemented. """
self.assertRaises(
NotImplementedError,
markdown.Markdown, extensions=[markdown.extensions.Extension()]
)
def buildExtension(self):
""" Build an extension which registers fakeSerializer. """
def fakeSerializer(elem):
# Ignore input and return hardcoded output
return '<div><p>foo</p></div>'
class registerFakeSerializer(markdown.extensions.Extension):
def extendMarkdown(self, md):
md.output_formats['fake'] = fakeSerializer
return registerFakeSerializer()
class HeaderAnchorsTreeprocessor(
markdown.treeprocessors.Treeprocessor):
HEADER_TAGS = {'h1', 'h2', 'h3', 'h4', 'h5', 'h6'}
def run(self, root):
hd_tags = self.HEADER_TAGS
for elem in root.iter():
if elem.tag in hd_tags:
hd_id = elem.text.lower().replace(' ', '-')
hd_id = elem.attrib.setdefault('id', hd_id)
elem.append(etree.Element(
'a',
{'class': 'wiki-header-link',
'href': '#%s' % hd_id}))
class HeaderAnchorsExtension(markdown.extensions.Extension):
def extendMarkdown(self, md, *args, **kwargs):
md.treeprocessors.register(
HeaderAnchorsTreeprocessor(md),
'header_anchors',
100)
class _MarkdownWrapper:
def __init__(self, md):
self._md = md
def __call__(self, text):
self._md.reset()
return self._md.convert(text)
exts = self.config.get('markdown', 'extensions').split(',')
exts.append(HeaderAnchorsExtension())
def render_markdown(markdown_doc):
"""
Render given markdown document and return (html, table_of_contents, meta)
"""
md = markdown.Markdown(extensions=[TocExtension(baselevel=2, marker=''), AttrListExtension(), listStyleExtension(),
'meta'])
html = md.convert(markdown_doc.lstrip())
toc = md.toc.replace('<a class="list-group-item"><ul> around toc by dropping first and last two lines
meta = {k:' '.join(v) for k, v in md.Meta.items()}
return html, toc, meta
class listStyleExtension(Extension):
"""
This extension to the Markdown library looks at li elements which have the add_list_class attribute and
adds the space-separated list of classes to its parent ul or ol element
"""
def extendMarkdown(self, md):
md.treeprocessors.register(listStyleProcessor(md), 'list_style', 7)
class listStyleProcessor(Treeprocessor):
"""
This is the meat of the listStyleExtension extension for python markdown
"""
def run(self, tree):
# the list comprehension that feeds this for loop returns the parent (/..) of all list items regardless of their
# location in the document (//li) if they have the add_list_class attribute ([@add_list_class])
for modified_parent in [ element for element in tree.findall('.//li[@add_list_class]/..') ]:
existing_classes = [] if 'class' not in modified_parent.attrib \</ul></a>
#
# -*- coding: utf-8 -*-
'''
Math extension for Python-Markdown
==================================
Adds support for displaying math formulas using [MathJax](http://www.mathjax.org/).
Author: 2015, Dmitry Shachnev .
'''
import markdown
class MathExtension(markdown.extensions.Extension):
def __init__(self, *args, **kwargs):
self.config = {
'enable_dollar_delimiter': [False, 'Enable single-dollar delimiter'],
'render_to_span': [False,
'Render to span elements rather than script for fallback'],
}
super(MathExtension, self).__init__(*args, **kwargs)
def extendMarkdown(self, md, md_globals):
def handle_match_inline(m):
if self.getConfig('render_to_span'):
node = markdown.util.etree.Element('span')
node.set('class', 'tex')
node.text = ("\\\\(" + markdown.util.AtomicString(m.group(3)) +
"\\\\)")
else:
tags = set()
else:
it = elem.getiterator()
tags = set(tags)
for child in it:
#pout.v(child.tag, tags, child.tag in tags)
if not tags or (child.tag in tags):
yield child
def run(self, doc):
raise NotImplementedError()
class Extension(BaseExtension):
"""
https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/__init__.py
"""
def extendMarkdown(self, md):
raise NotImplementedError()
from markdown.inlinepatterns import SimpleTagPattern
DEL_RE = r'(~~)(.*?)~~' # <del>
INS_RE = r'(__)(.*?)__' # <ins>
MARK_RE = r'(\=\=)(.*?)\=\=' # <mark>
Q_RE = r'(\")(.*?)\"' # <q>
U_RE = r'(_)(.*?)_' # <u>
SUP_RE = r'(\^)([^ ]*)' # <sup>
SUB_RE = r'(\!\!)([^ ]*)' # <sub>
STRONG_RE = r'(\*\*)(.*?)\*\*' # <strong>
EM_RE = r'(\*)(.*?)\*' # <em>
EMPH_RE = r'(\/\/)(.*?)\/\/' #
CAPTION_RE = r'(\*\[\[)(.*?)\]\]\*' #
DROPCAP_RE = r'(\[\[)(.*?)\]\]' # Dropcap
class InlineExtension(Extension):
def extendMarkdown(self, md, md_globals):
# *[[Caption]]* converts to Caption
caption_tag = SimpleTagPattern(CAPTION_RE, 'caption')
md.inlinePatterns.add('caption', caption_tag, '>not_strong')
# ~~Delete~~ converts to <del>Delete</del>
del_tag = SimpleTagPattern(DEL_RE, 'del')
md.inlinePatterns.add('del', del_tag, '>caption')
# __Insert__ converts to <ins>Insert</ins>
ins_tag = SimpleTagPattern(INS_RE, 'ins')
md.inlinePatterns.add('ins', ins_tag, '>del')
# "Quote" converts to <q>Quote</q>
q_tag = SimpleTagPattern(Q_RE, 'q')
md.inlinePatterns.add('q', q_tag, '>ins')
# ==Mark== converts to <mark>..</mark>
mark_tag = SimpleTagPattern(MARK_RE, 'mark')
md.inlinePatterns.add('mark', mark_tag, '>q')</em></strong></sub></sup></u></q></mark></ins></del>
categories = Category.objects.filter(project=project)
serializer = CategorySerializer(categories, many=True)
return Response(serializer.data)
except:
return Response([])
class ImgExtractor(Treeprocessor):
def run(self, doc):
"""Find all images and append to markdown.images."""
self.markdown.images = []
for image in doc.findall('.//img'):
self.markdown.images.append(image.get('src'))
class ImgExtExtension(Extension):
def extendMarkdown(self, md, md_globals):
img_ext = ImgExtractor(md)
md.treeprocessors.add('imgext', img_ext, '>inline')
def download_all_referenced_images(request, **kwargs):
"""Function to download all referenced images from other site."""
project_slug = kwargs.get('project_slug', None)
version_slug = kwargs.get('slug', None)
try:
version = \
Version.objects.get(project__slug=project_slug, slug=version_slug)
except Version.DoesNotExist:
JsonResponse({
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from markdown.extensions import Extension
from markdown.preprocessors import Preprocessor
class ImagifyExtension(Extension):
def extendMarkdown(self, md, md_globals):
md.registerExtension(self)
md.preprocessors.add('imagify',
ImagifyPreprocessor(md),
'_end')
class ImagifyPreprocessor(Preprocessor):
def run(self, lines):
new_lines = []
def imagify(match):
return '![image](%s)' % match.group(0)
import markdown
from _1327.documents.models import Document
from _1327.polls.models import Poll
class InternalLinksMarkdownExtension(markdown.extensions.Extension):
def extendMarkdown(self, md):
md.inlinePatterns.register(Document.LinkPattern(Document.DOCUMENT_LINK_REGEX, md), 'InternalLinkDocumentsPattern', 200)
md.inlinePatterns.register(Poll.LinkPattern(Poll.POLLS_LINK_REGEX, md), 'InternalLinkPollsPattern', 200)