#!/usr/bin/env python # Copyright (c) 2012 Trent Mick. # Copyright (c) 2007-2008 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A fast and complete Python implementation of Markdown. [from http://daringfireball.net/projects/markdown/] > Markdown is a text-to-HTML filter; it translates an easy-to-read / > easy-to-write structured text format into HTML. Markdown's text > format is most similar to that of plain text email, and supports > features such as headers, *emphasis*, code blocks, blockquotes, and > links. > > Markdown's syntax is designed not as a generic markup language, but > specifically to serve as a front-end to (X)HTML. You can use span-level > HTML tags anywhere in a Markdown document, and you can use block level > HTML tags (like
':
peek_tokens = split_tokens[index: index + 3]
elif token == '':
peek_tokens = split_tokens[index - 2: index + 1]
else:
return False
except IndexError:
return False
return re.match(r'md5-[A-Fa-f0-9]{32}', ''.join(peek_tokens))
tokens = []
split_tokens = self._sorta_html_tokenize_re.split(text)
is_html_markup = False
for index, token in enumerate(split_tokens):
if is_html_markup and not _is_auto_link(token) and not _is_code_span(index, token):
sanitized = self._sanitize_html(token)
key = _hash_text(sanitized)
self.html_spans[key] = sanitized
tokens.append(key)
else:
tokens.append(self._encode_incomplete_tags(token))
is_html_markup = not is_html_markup
return ''.join(tokens)
def _unhash_html_spans(self, text):
for key, sanitized in list(self.html_spans.items()):
text = text.replace(key, sanitized)
return text
def _sanitize_html(self, s):
if self.safe_mode == "replace":
return self.html_removed_text
elif self.safe_mode == "escape":
replacements = [
('&', '&'),
('<', '<'),
('>', '>'),
]
for before, after in replacements:
s = s.replace(before, after)
return s
else:
raise MarkdownError("invalid value for 'safe_mode': %r (must be "
"'escape' or 'replace')" % self.safe_mode)
_inline_link_title = re.compile(r'''
( # \1
[ \t]+
(['"]) # quote char = \2
(?P tags.
"""
yield 0, ""
for tup in inner:
yield tup
yield 0, ""
def _add_newline(self, inner):
# Add newlines around the inner contents so that _strict_tag_block_re matches the outer div.
yield 0, "\n"
yield from inner
yield 0, "\n"
def wrap(self, source, outfile=None):
"""Return the source with a code, pre, and div."""
if outfile is None:
# pygments >= 2.12
return self._add_newline(self._wrap_pre(self._wrap_code(source)))
else:
# pygments < 2.12
return self._wrap_div(self._add_newline(self._wrap_pre(self._wrap_code(source))))
formatter_opts.setdefault("cssclass", "codehilite")
formatter = HtmlCodeFormatter(**formatter_opts)
return pygments.highlight(codeblock, lexer, formatter)
def _code_block_sub(self, match, is_fenced_code_block=False):
lexer_name = None
if is_fenced_code_block:
lexer_name = match.group(2)
codeblock = match.group(3)
codeblock = codeblock[:-1] # drop one trailing newline
else:
codeblock = match.group(1)
codeblock = self._outdent(codeblock)
codeblock = self._detab(codeblock)
codeblock = codeblock.lstrip('\n') # trim leading newlines
codeblock = codeblock.rstrip() # trim trailing whitespace
# Use pygments only if not using the highlightjs-lang extra
if lexer_name and "highlightjs-lang" not in self.extras:
lexer = self._get_pygments_lexer(lexer_name)
if lexer:
leading_indent = ' '*(len(match.group(1)) - len(match.group(1).lstrip()))
return self._code_block_with_lexer_sub(codeblock, leading_indent, lexer, is_fenced_code_block)
pre_class_str = self._html_class_str_from_tag("pre")
if "highlightjs-lang" in self.extras and lexer_name:
code_class_str = ' class="%s language-%s"' % (lexer_name, lexer_name)
else:
code_class_str = self._html_class_str_from_tag("code")
if is_fenced_code_block:
# Fenced code blocks need to be outdented before encoding, and then reapplied
leading_indent = ' ' * (len(match.group(1)) - len(match.group(1).lstrip()))
if codeblock:
# only run the codeblock through the outdenter if not empty
leading_indent, codeblock = self._uniform_outdent(codeblock, max_outdent=leading_indent)
codeblock = self._encode_code(codeblock)
if lexer_name == 'mermaid' and 'mermaid' in self.extras:
return '\n%s%s\n
\n' % (
leading_indent, codeblock)
return "\n%s%s\n
\n" % (
leading_indent, pre_class_str, code_class_str, codeblock)
else:
codeblock = self._encode_code(codeblock)
return "\n%s\n
\n" % (
pre_class_str, code_class_str, codeblock)
def _code_block_with_lexer_sub(self, codeblock, leading_indent, lexer, is_fenced_code_block):
if is_fenced_code_block:
formatter_opts = self.extras['fenced-code-blocks'] or {}
else:
formatter_opts = {}
def unhash_code(codeblock):
for key, sanitized in list(self.html_spans.items()):
codeblock = codeblock.replace(key, sanitized)
replacements = [
("&", "&"),
("<", "<"),
(">", ">")
]
for old, new in replacements:
codeblock = codeblock.replace(old, new)
return codeblock
# remove leading indent from code block
_, codeblock = self._uniform_outdent(codeblock, max_outdent=leading_indent)
codeblock = unhash_code(codeblock)
colored = self._color_with_pygments(codeblock, lexer,
**formatter_opts)
# add back the indent to all lines
return "\n%s\n" % self._uniform_indent(colored, leading_indent, True)
def _html_class_str_from_tag(self, tag):
"""Get the appropriate ' class="..."' string (note the leading
space), if any, for the given tag.
"""
if "html-classes" not in self.extras:
return ""
try:
html_classes_from_tag = self.extras["html-classes"]
except TypeError:
return ""
else:
if isinstance(html_classes_from_tag, dict):
if tag in html_classes_from_tag:
return ' class="%s"' % html_classes_from_tag[tag]
return ""
def _do_code_blocks(self, text):
"""Process Markdown `` blocks."""
code_block_re = re.compile(r'''
(?:\n\n|\A\n?)
( # $1 = the code block -- one or more lines, starting with a space/tab
(?:
(?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces
.*\n+
)+
)
((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
# Lookahead to make sure this block isn't already in a code block.
# Needed when syntax highlighting is being used.
(?!([^<]|<(/?)span)*\)
''' % (self.tab_width, self.tab_width),
re.M | re.X)
return code_block_re.sub(self._code_block_sub, text)
_fenced_code_block_re = re.compile(r'''
(?:\n+|\A\n?|(?<=\n))
(^[ \t]*`{3,})\s{0,99}?([\w+-]+)?\s{0,99}?\n # $1 = opening fence (captured for back-referencing), $2 = optional lang
(.*?) # $3 = code block content
\1[ \t]*\n # closing fence
''', re.M | re.X | re.S)
def _fenced_code_block_sub(self, match):
return self._code_block_sub(match, is_fenced_code_block=True)
def _do_fenced_code_blocks(self, text):
"""Process ```-fenced unindented code blocks ('fenced-code-blocks' extra)."""
return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text)
# Rules for a code span:
# - backslash escapes are not interpreted in a code span
# - to include one or or a run of more backticks the delimiters must
# be a longer run of backticks
# - cannot start or end a code span with a backtick; pad with a
# space and that space will be removed in the emitted HTML
# See `test/tm-cases/escapes.text` for a number of edge-case
# examples.
_code_span_re = re.compile(r'''
(?%s
" % (self._html_class_str_from_tag("code"), c)
def _do_code_spans(self, text):
# * Backtick quotes are used for spans.
#
# * You can use multiple backticks as the delimiters if you want to
# include literal backticks in the code span. So, this input:
#
# Just type ``foo `bar` baz`` at the prompt.
#
# Will translate to:
#
# Just type foo `bar` baz at the prompt.
`bar` ...
return self._code_span_re.sub(self._code_span_sub, text)
def _encode_code(self, text):
"""Encode/escape certain characters inside Markdown code runs.
The point is that in code, these characters are literals,
and lose their special Markdown meanings.
"""
replacements = [
# Encode all ampersands; HTML entities are not
# entities within a Markdown code span.
('&', '&'),
# Do the angle bracket song and dance:
('<', '<'),
('>', '>'),
]
for before, after in replacements:
text = text.replace(before, after)
hashed = _hash_text(text)
self._code_table[text] = hashed
return hashed
def _wavedrom_block_sub(self, match):
# if this isn't a wavedrom diagram block, exit now
if match.group(2) != 'wavedrom':
return match.string[match.start():match.end()]
# dedent the block for processing
lead_indent, waves = self._uniform_outdent(match.group(3))
# default tags to wrap the wavedrom block in
open_tag, close_tag = ''
# check if the user would prefer to have the SVG embedded directly
if not isinstance(self.extras['wavedrom'], dict):
embed_svg = True
else:
# default behaviour is to embed SVGs
embed_svg = self.extras['wavedrom'].get('prefer_embed_svg', True)
if embed_svg:
try:
import wavedrom
waves = wavedrom.render(waves).tostring()
open_tag, close_tag = '.+?)', re.S) def _dedent_two_spaces_sub(self, match): return re.sub(r'(?m)^ ', '', match.group(1)) def _block_quote_sub(self, match): bq = match.group(1) is_spoiler = 'spoiler' in self.extras and self._bq_all_lines_spoilers.match(bq) # trim one level of quoting if is_spoiler: bq = self._bq_one_level_re_spoiler.sub('', bq) else: bq = self._bq_one_level_re.sub('', bq) # trim whitespace-only lines bq = self._ws_only_line_re.sub('', bq) bq = self._run_block_gamut(bq) # recurse bq = re.sub('(?m)^', ' ', bq) # These leading spaces screw with
content, so we need to fix that:
bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq)
if is_spoiler:
return '\n%s\n
\n\n' % bq
else:
return '\n%s\n
\n\n' % bq
def _do_block_quotes(self, text):
if '>' not in text:
return text
if 'spoiler' in self.extras:
return self._block_quote_re_spoiler.sub(self._block_quote_sub, text)
else:
return self._block_quote_re.sub(self._block_quote_sub, text)
def _form_paragraphs(self, text):
# Strip leading and trailing lines:
text = text.strip('\n')
# Wrap tags.
grafs = []
for i, graf in enumerate(re.split(r"\n{2,}", text)):
if graf in self.html_blocks:
# Unhashify HTML blocks
grafs.append(self.html_blocks[graf])
else:
cuddled_list = None
if "cuddled-lists" in self.extras:
# Need to put back trailing '\n' for `_list_item_re`
# match at the end of the paragraph.
li = self._list_item_re.search(graf + '\n')
# Two of the same list marker in this paragraph: a likely
# candidate for a list cuddled to preceding paragraph
# text (issue 33). Note the `[-1]` is a quick way to
# consider numeric bullets (e.g. "1." and "2.") to be
# equal.
if (li and len(li.group(2)) <= 3
and (
(li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1])
or
li.group("next_marker") is None
)
):
start = li.start()
cuddled_list = self._do_lists(graf[start:]).rstrip("\n")
assert re.match(r'^<(?:ul|ol).*?>', cuddled_list)
graf = graf[:start]
# Wrap
tags.
graf = self._run_span_gamut(graf)
grafs.append("
" % self._html_class_str_from_tag('p') + graf.lstrip(" \t") + "
")
if cuddled_list:
grafs.append(cuddled_list)
return "\n\n".join(grafs)
def _add_footnotes(self, text):
if self.footnotes:
footer = [
'',
'
',
]
if not self.footnote_title:
self.footnote_title = "Jump back to footnote %d in the text."
if not self.footnote_return_symbol:
self.footnote_return_symbol = "↩"
for i, id in enumerate(self.footnote_ids):
if i != 0:
footer.append('')
footer.append('' % id)
footer.append(self._run_block_gamut(self.footnotes[id]))
try:
backlink = ('' +
self.footnote_return_symbol +
'') % (id, i+1)
except TypeError:
log.debug("Footnote error. `footnote_title` "
"must include parameter. Using defaults.")
backlink = (''
'↩' % (id, i+1))
if footer[-1].endswith(""):
footer[-1] = footer[-1][:-len("")] \
+ ' ' + backlink + ""
else:
footer.append("\n%s
" % backlink)
footer.append(' ')
footer.append('')
footer.append('')
return text + '\n\n' + '\n'.join(footer)
else:
return text
_naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I)
_naked_gt_re = re.compile(r'''(?''', re.I)
def _encode_amps_and_angles(self, text):
# Smart processing for ampersands and angle brackets that need
# to be encoded.
text = _AMPERSAND_RE.sub('&', text)
# Encode naked <'s
text = self._naked_lt_re.sub('<', text)
# Encode naked >'s
# Note: Other markdown implementations (e.g. Markdown.pl, PHP
# Markdown) don't do this.
text = self._naked_gt_re.sub('>', text)
return text
_incomplete_tags_re = re.compile(r"<(/?\w+?(?!\w)\s*?.+?[\s/]+?)")
def _encode_incomplete_tags(self, text):
if self.safe_mode not in ("replace", "escape"):
return text
if text.endswith(">"):
return text # this is not an incomplete tag, this is a link in the form
def incomplete_tags_sub(match):
return match.group().replace('<', '<')
return self._incomplete_tags_re.sub(incomplete_tags_sub, text)
def _encode_backslash_escapes(self, text):
for ch, escape in list(self._escape_table.items()):
text = text.replace("\\"+ch, escape)
return text
_auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I)
def _auto_link_sub(self, match):
g1 = match.group(1)
return '%s' % (self._protect_url(g1), g1)
_auto_email_link_re = re.compile(r"""
<
(?:mailto:)?
(
[-.\w]+
\@
[-\w]+(\.[-\w]+)*\.[a-z]+
)
>
""", re.I | re.X | re.U)
def _auto_email_link_sub(self, match):
return self._encode_email_address(
self._unescape_special_chars(match.group(1)))
def _do_auto_links(self, text):
text = self._auto_link_re.sub(self._auto_link_sub, text)
text = self._auto_email_link_re.sub(self._auto_email_link_sub, text)
return text
def _encode_email_address(self, addr):
# Input: an email address, e.g. "foo@example.com"
#
# Output: the email address as a mailto link, with each character
# of the address encoded as either a decimal or hex entity, in
# the hopes of foiling most address harvesting spam bots. E.g.:
#
# foo
# @example.com
#
# Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
# mailing list:
chars = [_xml_encode_email_char_at_random(ch)
for ch in "mailto:" + addr]
# Strip the mailto: from the visible part.
addr = '%s' \
% (''.join(chars), ''.join(chars[7:]))
return addr
_basic_link_re = re.compile(r'!?\[.*?\]\(.*?\)')
def _do_link_patterns(self, text):
link_from_hash = {}
for regex, repl in self.link_patterns:
replacements = []
for match in regex.finditer(text):
if any(self._match_overlaps_substr(text, match, h) for h in link_from_hash):
continue
if hasattr(repl, "__call__"):
href = repl(match)
else:
href = match.expand(repl)
replacements.append((match.span(), href))
for (start, end), href in reversed(replacements):
# Do not match against links inside brackets.
if text[start - 1:start] == '[' and text[end:end + 1] == ']':
continue
# Do not match against links in the standard markdown syntax.
if text[start - 2:start] == '](' or text[end:end + 2] == '")':
continue
# Do not match against links which are escaped.
if text[start - 3:start] == '"""' and text[end:end + 3] == '"""':
text = text[:start - 3] + text[start:end] + text[end + 3:]
continue
# search the text for anything that looks like a link
is_inside_link = False
for link_re in (self._auto_link_re, self._basic_link_re):
for match in link_re.finditer(text):
if any((r[0] <= start and end <= r[1]) for r in match.regs):
# if the link pattern start and end pos is within the bounds of
# something that looks like a link, then don't process it
is_inside_link = True
break
else:
continue
break
if is_inside_link:
continue
escaped_href = (
href.replace('"', '"') # b/c of attr quote
# To avoid markdown and :
.replace('*', self._escape_table['*'])
.replace('_', self._escape_table['_']))
link = '%s' % (escaped_href, text[start:end])
hash = _hash_text(link)
link_from_hash[hash] = link
text = text[:start] + hash + text[end:]
for hash, link in list(link_from_hash.items()):
text = text.replace(hash, link)
return text
def _unescape_special_chars(self, text):
# Swap back in all the special characters we've hidden.
hashmap = tuple(self._escape_table.items()) + tuple(self._code_table.items())
# html_blocks table is in format {hash: item} compared to usual {item: hash}
hashmap += tuple(tuple(reversed(i)) for i in self.html_blocks.items())
while True:
orig_text = text
for ch, hash in hashmap:
text = text.replace(hash, ch)
if text == orig_text:
break
return text
def _outdent(self, text):
# Remove one level of line-leading tabs or spaces
return self._outdent_re.sub('', text)
@staticmethod
def _uniform_outdent(text, min_outdent=None, max_outdent=None):
'''
Removes the smallest common leading indentation from each (non empty)
line of `text` and returns said indent along with the outdented text.
Args:
min_outdent: make sure the smallest common whitespace is at least this size
max_outdent: the maximum amount a line can be outdented by
'''
# find the leading whitespace for every line
whitespace = [
re.findall(r'^[ \t]*', line)[0] if line else None
for line in text.splitlines()
]
whitespace_not_empty = [i for i in whitespace if i is not None]
# if no whitespace detected (ie: no lines in code block, issue #505)
if not whitespace_not_empty:
return '', text
# get minimum common whitespace
outdent = min(whitespace_not_empty)
# adjust min common ws to be within bounds
if min_outdent is not None:
outdent = min([i for i in whitespace_not_empty if i >= min_outdent] or [min_outdent])
if max_outdent is not None:
outdent = min(outdent, max_outdent)
outdented = []
for line_ws, line in zip(whitespace, text.splitlines(True)):
if line.startswith(outdent):
# if line starts with smallest common ws, dedent it
outdented.append(line.replace(outdent, '', 1))
elif line_ws is not None and line_ws < outdent:
# if less indented than min common whitespace then outdent as much as possible
outdented.append(line.replace(line_ws, '', 1))
else:
outdented.append(line)
return outdent, ''.join(outdented)
@staticmethod
def _uniform_indent(text, indent, include_empty_lines=False, indent_empty_lines=False):
'''
Uniformly indent a block of text by a fixed amount
Args:
text: the text to indent
indent: a string containing the indent to apply
include_empty_lines: don't remove whitespace only lines
indent_empty_lines: indent whitespace only lines with the rest of the text
'''
blocks = []
for line in text.splitlines(True):
if line.strip() or indent_empty_lines:
blocks.append(indent + line)
elif include_empty_lines:
blocks.append(line)
else:
blocks.append('')
return ''.join(blocks)
@staticmethod
def _match_overlaps_substr(text, match, substr):
'''
Checks if a regex match overlaps with a substring in the given text.
'''
for instance in re.finditer(re.escape(substr), text):
start, end = instance.span()
if start <= match.start() <= end:
return True
if start <= match.end() <= end:
return True
return False
class MarkdownWithExtras(Markdown):
"""A markdowner class that enables most extras:
- footnotes
- fenced-code-blocks (only highlights code if 'pygments' Python module on path)
These are not included:
- pyshell (specific to Python-related documenting)
- code-friendly (because it *disables* part of the syntax)
- link-patterns (because you need to specify some actual
link-patterns anyway)
"""
extras = ["footnotes", "fenced-code-blocks"]
# ---- internal support functions
def calculate_toc_html(toc):
"""Return the HTML for the current TOC.
This expects the `_toc` attribute to have been set on this instance.
"""
if toc is None:
return None
def indent():
return ' ' * (len(h_stack) - 1)
lines = []
h_stack = [0] # stack of header-level numbers
for level, id, name in toc:
if level > h_stack[-1]:
lines.append("%s" % indent())
h_stack.append(level)
elif level == h_stack[-1]:
lines[-1] += ""
else:
while level < h_stack[-1]:
h_stack.pop()
if not lines[-1].endswith(""):
lines[-1] += ""
lines.append("%s
" % indent())
lines.append('%s%s' % (
indent(), id, name))
while len(h_stack) > 1:
h_stack.pop()
if not lines[-1].endswith(" "):
lines[-1] += ""
lines.append("%s" % indent())
return '\n'.join(lines) + '\n'
class UnicodeWithAttrs(str):
"""A subclass of unicode used for the return value of conversion to
possibly attach some attributes. E.g. the "toc_html" attribute when
the "toc" extra is used.
"""
metadata = None
toc_html = None
## {{{ http://code.activestate.com/recipes/577257/ (r1)
_slugify_strip_re = re.compile(r'[^\w\s-]')
_slugify_hyphenate_re = re.compile(r'[-\s]+')
def _slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
From Django's "django/template/defaultfilters.py".
"""
import unicodedata
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode()
value = _slugify_strip_re.sub('', value).strip().lower()
return _slugify_hyphenate_re.sub('-', value)
## end of http://code.activestate.com/recipes/577257/ }}}
# From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
def _curry(*args, **kwargs):
function, args = args[0], args[1:]
def result(*rest, **kwrest):
combined = kwargs.copy()
combined.update(kwrest)
return function(*args + rest, **combined)
return result
# Recipe: regex_from_encoded_pattern (1.0)
def _regex_from_encoded_pattern(s):
"""'foo' -> re.compile(re.escape('foo'))
'/foo/' -> re.compile('foo')
'/foo/i' -> re.compile('foo', re.I)
"""
if s.startswith('/') and s.rfind('/') != 0:
# Parse it: /PATTERN/FLAGS
idx = s.rfind('/')
_, flags_str = s[1:idx], s[idx+1:]
flag_from_char = {
"i": re.IGNORECASE,
"l": re.LOCALE,
"s": re.DOTALL,
"m": re.MULTILINE,
"u": re.UNICODE,
}
flags = 0
for char in flags_str:
try:
flags |= flag_from_char[char]
except KeyError:
raise ValueError("unsupported regex flag: '%s' in '%s' "
"(must be one of '%s')"
% (char, s, ''.join(list(flag_from_char.keys()))))
return re.compile(s[1:idx], flags)
else: # not an encoded regex
return re.compile(re.escape(s))
# Recipe: dedent (0.1.2)
def _dedentlines(lines, tabsize=8, skip_first_line=False):
"""_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
"lines" is a list of lines to dedent.
"tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first line should
be skipped for calculating the indent width and for dedenting.
This is sometimes useful for docstrings and similar.
Same as dedent() except operates on a sequence of lines. Note: the
lines list is modified **in-place**.
"""
DEBUG = False
if DEBUG:
print("dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\
% (tabsize, skip_first_line))
margin = None
for i, line in enumerate(lines):
if i == 0 and skip_first_line: continue
indent = 0
for ch in line:
if ch == ' ':
indent += 1
elif ch == '\t':
indent += tabsize - (indent % tabsize)
elif ch in '\r\n':
continue # skip all-whitespace lines
else:
break
else:
continue # skip all-whitespace lines
if DEBUG: print("dedent: indent=%d: %r" % (indent, line))
if margin is None:
margin = indent
else:
margin = min(margin, indent)
if DEBUG: print("dedent: margin=%r" % margin)
if margin is not None and margin > 0:
for i, line in enumerate(lines):
if i == 0 and skip_first_line: continue
removed = 0
for j, ch in enumerate(line):
if ch == ' ':
removed += 1
elif ch == '\t':
removed += tabsize - (removed % tabsize)
elif ch in '\r\n':
if DEBUG: print("dedent: %r: EOL -> strip up to EOL" % line)
lines[i] = lines[i][j:]
break
else:
raise ValueError("unexpected non-whitespace char %r in "
"line %r while removing %d-space margin"
% (ch, line, margin))
if DEBUG:
print("dedent: %r: %r -> removed %d/%d"\
% (line, ch, removed, margin))
if removed == margin:
lines[i] = lines[i][j+1:]
break
elif removed > margin:
lines[i] = ' '*(removed-margin) + lines[i][j+1:]
break
else:
if removed:
lines[i] = lines[i][removed:]
return lines
def _dedent(text, tabsize=8, skip_first_line=False):
"""_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
"text" is the text to dedent.
"tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first line should
be skipped for calculating the indent width and for dedenting.
This is sometimes useful for docstrings and similar.
textwrap.dedent(s), but don't expand tabs to spaces
"""
lines = text.splitlines(1)
_dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)
return ''.join(lines)
class _memoized(object):
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
http://wiki.python.org/moin/PythonDecoratorLibrary
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
self.cache[args] = value = self.func(*args)
return value
except TypeError:
# uncachable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
def __repr__(self):
"""Return the function's docstring."""
return self.func.__doc__
def _xml_oneliner_re_from_tab_width(tab_width):
"""Standalone XML processing instruction regex."""
return re.compile(r"""
(?:
(?<=\n\n) # Starting after a blank line
| # or
\A\n? # the beginning of the doc
)
( # save in $1
[ ]{0,%d}
(?:
<\?\w+\b\s+.*?\?> # XML processing instruction
|
<\w+:\w+\b\s+.*?/> # namespaced single tag
)
[ \t]*
(?=\n{2,}|\Z) # followed by a blank line or end of document
)
""" % (tab_width - 1), re.X)
_xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width)
def _hr_tag_re_from_tab_width(tab_width):
return re.compile(r"""
(?:
(?<=\n\n) # Starting after a blank line
| # or
\A\n? # the beginning of the doc
)
( # save in \1
[ ]{0,%d}
<(hr) # start tag = \2
\b # word break
([^<>])*? #
/?> # the matching end tag
[ \t]*
(?=\n{2,}|\Z) # followed by a blank line or end of document
)
""" % (tab_width - 1), re.X)
_hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width)
def _xml_escape_attr(attr, skip_single_quote=True):
"""Escape the given string for use in an HTML/XML tag attribute.
By default this doesn't bother with escaping `'` to `'`, presuming that
the tag attribute is surrounded by double quotes.
"""
escaped = _AMPERSAND_RE.sub('&', attr)
escaped = (attr
.replace('"', '"')
.replace('<', '<')
.replace('>', '>'))
if not skip_single_quote:
escaped = escaped.replace("'", "'")
return escaped
def _xml_encode_email_char_at_random(ch):
r = random()
# Roughly 10% raw, 45% hex, 45% dec.
# '@' *must* be encoded. I [John Gruber] insist.
# Issue 26: '_' must be encoded.
if r > 0.9 and ch not in "@_":
return ch
elif r < 0.45:
# The [1:] is to drop leading '0': 0x63 -> x63
return '%s;' % hex(ord(ch))[1:]
else:
return '%s;' % ord(ch)
def _html_escape_url(attr, safe_mode=False):
"""Replace special characters that are potentially malicious in url string."""
escaped = (attr
.replace('"', '"')
.replace('<', '<')
.replace('>', '>'))
if safe_mode:
escaped = escaped.replace('+', ' ')
escaped = escaped.replace("'", "'")
return escaped
# ---- mainline
class _NoReflowFormatter(argparse.RawDescriptionHelpFormatter):
"""An argparse formatter that does NOT reflow the description."""
def format_description(self, description):
return description or ""
def _test():
import doctest
doctest.testmod()
def main(argv=None):
if argv is None:
argv = sys.argv
if not logging.root.handlers:
logging.basicConfig()
parser = argparse.ArgumentParser(
prog="markdown2", description=cmdln_desc, usage='%(prog)s [PATHS...]',
formatter_class=_NoReflowFormatter
)
parser.add_argument('--version', action='version',
version='%(prog)s {version}'.format(version=__version__))
parser.add_argument('paths', nargs='*',
help=(
'optional list of files to convert.'
'If none are given, stdin will be used'
))
parser.add_argument("-v", "--verbose", dest="log_level",
action="store_const", const=logging.DEBUG,
help="more verbose output")
parser.add_argument("--encoding",
help="specify encoding of text content")
parser.add_argument("--html4tags", action="store_true", default=False,
help="use HTML 4 style for empty element tags")
parser.add_argument("-s", "--safe", metavar="MODE", dest="safe_mode",
help="sanitize literal HTML: 'escape' escapes "
"HTML meta chars, 'replace' replaces with an "
"[HTML_REMOVED] note")
parser.add_argument("-x", "--extras", action="append",
help="Turn on specific extra features (not part of "
"the core Markdown spec). See above.")
parser.add_argument("--use-file-vars",
help="Look for and use Emacs-style 'markdown-extras' "
"file var to turn on extras. See "
"")
parser.add_argument("--link-patterns-file",
help="path to a link pattern file")
parser.add_argument("--self-test", action="store_true",
help="run internal self-tests (some doctests)")
parser.add_argument("--compare", action="store_true",
help="run against Markdown.pl as well (for testing)")
parser.set_defaults(log_level=logging.INFO, compare=False,
encoding="utf-8", safe_mode=None, use_file_vars=False)
opts = parser.parse_args()
paths = opts.paths
log.setLevel(opts.log_level)
if opts.self_test:
return _test()
if opts.extras:
extras = {}
for s in opts.extras:
splitter = re.compile("[,;: ]+")
for e in splitter.split(s):
if '=' in e:
ename, earg = e.split('=', 1)
try:
earg = int(earg)
except ValueError:
pass
else:
ename, earg = e, None
extras[ename] = earg
else:
extras = None
if opts.link_patterns_file:
link_patterns = []
f = open(opts.link_patterns_file)
try:
for i, line in enumerate(f.readlines()):
if not line.strip(): continue
if line.lstrip().startswith("#"): continue
try:
pat, href = line.rstrip().rsplit(None, 1)
except ValueError:
raise MarkdownError("%s:%d: invalid link pattern line: %r"
% (opts.link_patterns_file, i+1, line))
link_patterns.append(
(_regex_from_encoded_pattern(pat), href))
finally:
f.close()
else:
link_patterns = None
from os.path import abspath, dirname, exists, join
markdown_pl = join(dirname(dirname(abspath(__file__))), "test",
"Markdown.pl")
if not paths:
paths = ['-']
for path in paths:
if path == '-':
text = sys.stdin.read()
else:
fp = codecs.open(path, 'r', opts.encoding)
text = fp.read()
fp.close()
if opts.compare:
from subprocess import PIPE, Popen
print("==== Markdown.pl ====")
p = Popen('perl %s' % markdown_pl, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True)
p.stdin.write(text.encode('utf-8'))
p.stdin.close()
perl_html = p.stdout.read().decode('utf-8')
sys.stdout.write(perl_html)
print("==== markdown2.py ====")
html = markdown(text,
html4tags=opts.html4tags,
safe_mode=opts.safe_mode,
extras=extras, link_patterns=link_patterns,
use_file_vars=opts.use_file_vars,
cli=True)
sys.stdout.write(html)
if extras and "toc" in extras:
log.debug("toc_html: " +
str(html.toc_html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')))
if opts.compare:
test_dir = join(dirname(dirname(abspath(__file__))), "test")
if exists(join(test_dir, "test_markdown2.py")):
sys.path.insert(0, test_dir)
from test_markdown2 import norm_html_from_html
norm_html = norm_html_from_html(html)
norm_perl_html = norm_html_from_html(perl_html)
else:
norm_html = html
norm_perl_html = perl_html
print("==== match? %r ====" % (norm_perl_html == norm_html))
if __name__ == "__main__":
sys.exit(main(sys.argv))