Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
self.md.registerExtensions(["pymdownx._bypassnorm"], {})
tabbed = SuperFencesTabPostProcessor(self.md)
tabbed.config = config
self.md.postprocessors.register(tabbed, "fenced_tabs", 25)
# Add the highlight extension, but do so in a disabled state so we can just retrieve default configurations
self.md.registerExtensions(["pymdownx.highlight"], {"pymdownx.highlight": {"_enabled": False}})
def reset(self):
"""Clear the stash."""
self.stash.clear_stash()
class SuperFencesTabPostProcessor(Postprocessor):
"""Post processor for grouping tabs."""
def repl(self, m):
"""Replace grouped superfences tabs with a tab group."""
self.count += 1
tab_count = 0
tabs = []
for entry in [x.strip() for x in m.group(1).split('<p></p>')]:
tab_count += 1
tabs.append(
entry.replace('<p>', '') % {
'index': self.count,
'tab_index': tab_count,
'state': ('checked="checked" ' if tab_count == 1 else ''),</p>
# Jones, $x=3$, is ...
pat3 = re.compile(r'\$([^\$]+)\$(\s|$)')
out = pat3.sub(repl_2, out)
# # $100 million
# pat2 = re.compile('([^\$])\$([^\$])')
# out = pat2.sub('\g<1>\\$\g<2>', out)
# some extras due to asciimathml
# out = out.replace('\\lt', '<')
# out = out.replace(' * ', ' \\cdot ')
# out = out.replace('\\del', '\\partial')
return out
# ========================= TABLES =================================
class TableTextPostProcessor(markdown.postprocessors.Postprocessor):
def run(self, instr):
"""This is not very sophisticated and for it to work it is expected
that:
1. tables to be in a section on their own (that is at least one
blank line above and below)
2. no nesting of tables
"""
converter = Table2Latex()
new_blocks = []
for block in instr.split('\n\n'):
stripped = block.strip()
#
if stripped.startswith(''):
latex_table = converter.convert(stripped).strip()<table class=".."></table>
def handleMatch(self, m):
node = markdown.util.etree.Element('mathjax')
node.text = markdown.util.AtomicString(m.group(2) + m.group(3) + m.group(2))
return node
class MathJaxExtension(markdown.Extension):
def extendMarkdown(self, md, md_globals):
# Needs to come before escape matching because \ is pretty important in LaTeX
md.inlinePatterns.add('mathjax', MathJaxPattern(), ').)+)-->', re.DOTALL)
def run(self, text):
return self.COMMENTS_RE.sub(self.compile_comment, text)
def compile_comment(self, match):
text = match.group(1)
html = compile_markdown(text)
return '\n<div class="comment">\n{}\n</div>'.format(html)
class CommentExtension(markdown.Extension):
def extendMarkdown(self, md, md_globals):
md.postprocessors.add('commentAltExtension',
CommentProcessor(md.parser),
'>raw_html')
# @Email : i@coderap.com
# @File : ResolveCodeLineNumberExtension.py
# @Software: PyCharm
import copy, re
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from markdown import Extension
from markdown.postprocessors import Postprocessor
class ResolveLineNumberPostprocessor(Postprocessor):
@staticmethod
def addUlTag1(matched):
value = matched.group()
return value
@staticmethod
def addUlTag(matched):
value = matched.group()
return value
preEle = ET.fromstring(value)
children = preEle.getchildren()
if len(children) == 0 and children[0].tag == 'ul':
return value
else:
# 创建ul
self.alinks = []
class MarkAsSafe(markdown.postprocessors.Postprocessor):
def run(self, text):
return h.html.literal(text)
class AddCustomClass(markdown.postprocessors.Postprocessor):
def run(self, text):
return '<div class="markdown_content">%s</div>' % text
class RelativeLinkRewriter(markdown.postprocessors.Postprocessor):
def __init__(self, make_absolute=False):
self._make_absolute = make_absolute
def run(self, text):
soup = BeautifulSoup(text, 'html5lib') # 'html.parser' parser gives weird behaviour with test_macro_members
if self._make_absolute:
rewrite = self._rewrite_abs
else:
rewrite = self._rewrite
for link in soup.findAll('a'):
rewrite(link, 'href')
for link in soup.findAll('img'):
rewrite(link, 'src')
footnotesDiv = self.footnotes.makeFootnotesDiv(root)
if footnotesDiv:
result = self.footnotes.findFootnotesPlaceholder(root)
if result:
child, parent, isText = result
ind = parent.getchildren().index(child)
if isText:
parent.remove(child)
parent.insert(ind, footnotesDiv)
else:
parent.insert(ind + 1, footnotesDiv)
child.tail = None
else:
root.append(footnotesDiv)
class FootnotePostprocessor(markdown.postprocessors.Postprocessor):
""" Replace placeholders with html entities. """
def __init__(self, footnotes):
self.footnotes = footnotes
def run(self, text):
text = text.replace(FN_BACKLINK_TEXT, self.footnotes.getConfig("BACKLINK_TEXT"))
return text.replace(NBSP_PLACEHOLDER, " ")
def makeExtension(configs=[]):
""" Return an instance of the FootnoteExtension """
return FootnoteExtension(configs=configs)
img.set("class", "lazyload")
# Create a global span in which we add both the new img tag and the
# noscript one
outel = markdown.util.etree.Element("span")
outel.append(img)
outel.append(noscript)
output = outel
if MK_VERSION == 3:
output = (outel, out[1], out[2])
return output
class EncapsulateMarkdownPostprocessor(markdown.postprocessors.Postprocessor):
def run(self, text):
return '<div class="markdown">' + text + "</div>"
class PagureExtension(markdown.extensions.Extension):
def extendMarkdown(self, md, md_globals):
# First, make it so that bare links get automatically linkified.
AUTOLINK_RE = "(%s)" % "|".join(
[
r"<((?:[Ff]|[Hh][Tt])[Tt][Pp][Ss]?://[^>]*)>",
r"\b(?:[Ff]|[Hh][Tt])[Tt][Pp][Ss]?://[^)<>\s]+[^.,)<>\s]",
r"<(Ii][Rr][Cc][Ss]?://[^>]*)>",
r"\b[Ii][Rr][Cc][Ss]?://[^)<>\s]+[^.,)<>\s]",
]
)
markdown.inlinepatterns.AUTOLINK_RE = AUTOLINK_RE
Postprocessors must extend markdown.Postprocessor.
"""
def run(self, text):
"""
Subclasses of Postprocessor should implement a `run` method, which
takes the html document as a single text string and returns a
(possibly modified) string.
"""
pass # pragma: no cover
class RawHtmlPostprocessor(Postprocessor):
""" Restore raw html to the document. """
def run(self, text):
""" Iterate over html stash and restore html. """
replacements = OrderedDict()
for i in range(self.md.htmlStash.html_counter):
html = self.md.htmlStash.rawHtmlBlocks[i]
if self.isblocklevel(html):
replacements["<p>%s</p>" %
(self.md.htmlStash.get_placeholder(i))] = \
html + "\n"
replacements[self.md.htmlStash.get_placeholder(i)] = html
if replacements:
pattern = re.compile("|".join(re.escape(k) for k in replacements))
processed_text = pattern.sub(lambda m: replacements[m.group(0)], text)
result = self.footnotes.findFootnotesPlaceholder(root)
if result:
node, isText = result
if isText:
node.text = None
node.getchildren().insert(0, footnotesDiv)
else:
child, element = node
ind = element.getchildren().find(child)
element.getchildren().insert(ind + 1, footnotesDiv)
child.tail = None
fnPlaceholder.parent.replaceChild(fnPlaceholder, footnotesDiv)
else:
root.append(footnotesDiv)
class FootnotePostprocessor(markdown.postprocessors.Postprocessor):
""" Replace placeholders with html entities. """
def run(self, text):
text = text.replace(FN_BACKLINK_TEXT, "↩")
return text.replace(NBSP_PLACEHOLDER, " ")
def makeExtension(configs=[]):
""" Return an instance of the FootnoteExtension """
return FootnoteExtension(configs=configs)
if footnotesDiv is not None:
result = self.footnotes.findFootnotesPlaceholder(root)
if result:
child, parent, isText = result
ind = list(parent).index(child)
if isText:
parent.remove(child)
parent.insert(ind, footnotesDiv)
else:
parent.insert(ind + 1, footnotesDiv)
child.tail = None
else:
root.append(footnotesDiv)
class FootnotePostprocessor(Postprocessor):
""" Replace placeholders with html entities. """
def __init__(self, footnotes):
self.footnotes = footnotes
def run(self, text):
text = text.replace(
FN_BACKLINK_TEXT, self.footnotes.getConfig("BACKLINK_TEXT")
)
return text.replace(NBSP_PLACEHOLDER, " ")
def makeExtension(**kwargs): # pragma: no cover
""" Return an instance of the FootnoteExtension """
return FootnoteExtension(**kwargs)