PageRenderTime 64ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/markdown2.py

https://github.com/revolunet/python-markdown2
Python | 2321 lines | 2196 code | 39 blank | 86 comment | 73 complexity | 489c08b2d5bc6823f5bdbb0aaa1bbe72 MD5 | raw file
Possible License(s): MIT
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 Trent Mick.
  3. # Copyright (c) 2007-2008 ActiveState Corp.
  4. # License: MIT (http://www.opensource.org/licenses/mit-license.php)
  5. from __future__ import generators
  6. r"""A fast and complete Python implementation of Markdown.
  7. [from http://daringfireball.net/projects/markdown/]
  8. > Markdown is a text-to-HTML filter; it translates an easy-to-read /
  9. > easy-to-write structured text format into HTML. Markdown's text
  10. > format is most similar to that of plain text email, and supports
  11. > features such as headers, *emphasis*, code blocks, blockquotes, and
  12. > links.
  13. >
  14. > Markdown's syntax is designed not as a generic markup language, but
  15. > specifically to serve as a front-end to (X)HTML. You can use span-level
  16. > HTML tags anywhere in a Markdown document, and you can use block level
  17. > HTML tags (like <div> and <table> as well).
  18. Module usage:
  19. >>> import markdown2
  20. >>> markdown2.markdown("*boo!*") # or use `html = markdown_path(PATH)`
  21. u'<p><em>boo!</em></p>\n'
  22. >>> markdowner = Markdown()
  23. >>> markdowner.convert("*boo!*")
  24. u'<p><em>boo!</em></p>\n'
  25. >>> markdowner.convert("**boom!**")
  26. u'<p><strong>boom!</strong></p>\n'
  27. This implementation of Markdown implements the full "core" syntax plus a
  28. number of extras (e.g., code syntax coloring, footnotes) as described on
  29. <https://github.com/trentm/python-markdown2/wiki/Extras>.
  30. """
  31. cmdln_desc = """A fast and complete Python implementation of Markdown, a
  32. text-to-HTML conversion tool for web writers.
  33. Supported extra syntax options (see -x|--extras option below and
  34. see <https://github.com/trentm/python-markdown2/wiki/Extras> for details):
  35. * code-friendly: Disable _ and __ for em and strong.
  36. * cuddled-lists: Allow lists to be cuddled to the preceding paragraph.
  37. * fenced-code-blocks: Allows a code block to not have to be indented
  38. by fencing it with '```' on a line before and after. Based on
  39. <http://github.github.com/github-flavored-markdown/> with support for
  40. syntax highlighting.
  41. * footnotes: Support footnotes as in use on daringfireball.net and
  42. implemented in other Markdown processors (tho not in Markdown.pl v1.0.1).
  43. * header-ids: Adds "id" attributes to headers. The id value is a slug of
  44. the header text.
  45. * html-classes: Takes a dict mapping html tag names (lowercase) to a
  46. string to use for a "class" tag attribute. Currently only supports
  47. "pre" and "code" tags. Add an issue if you require this for other tags.
  48. * markdown-in-html: Allow the use of `markdown="1"` in a block HTML tag to
  49. have markdown processing be done on its contents. Similar to
  50. <http://michelf.com/projects/php-markdown/extra/#markdown-attr> but with
  51. some limitations.
  52. * metadata: Extract metadata from a leading '---'-fenced block.
  53. See <https://github.com/trentm/python-markdown2/issues/77> for details.
  54. * nofollow: Add `rel="nofollow"` to add `<a>` tags with an href. See
  55. <http://en.wikipedia.org/wiki/Nofollow>.
  56. * pyshell: Treats unindented Python interactive shell sessions as <code>
  57. blocks.
  58. * link-patterns: Auto-link given regex patterns in text (e.g. bug number
  59. references, revision number references).
  60. * smarty-pants: Replaces ' and " with curly quotation marks or curly
  61. apostrophes. Replaces --, ---, ..., and . . . with en dashes, em dashes,
  62. and ellipses.
  63. * toc: The returned HTML string gets a new "toc_html" attribute which is
  64. a Table of Contents for the document. (experimental)
  65. * xml: Passes one-liner processing instructions and namespaced XML tags.
  66. * wiki-tables: Google Code Wiki-style tables. See
  67. <http://code.google.com/p/support/wiki/WikiSyntax#Tables>.
  68. """
  69. # Dev Notes:
  70. # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm
  71. # not yet sure if there implications with this. Compare 'pydoc sre'
  72. # and 'perldoc perlre'.
  73. __version_info__ = (2, 1, 1)
  74. __version__ = '.'.join(map(str, __version_info__))
  75. __author__ = "Trent Mick"
  76. import os
  77. import sys
  78. from pprint import pprint
  79. import re
  80. import logging
  81. try:
  82. from hashlib import md5
  83. except ImportError:
  84. from md5 import md5
  85. import optparse
  86. from random import random, randint
  87. import codecs
  88. #---- Python version compat
  89. try:
  90. from urllib.parse import quote # python3
  91. except ImportError:
  92. from urllib import quote # python2
  93. if sys.version_info[:2] < (2,4):
  94. from sets import Set as set
  95. def reversed(sequence):
  96. for i in sequence[::-1]:
  97. yield i
  98. # Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3).
  99. if sys.version_info[0] <= 2:
  100. py3 = False
  101. try:
  102. bytes
  103. except NameError:
  104. bytes = str
  105. base_string_type = basestring
  106. elif sys.version_info[0] >= 3:
  107. py3 = True
  108. unicode = str
  109. base_string_type = str
  110. #---- globals
  111. DEBUG = False
  112. log = logging.getLogger("markdown")
  113. DEFAULT_TAB_WIDTH = 4
  114. SECRET_SALT = bytes(randint(0, 1000000))
  115. def _hash_text(s):
  116. return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest()
  117. # Table of hash values for escaped characters:
  118. g_escape_table = dict([(ch, _hash_text(ch))
  119. for ch in '\\`*_{}[]()>#+-.!'])
  120. #---- exceptions
  121. class MarkdownError(Exception):
  122. pass
  123. #---- public api
  124. def markdown_path(path, encoding="utf-8",
  125. html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
  126. safe_mode=None, extras=None, link_patterns=None,
  127. use_file_vars=False):
  128. fp = codecs.open(path, 'r', encoding)
  129. text = fp.read()
  130. fp.close()
  131. return Markdown(html4tags=html4tags, tab_width=tab_width,
  132. safe_mode=safe_mode, extras=extras,
  133. link_patterns=link_patterns,
  134. use_file_vars=use_file_vars).convert(text)
  135. def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
  136. safe_mode=None, extras=None, link_patterns=None,
  137. use_file_vars=False):
  138. return Markdown(html4tags=html4tags, tab_width=tab_width,
  139. safe_mode=safe_mode, extras=extras,
  140. link_patterns=link_patterns,
  141. use_file_vars=use_file_vars).convert(text)
  142. class Markdown(object):
  143. # The dict of "extras" to enable in processing -- a mapping of
  144. # extra name to argument for the extra. Most extras do not have an
  145. # argument, in which case the value is None.
  146. #
  147. # This can be set via (a) subclassing and (b) the constructor
  148. # "extras" argument.
  149. extras = None
  150. urls = None
  151. titles = None
  152. html_blocks = None
  153. html_spans = None
  154. html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py
  155. # Used to track when we're inside an ordered or unordered list
  156. # (see _ProcessListItems() for details):
  157. list_level = 0
  158. _ws_only_line_re = re.compile(r"^[ \t]+$", re.M)
  159. def __init__(self, html4tags=False, tab_width=4, safe_mode=None,
  160. extras=None, link_patterns=None, use_file_vars=False):
  161. if html4tags:
  162. self.empty_element_suffix = ">"
  163. else:
  164. self.empty_element_suffix = " />"
  165. self.tab_width = tab_width
  166. # For compatibility with earlier markdown2.py and with
  167. # markdown.py's safe_mode being a boolean,
  168. # safe_mode == True -> "replace"
  169. if safe_mode is True:
  170. self.safe_mode = "replace"
  171. else:
  172. self.safe_mode = safe_mode
  173. # Massaging and building the "extras" info.
  174. if self.extras is None:
  175. self.extras = {}
  176. elif not isinstance(self.extras, dict):
  177. self.extras = dict([(e, None) for e in self.extras])
  178. if extras:
  179. if not isinstance(extras, dict):
  180. extras = dict([(e, None) for e in extras])
  181. self.extras.update(extras)
  182. assert isinstance(self.extras, dict)
  183. if "toc" in self.extras and not "header-ids" in self.extras:
  184. self.extras["header-ids"] = None # "toc" implies "header-ids"
  185. self._instance_extras = self.extras.copy()
  186. self.link_patterns = link_patterns
  187. self.use_file_vars = use_file_vars
  188. self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M)
  189. self._escape_table = g_escape_table.copy()
  190. if "smarty-pants" in self.extras:
  191. self._escape_table['"'] = _hash_text('"')
  192. self._escape_table["'"] = _hash_text("'")
  193. def reset(self):
  194. self.urls = {}
  195. self.titles = {}
  196. self.html_blocks = {}
  197. self.html_spans = {}
  198. self.list_level = 0
  199. self.extras = self._instance_extras.copy()
  200. if "footnotes" in self.extras:
  201. self.footnotes = {}
  202. self.footnote_ids = []
  203. if "header-ids" in self.extras:
  204. self._count_from_header_id = {} # no `defaultdict` in Python 2.4
  205. if "metadata" in self.extras:
  206. self.metadata = {}
  207. # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel"
  208. # should only be used in <a> tags with an "href" attribute.
  209. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE)
  210. def convert(self, text):
  211. """Convert the given text."""
  212. # Main function. The order in which other subs are called here is
  213. # essential. Link and image substitutions need to happen before
  214. # _EscapeSpecialChars(), so that any *'s or _'s in the <a>
  215. # and <img> tags get encoded.
  216. # Clear the global hashes. If we don't clear these, you get conflicts
  217. # from other articles when generating a page which contains more than
  218. # one article (e.g. an index page that shows the N most recent
  219. # articles):
  220. self.reset()
  221. if not isinstance(text, unicode):
  222. #TODO: perhaps shouldn't presume UTF-8 for string input?
  223. text = unicode(text, 'utf-8')
  224. if self.use_file_vars:
  225. # Look for emacs-style file variable hints.
  226. emacs_vars = self._get_emacs_vars(text)
  227. if "markdown-extras" in emacs_vars:
  228. splitter = re.compile("[ ,]+")
  229. for e in splitter.split(emacs_vars["markdown-extras"]):
  230. if '=' in e:
  231. ename, earg = e.split('=', 1)
  232. try:
  233. earg = int(earg)
  234. except ValueError:
  235. pass
  236. else:
  237. ename, earg = e, None
  238. self.extras[ename] = earg
  239. # Standardize line endings:
  240. text = re.sub("\r\n|\r", "\n", text)
  241. # Make sure $text ends with a couple of newlines:
  242. text += "\n\n"
  243. # Convert all tabs to spaces.
  244. text = self._detab(text)
  245. # Strip any lines consisting only of spaces and tabs.
  246. # This makes subsequent regexen easier to write, because we can
  247. # match consecutive blank lines with /\n+/ instead of something
  248. # contorted like /[ \t]*\n+/ .
  249. text = self._ws_only_line_re.sub("", text)
  250. # strip metadata from head and extract
  251. if "metadata" in self.extras:
  252. text = self._extract_metadata(text)
  253. text = self.preprocess(text)
  254. if self.safe_mode:
  255. text = self._hash_html_spans(text)
  256. # Turn block-level HTML blocks into hash entries
  257. text = self._hash_html_blocks(text, raw=True)
  258. # Strip link definitions, store in hashes.
  259. if "footnotes" in self.extras:
  260. # Must do footnotes first because an unlucky footnote defn
  261. # looks like a link defn:
  262. # [^4]: this "looks like a link defn"
  263. text = self._strip_footnote_definitions(text)
  264. text = self._strip_link_definitions(text)
  265. text = self._run_block_gamut(text)
  266. if "footnotes" in self.extras:
  267. text = self._add_footnotes(text)
  268. text = self.postprocess(text)
  269. text = self._unescape_special_chars(text)
  270. if self.safe_mode:
  271. text = self._unhash_html_spans(text)
  272. if "nofollow" in self.extras:
  273. text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text)
  274. text += "\n"
  275. rv = UnicodeWithAttrs(text)
  276. if "toc" in self.extras:
  277. rv._toc = self._toc
  278. if "metadata" in self.extras:
  279. rv.metadata = self.metadata
  280. return rv
  281. def postprocess(self, text):
  282. """A hook for subclasses to do some postprocessing of the html, if
  283. desired. This is called before unescaping of special chars and
  284. unhashing of raw HTML spans.
  285. """
  286. return text
  287. def preprocess(self, text):
  288. """A hook for subclasses to do some preprocessing of the Markdown, if
  289. desired. This is called after basic formatting of the text, but prior
  290. to any extras, safe mode, etc. processing.
  291. """
  292. return text
  293. # Is metadata if the content starts with '---'-fenced `key: value`
  294. # pairs. E.g. (indented for presentation):
  295. # ---
  296. # foo: bar
  297. # another-var: blah blah
  298. # ---
  299. _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""")
  300. def _extract_metadata(self, text):
  301. # fast test
  302. if not text.startswith("---"):
  303. return text
  304. match = self._metadata_pat.match(text)
  305. if not match:
  306. return text
  307. tail = text[len(match.group(0)):]
  308. metadata_str = match.group(1).strip()
  309. for line in metadata_str.split('\n'):
  310. key, value = line.split(':', 1)
  311. self.metadata[key.strip()] = value.strip()
  312. return tail
  313. _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE)
  314. # This regular expression is intended to match blocks like this:
  315. # PREFIX Local Variables: SUFFIX
  316. # PREFIX mode: Tcl SUFFIX
  317. # PREFIX End: SUFFIX
  318. # Some notes:
  319. # - "[ \t]" is used instead of "\s" to specifically exclude newlines
  320. # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does
  321. # not like anything other than Unix-style line terminators.
  322. _emacs_local_vars_pat = re.compile(r"""^
  323. (?P<prefix>(?:[^\r\n|\n|\r])*?)
  324. [\ \t]*Local\ Variables:[\ \t]*
  325. (?P<suffix>.*?)(?:\r\n|\n|\r)
  326. (?P<content>.*?\1End:)
  327. """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)
  328. def _get_emacs_vars(self, text):
  329. """Return a dictionary of emacs-style local variables.
  330. Parsing is done loosely according to this spec (and according to
  331. some in-practice deviations from this):
  332. http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables
  333. """
  334. emacs_vars = {}
  335. SIZE = pow(2, 13) # 8kB
  336. # Search near the start for a '-*-'-style one-liner of variables.
  337. head = text[:SIZE]
  338. if "-*-" in head:
  339. match = self._emacs_oneliner_vars_pat.search(head)
  340. if match:
  341. emacs_vars_str = match.group(1)
  342. assert '\n' not in emacs_vars_str
  343. emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';')
  344. if s.strip()]
  345. if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]:
  346. # While not in the spec, this form is allowed by emacs:
  347. # -*- Tcl -*-
  348. # where the implied "variable" is "mode". This form
  349. # is only allowed if there are no other variables.
  350. emacs_vars["mode"] = emacs_var_strs[0].strip()
  351. else:
  352. for emacs_var_str in emacs_var_strs:
  353. try:
  354. variable, value = emacs_var_str.strip().split(':', 1)
  355. except ValueError:
  356. log.debug("emacs variables error: malformed -*- "
  357. "line: %r", emacs_var_str)
  358. continue
  359. # Lowercase the variable name because Emacs allows "Mode"
  360. # or "mode" or "MoDe", etc.
  361. emacs_vars[variable.lower()] = value.strip()
  362. tail = text[-SIZE:]
  363. if "Local Variables" in tail:
  364. match = self._emacs_local_vars_pat.search(tail)
  365. if match:
  366. prefix = match.group("prefix")
  367. suffix = match.group("suffix")
  368. lines = match.group("content").splitlines(0)
  369. #print "prefix=%r, suffix=%r, content=%r, lines: %s"\
  370. # % (prefix, suffix, match.group("content"), lines)
  371. # Validate the Local Variables block: proper prefix and suffix
  372. # usage.
  373. for i, line in enumerate(lines):
  374. if not line.startswith(prefix):
  375. log.debug("emacs variables error: line '%s' "
  376. "does not use proper prefix '%s'"
  377. % (line, prefix))
  378. return {}
  379. # Don't validate suffix on last line. Emacs doesn't care,
  380. # neither should we.
  381. if i != len(lines)-1 and not line.endswith(suffix):
  382. log.debug("emacs variables error: line '%s' "
  383. "does not use proper suffix '%s'"
  384. % (line, suffix))
  385. return {}
  386. # Parse out one emacs var per line.
  387. continued_for = None
  388. for line in lines[:-1]: # no var on the last line ("PREFIX End:")
  389. if prefix: line = line[len(prefix):] # strip prefix
  390. if suffix: line = line[:-len(suffix)] # strip suffix
  391. line = line.strip()
  392. if continued_for:
  393. variable = continued_for
  394. if line.endswith('\\'):
  395. line = line[:-1].rstrip()
  396. else:
  397. continued_for = None
  398. emacs_vars[variable] += ' ' + line
  399. else:
  400. try:
  401. variable, value = line.split(':', 1)
  402. except ValueError:
  403. log.debug("local variables error: missing colon "
  404. "in local variables entry: '%s'" % line)
  405. continue
  406. # Do NOT lowercase the variable name, because Emacs only
  407. # allows "mode" (and not "Mode", "MoDe", etc.) in this block.
  408. value = value.strip()
  409. if value.endswith('\\'):
  410. value = value[:-1].rstrip()
  411. continued_for = variable
  412. else:
  413. continued_for = None
  414. emacs_vars[variable] = value
  415. # Unquote values.
  416. for var, val in list(emacs_vars.items()):
  417. if len(val) > 1 and (val.startswith('"') and val.endswith('"')
  418. or val.startswith('"') and val.endswith('"')):
  419. emacs_vars[var] = val[1:-1]
  420. return emacs_vars
  421. # Cribbed from a post by Bart Lateur:
  422. # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154>
  423. _detab_re = re.compile(r'(.*?)\t', re.M)
  424. def _detab_sub(self, match):
  425. g1 = match.group(1)
  426. return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width))
  427. def _detab(self, text):
  428. r"""Remove (leading?) tabs from a file.
  429. >>> m = Markdown()
  430. >>> m._detab("\tfoo")
  431. ' foo'
  432. >>> m._detab(" \tfoo")
  433. ' foo'
  434. >>> m._detab("\t foo")
  435. ' foo'
  436. >>> m._detab(" foo")
  437. ' foo'
  438. >>> m._detab(" foo\n\tbar\tblam")
  439. ' foo\n bar blam'
  440. """
  441. if '\t' not in text:
  442. return text
  443. return self._detab_re.subn(self._detab_sub, text)[0]
  444. # I broke out the html5 tags here and add them to _block_tags_a and
  445. # _block_tags_b. This way html5 tags are easy to keep track of.
  446. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption'
  447. _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del'
  448. _block_tags_a += _html5tags
  449. _strict_tag_block_re = re.compile(r"""
  450. ( # save in \1
  451. ^ # start of line (with re.M)
  452. <(%s) # start tag = \2
  453. \b # word break
  454. (.*\n)*? # any number of lines, minimally matching
  455. </\2> # the matching end tag
  456. [ \t]* # trailing spaces/tabs
  457. (?=\n+|\Z) # followed by a newline or end of document
  458. )
  459. """ % _block_tags_a,
  460. re.X | re.M)
  461. _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math'
  462. _block_tags_b += _html5tags
  463. _liberal_tag_block_re = re.compile(r"""
  464. ( # save in \1
  465. ^ # start of line (with re.M)
  466. <(%s) # start tag = \2
  467. \b # word break
  468. (.*\n)*? # any number of lines, minimally matching
  469. .*</\2> # the matching end tag
  470. [ \t]* # trailing spaces/tabs
  471. (?=\n+|\Z) # followed by a newline or end of document
  472. )
  473. """ % _block_tags_b,
  474. re.X | re.M)
  475. _html_markdown_attr_re = re.compile(
  476. r'''\s+markdown=("1"|'1')''')
  477. def _hash_html_block_sub(self, match, raw=False):
  478. html = match.group(1)
  479. if raw and self.safe_mode:
  480. html = self._sanitize_html(html)
  481. elif 'markdown-in-html' in self.extras and 'markdown=' in html:
  482. first_line = html.split('\n', 1)[0]
  483. m = self._html_markdown_attr_re.search(first_line)
  484. if m:
  485. lines = html.split('\n')
  486. middle = '\n'.join(lines[1:-1])
  487. last_line = lines[-1]
  488. first_line = first_line[:m.start()] + first_line[m.end():]
  489. f_key = _hash_text(first_line)
  490. self.html_blocks[f_key] = first_line
  491. l_key = _hash_text(last_line)
  492. self.html_blocks[l_key] = last_line
  493. return ''.join(["\n\n", f_key,
  494. "\n\n", middle, "\n\n",
  495. l_key, "\n\n"])
  496. key = _hash_text(html)
  497. self.html_blocks[key] = html
  498. return "\n\n" + key + "\n\n"
  499. def _hash_html_blocks(self, text, raw=False):
  500. """Hashify HTML blocks
  501. We only want to do this for block-level HTML tags, such as headers,
  502. lists, and tables. That's because we still want to wrap <p>s around
  503. "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  504. phrase emphasis, and spans. The list of tags we're looking for is
  505. hard-coded.
  506. @param raw {boolean} indicates if these are raw HTML blocks in
  507. the original source. It makes a difference in "safe" mode.
  508. """
  509. if '<' not in text:
  510. return text
  511. # Pass `raw` value into our calls to self._hash_html_block_sub.
  512. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw)
  513. # First, look for nested blocks, e.g.:
  514. # <div>
  515. # <div>
  516. # tags for inner block must be indented.
  517. # </div>
  518. # </div>
  519. #
  520. # The outermost tags must start at the left margin for this to match, and
  521. # the inner nested divs must be indented.
  522. # We need to do this before the next, more liberal match, because the next
  523. # match will start at the first `<div>` and stop at the first `</div>`.
  524. text = self._strict_tag_block_re.sub(hash_html_block_sub, text)
  525. # Now match more liberally, simply from `\n<tag>` to `</tag>\n`
  526. text = self._liberal_tag_block_re.sub(hash_html_block_sub, text)
  527. # Special case just for <hr />. It was easier to make a special
  528. # case than to make the other regex more complicated.
  529. if "<hr" in text:
  530. _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width)
  531. text = _hr_tag_re.sub(hash_html_block_sub, text)
  532. # Special case for standalone HTML comments:
  533. if "<!--" in text:
  534. start = 0
  535. while True:
  536. # Delimiters for next comment block.
  537. try:
  538. start_idx = text.index("<!--", start)
  539. except ValueError:
  540. break
  541. try:
  542. end_idx = text.index("-->", start_idx) + 3
  543. except ValueError:
  544. break
  545. # Start position for next comment block search.
  546. start = end_idx
  547. # Validate whitespace before comment.
  548. if start_idx:
  549. # - Up to `tab_width - 1` spaces before start_idx.
  550. for i in range(self.tab_width - 1):
  551. if text[start_idx - 1] != ' ':
  552. break
  553. start_idx -= 1
  554. if start_idx == 0:
  555. break
  556. # - Must be preceded by 2 newlines or hit the start of
  557. # the document.
  558. if start_idx == 0:
  559. pass
  560. elif start_idx == 1 and text[0] == '\n':
  561. start_idx = 0 # to match minute detail of Markdown.pl regex
  562. elif text[start_idx-2:start_idx] == '\n\n':
  563. pass
  564. else:
  565. break
  566. # Validate whitespace after comment.
  567. # - Any number of spaces and tabs.
  568. while end_idx < len(text):
  569. if text[end_idx] not in ' \t':
  570. break
  571. end_idx += 1
  572. # - Must be following by 2 newlines or hit end of text.
  573. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'):
  574. continue
  575. # Escape and hash (must match `_hash_html_block_sub`).
  576. html = text[start_idx:end_idx]
  577. if raw and self.safe_mode:
  578. html = self._sanitize_html(html)
  579. key = _hash_text(html)
  580. self.html_blocks[key] = html
  581. text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:]
  582. if "xml" in self.extras:
  583. # Treat XML processing instructions and namespaced one-liner
  584. # tags as if they were block HTML tags. E.g., if standalone
  585. # (i.e. are their own paragraph), the following do not get
  586. # wrapped in a <p> tag:
  587. # <?foo bar?>
  588. #
  589. # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/>
  590. _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width)
  591. text = _xml_oneliner_re.sub(hash_html_block_sub, text)
  592. return text
  593. def _strip_link_definitions(self, text):
  594. # Strips link definitions from text, stores the URLs and titles in
  595. # hash references.
  596. less_than_tab = self.tab_width - 1
  597. # Link defs are in the form:
  598. # [id]: url "optional title"
  599. _link_def_re = re.compile(r"""
  600. ^[ ]{0,%d}\[(.+)\]: # id = \1
  601. [ \t]*
  602. \n? # maybe *one* newline
  603. [ \t]*
  604. <?(.+?)>? # url = \2
  605. [ \t]*
  606. (?:
  607. \n? # maybe one newline
  608. [ \t]*
  609. (?<=\s) # lookbehind for whitespace
  610. ['"(]
  611. ([^\n]*) # title = \3
  612. ['")]
  613. [ \t]*
  614. )? # title is optional
  615. (?:\n+|\Z)
  616. """ % less_than_tab, re.X | re.M | re.U)
  617. return _link_def_re.sub(self._extract_link_def_sub, text)
  618. def _extract_link_def_sub(self, match):
  619. id, url, title = match.groups()
  620. key = id.lower() # Link IDs are case-insensitive
  621. self.urls[key] = self._encode_amps_and_angles(url)
  622. if title:
  623. self.titles[key] = title
  624. return ""
  625. def _extract_footnote_def_sub(self, match):
  626. id, text = match.groups()
  627. text = _dedent(text, skip_first_line=not text.startswith('\n')).strip()
  628. normed_id = re.sub(r'\W', '-', id)
  629. # Ensure footnote text ends with a couple newlines (for some
  630. # block gamut matches).
  631. self.footnotes[normed_id] = text + "\n\n"
  632. return ""
  633. def _strip_footnote_definitions(self, text):
  634. """A footnote definition looks like this:
  635. [^note-id]: Text of the note.
  636. May include one or more indented paragraphs.
  637. Where,
  638. - The 'note-id' can be pretty much anything, though typically it
  639. is the number of the footnote.
  640. - The first paragraph may start on the next line, like so:
  641. [^note-id]:
  642. Text of the note.
  643. """
  644. less_than_tab = self.tab_width - 1
  645. footnote_def_re = re.compile(r'''
  646. ^[ ]{0,%d}\[\^(.+)\]: # id = \1
  647. [ \t]*
  648. ( # footnote text = \2
  649. # First line need not start with the spaces.
  650. (?:\s*.*\n+)
  651. (?:
  652. (?:[ ]{%d} | \t) # Subsequent lines must be indented.
  653. .*\n+
  654. )*
  655. )
  656. # Lookahead for non-space at line-start, or end of doc.
  657. (?:(?=^[ ]{0,%d}\S)|\Z)
  658. ''' % (less_than_tab, self.tab_width, self.tab_width),
  659. re.X | re.M)
  660. return footnote_def_re.sub(self._extract_footnote_def_sub, text)
  661. _hr_data = [
  662. ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)),
  663. ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)),
  664. ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)),
  665. ]
  666. def _run_block_gamut(self, text):
  667. # These are all the transformations that form block-level
  668. # tags like paragraphs, headers, and list items.
  669. if "fenced-code-blocks" in self.extras:
  670. text = self._do_fenced_code_blocks(text)
  671. text = self._do_headers(text)
  672. # Do Horizontal Rules:
  673. # On the number of spaces in horizontal rules: The spec is fuzzy: "If
  674. # you wish, you may use spaces between the hyphens or asterisks."
  675. # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the
  676. # hr chars to one or two. We'll reproduce that limit here.
  677. hr = "\n<hr"+self.empty_element_suffix+"\n"
  678. for ch, regex in self._hr_data:
  679. if ch in text:
  680. for m in reversed(list(regex.finditer(text))):
  681. tail = m.group(1).rstrip()
  682. if not tail.strip(ch + ' ') and tail.count(" ") == 0:
  683. start, end = m.span()
  684. text = text[:start] + hr + text[end:]
  685. text = self._do_lists(text)
  686. if "pyshell" in self.extras:
  687. text = self._prepare_pyshell_blocks(text)
  688. if "wiki-tables" in self.extras:
  689. text = self._do_wiki_tables(text)
  690. text = self._do_code_blocks(text)
  691. text = self._do_block_quotes(text)
  692. # We already ran _HashHTMLBlocks() before, in Markdown(), but that
  693. # was to escape raw HTML in the original Markdown source. This time,
  694. # we're escaping the markup we've just created, so that we don't wrap
  695. # <p> tags around block-level tags.
  696. text = self._hash_html_blocks(text)
  697. text = self._form_paragraphs(text)
  698. return text
  699. def _pyshell_block_sub(self, match):
  700. lines = match.group(0).splitlines(0)
  701. _dedentlines(lines)
  702. indent = ' ' * self.tab_width
  703. s = ('\n' # separate from possible cuddled paragraph
  704. + indent + ('\n'+indent).join(lines)
  705. + '\n\n')
  706. return s
  707. def _prepare_pyshell_blocks(self, text):
  708. """Ensure that Python interactive shell sessions are put in
  709. code blocks -- even if not properly indented.
  710. """
  711. if ">>>" not in text:
  712. return text
  713. less_than_tab = self.tab_width - 1
  714. _pyshell_block_re = re.compile(r"""
  715. ^([ ]{0,%d})>>>[ ].*\n # first line
  716. ^(\1.*\S+.*\n)* # any number of subsequent lines
  717. ^\n # ends with a blank line
  718. """ % less_than_tab, re.M | re.X)
  719. return _pyshell_block_re.sub(self._pyshell_block_sub, text)
  720. def _wiki_table_sub(self, match):
  721. ttext = match.group(0).strip()
  722. #print 'wiki table: %r' % match.group(0)
  723. rows = []
  724. for line in ttext.splitlines(0):
  725. line = line.strip()[2:-2].strip()
  726. row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)]
  727. rows.append(row)
  728. #pprint(rows)
  729. hlines = ['<table>', '<tbody>']
  730. for row in rows:
  731. hrow = ['<tr>']
  732. for cell in row:
  733. hrow.append('<td>')
  734. hrow.append(self._run_span_gamut(cell))
  735. hrow.append('</td>')
  736. hrow.append('</tr>')
  737. hlines.append(''.join(hrow))
  738. hlines += ['</tbody>', '</table>']
  739. return '\n'.join(hlines) + '\n'
  740. def _do_wiki_tables(self, text):
  741. # Optimization.
  742. if "||" not in text:
  743. return text
  744. less_than_tab = self.tab_width - 1
  745. wiki_table_re = re.compile(r'''
  746. (?:(?<=\n\n)|\A\n?) # leading blank line
  747. ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line
  748. (^\1\|\|.+?\|\|\n)* # any number of subsequent lines
  749. ''' % less_than_tab, re.M | re.X)
  750. return wiki_table_re.sub(self._wiki_table_sub, text)
  751. def _run_span_gamut(self, text):
  752. # These are all the transformations that occur *within* block-level
  753. # tags like paragraphs, headers, and list items.
  754. text = self._do_code_spans(text)
  755. text = self._escape_special_chars(text)
  756. # Process anchor and image tags.
  757. text = self._do_links(text)
  758. # Make links out of things like `<http://example.com/>`
  759. # Must come after _do_links(), because you can use < and >
  760. # delimiters in inline links like [this](<url>).
  761. text = self._do_auto_links(text)
  762. if "link-patterns" in self.extras:
  763. text = self._do_link_patterns(text)
  764. text = self._encode_amps_and_angles(text)
  765. text = self._do_italics_and_bold(text)
  766. if "smarty-pants" in self.extras:
  767. text = self._do_smart_punctuation(text)
  768. # Do hard breaks:
  769. text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text)
  770. return text
  771. # "Sorta" because auto-links are identified as "tag" tokens.
  772. _sorta_html_tokenize_re = re.compile(r"""
  773. (
  774. # tag
  775. </?
  776. (?:\w+) # tag name
  777. (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes
  778. \s*/?>
  779. |
  780. # auto-link (e.g., <http://www.activestate.com/>)
  781. <\w+[^>]*>
  782. |
  783. <!--.*?--> # comment
  784. |
  785. <\?.*?\?> # processing instruction
  786. )
  787. """, re.X)
  788. def _escape_special_chars(self, text):
  789. # Python markdown note: the HTML tokenization here differs from
  790. # that in Markdown.pl, hence the behaviour for subtle cases can
  791. # differ (I believe the tokenizer here does a better job because
  792. # it isn't susceptible to unmatched '<' and '>' in HTML tags).
  793. # Note, however, that '>' is not allowed in an auto-link URL
  794. # here.
  795. escaped = []
  796. is_html_markup = False
  797. for token in self._sorta_html_tokenize_re.split(text):
  798. if is_html_markup:
  799. # Within tags/HTML-comments/auto-links, encode * and _
  800. # so they don't conflict with their use in Markdown for
  801. # italics and strong. We're replacing each such
  802. # character with its corresponding MD5 checksum value;
  803. # this is likely overkill, but it should prevent us from
  804. # colliding with the escape values by accident.
  805. escaped.append(token.replace('*', self._escape_table['*'])
  806. .replace('_', self._escape_table['_']))
  807. else:
  808. escaped.append(self._encode_backslash_escapes(token))
  809. is_html_markup = not is_html_markup
  810. return ''.join(escaped)
  811. def _hash_html_spans(self, text):
  812. # Used for safe_mode.
  813. def _is_auto_link(s):
  814. if ':' in s and self._auto_link_re.match(s):
  815. return True
  816. elif '@' in s and self._auto_email_link_re.match(s):
  817. return True
  818. return False
  819. tokens = []
  820. is_html_markup = False
  821. for token in self._sorta_html_tokenize_re.split(text):
  822. if is_html_markup and not _is_auto_link(token):
  823. sanitized = self._sanitize_html(token)
  824. key = _hash_text(sanitized)
  825. self.html_spans[key] = sanitized
  826. tokens.append(key)
  827. else:
  828. tokens.append(token)
  829. is_html_markup = not is_html_markup
  830. return ''.join(tokens)
  831. def _unhash_html_spans(self, text):
  832. for key, sanitized in list(self.html_spans.items()):
  833. text = text.replace(key, sanitized)
  834. return text
  835. def _sanitize_html(self, s):
  836. if self.safe_mode == "replace":
  837. return self.html_removed_text
  838. elif self.safe_mode == "escape":
  839. replacements = [
  840. ('&', '&amp;'),
  841. ('<', '&lt;'),
  842. ('>', '&gt;'),
  843. ]
  844. for before, after in replacements:
  845. s = s.replace(before, after)
  846. return s
  847. else:
  848. raise MarkdownError("invalid value for 'safe_mode': %r (must be "
  849. "'escape' or 'replace')" % self.safe_mode)
  850. _tail_of_inline_link_re = re.compile(r'''
  851. # Match tail of: [text](/url/) or [text](/url/ "title")
  852. \( # literal paren
  853. [ \t]*
  854. (?P<url> # \1
  855. <.*?>
  856. |
  857. .*?
  858. )
  859. [ \t]*
  860. ( # \2
  861. (['"]) # quote char = \3
  862. (?P<title>.*?)
  863. \3 # matching quote
  864. )? # title is optional
  865. \)
  866. ''', re.X | re.S)
  867. _tail_of_reference_link_re = re.compile(r'''
  868. # Match tail of: [text][id]
  869. [ ]? # one optional space
  870. (?:\n[ ]*)? # one optional newline followed by spaces
  871. \[
  872. (?P<id>.*?)
  873. \]
  874. ''', re.X | re.S)
  875. def _do_links(self, text):
  876. """Turn Markdown link shortcuts into XHTML <a> and <img> tags.
  877. This is a combination of Markdown.pl's _DoAnchors() and
  878. _DoImages(). They are done together because that simplified the
  879. approach. It was necessary to use a different approach than
  880. Markdown.pl because of the lack of atomic matching support in
  881. Python's regex engine used in $g_nested_brackets.
  882. """
  883. MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24
  884. # `anchor_allowed_pos` is used to support img links inside
  885. # anchors, but not anchors inside anchors. An anchor's start
  886. # pos must be `>= anchor_allowed_pos`.
  887. anchor_allowed_pos = 0
  888. curr_pos = 0
  889. while True: # Handle the next link.
  890. # The next '[' is the start of:
  891. # - an inline anchor: [text](url "title")
  892. # - a reference anchor: [text][id]
  893. # - an inline img: ![text](url "title")
  894. # - a reference img: ![text][id]
  895. # - a footnote ref: [^id]
  896. # (Only if 'footnotes' extra enabled)
  897. # - a footnote defn: [^id]: ...
  898. # (Only if 'footnotes' extra enabled) These have already
  899. # been stripped in _strip_footnote_definitions() so no
  900. # need to watch for them.
  901. # - a link definition: [id]: url "title"
  902. # These have already been stripped in
  903. # _strip_link_definitions() so no need to watch for them.
  904. # - not markup: [...anything else...
  905. try:
  906. start_idx = text.index('[', curr_pos)
  907. except ValueError:
  908. break
  909. text_length = len(text)
  910. # Find the matching closing ']'.
  911. # Markdown.pl allows *matching* brackets in link text so we
  912. # will here too. Markdown.pl *doesn't* currently allow
  913. # matching brackets in img alt text -- we'll differ in that
  914. # regard.
  915. bracket_depth = 0
  916. for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL,
  917. text_length)):
  918. ch = text[p]
  919. if ch == ']':
  920. bracket_depth -= 1
  921. if bracket_depth < 0:
  922. break
  923. elif ch == '[':
  924. bracket_depth += 1
  925. else:
  926. # Closing bracket not found within sentinel length.
  927. # This isn't markup.
  928. curr_pos = start_idx + 1
  929. continue
  930. link_text = text[start_idx+1:p]
  931. # Possibly a footnote ref?
  932. if "footnotes" in self.extras and link_text.startswith("^"):
  933. normed_id = re.sub(r'\W', '-', link_text[1:])
  934. if normed_id in self.footnotes:
  935. self.footnote_ids.append(normed_id)
  936. result = '<sup class="footnote-ref" id="fnref-%s">' \
  937. '<a href="#fn-%s">%s</a></sup>' \
  938. % (normed_id, normed_id, len(self.footnote_ids))
  939. text = text[:start_idx] + result + text[p+1:]
  940. else:
  941. # This id isn't defined, leave the markup alone.
  942. curr_pos = p+1
  943. continue
  944. # Now determine what this is by the remainder.
  945. p += 1
  946. if p == text_length:
  947. return text
  948. # Inline anchor or img?
  949. if text[p] == '(': # attempt at perf improvement
  950. match = self._tail_of_inline_link_re.match(text, p)
  951. if match:
  952. # Handle an inline anchor or img.
  953. is_img = start_idx > 0 and text[start_idx-1] == "!"
  954. if is_img:
  955. start_idx -= 1
  956. url, title = match.group("url"), match.group("title")
  957. if url and url[0] == '<':
  958. url = url[1:-1] # '<url>' -> 'url'
  959. # We've got to encode these to avoid conflicting
  960. # with italics/bold.
  961. url = url.replace('*', self._escape_table['*']) \
  962. .replace('_', self._escape_table['_'])
  963. if title:
  964. title_str = ' title="%s"' % (
  965. _xml_escape_attr(title)
  966. .replace('*', self._escape_table['*'])
  967. .replace('_', self._escape_table['_']))
  968. else:
  969. title_str = ''
  970. if is_img:
  971. result = '<img src="%s" alt="%s"%s%s' \
  972. % (url.replace('"', '&quot;'),
  973. _xml_escape_attr(link_text),
  974. title_str, self.empty_element_suffix)
  975. if "smarty-pants" in self.extras:
  976. result = result.replace('"', self._escape_table['"'])
  977. curr_pos = start_idx + len(result)
  978. text = text[:start_idx] + result + text[match.end():]
  979. elif start_idx >= anchor_allowed_pos:
  980. result_head = '<a href="%s"%s>' % (url, title_str)
  981. result = '%s%s</a>' % (result_head, link_text)
  982. if "smarty-pants" in self.extras:
  983. result = result.replace('"', self._escape_table['"'])
  984. # <img> allowed from curr_pos on, <a> from
  985. # anchor_allowed_pos on.
  986. curr_pos = start_idx + len(result_head)
  987. anchor_allowed_pos = start_idx + len(result)
  988. text = text[:start_idx] + result + text[match.end():]
  989. else:
  990. # Anchor not allowed here.
  991. curr_pos = start_idx + 1
  992. continue
  993. # Reference anchor or img?
  994. else:
  995. match = self._tail_of_reference_link_re.match(text, p)
  996. if match:
  997. # Handle a reference-style anchor or img.
  998. is_img = start_idx > 0 and text[start_idx-1] == "!"
  999. if is_img:
  1000. start_idx -= 1
  1001. link_id = match.group("id").lower()
  1002. if not link_id:
  1003. link_id = link_text.lower() # for links like [this][]
  1004. if link_id in self.urls:
  1005. url = self.urls[link_id]
  1006. # We've got to encode these to avoid conflicting
  1007. # with italics/bold.
  1008. url = url.replace('*', self._escape_table['*']) \
  1009. .replace('_', self._escape_table['_'])
  1010. title = self.titles.get(link_id)
  1011. if title:
  1012. before = title
  1013. title = _xml_escape_attr(title) \
  1014. .replace('*', self._escape_table['*']) \
  1015. .replace('_', self._escape_table['_'])
  1016. title_str = ' title="%s"' % title
  1017. else:
  1018. title_str = ''
  1019. if is_img:
  1020. result = '<img src="%s" alt="%s"%s%s' \
  1021. % (url.replace('"', '&quot;'),
  1022. link_text.replace('"', '&quot;'),
  1023. title_str, self.empty_element_suffix)
  1024. if "smarty-pants" in self.extras:
  1025. result = result.replace('"', self._escape_table['"'])
  1026. curr_pos = start_idx + len(result)
  1027. text = text[:start_idx] + result + text[match.end():]
  1028. elif start_idx >= anchor_allowed_pos:
  1029. result = '<a href="%s"%s>%s</a>' \
  1030. % (url, title_str, link_text)
  1031. result_head = '<a href="%s"%s>' % (url, title_str)
  1032. result = '%s%s</a>' % (result_head, link_text)
  1033. if "smarty-pants" in self.extras:
  1034. result = result.replace('"', self._escape_table['"'])
  1035. # <img> allowed from curr_pos on, <a> from
  1036. # anchor_allowed_pos on.
  1037. curr_pos = start_idx + len(result_head)
  1038. anchor_allowed_pos = start_idx + len(result)
  1039. text = text[:start_idx] + result + text[match.end():]
  1040. else:
  1041. # Anchor not allowed here.
  1042. curr_pos = start_idx + 1
  1043. else:
  1044. # This id isn't defined, leave the markup alone.
  1045. curr_pos = match.end()
  1046. continue
  1047. # Otherwise, it isn't markup.
  1048. curr_pos = start_idx + 1
  1049. return text
  1050. def header_id_from_text(self, text, prefix, n):
  1051. """Generate a header id attribute value from the given header
  1052. HTML content.
  1053. This is only called if the "header-ids" extra is enabled.
  1054. Subclasses may override this for different header ids.
  1055. @param text {str} The text of the header tag
  1056. @param prefix {str} The requested prefix for header ids. This is the
  1057. value of the "header-ids" extra key, if any. Otherwise, None.
  1058. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag.
  1059. @returns {str} The value for the header tag's "id" attribute. Return
  1060. None to not have an id attribute and to exclude this header from
  1061. the TOC (if the "toc" extra is specified).
  1062. """
  1063. header_id = _slugify(text)
  1064. if prefix and isinstance(prefix, base_string_type):
  1065. header_id = prefix + '-' + header_id
  1066. if header_id in self._count_from_header_id:
  1067. self._count_from_header_id[header_id] += 1
  1068. header_id += '-%s' % self._count_from_header_id[header_id]
  1069. else:
  1070. self._count_from_header_id[header_id] = 1
  1071. return header_id
  1072. _toc = None
  1073. def _toc_add_entry(self, level, id, name):
  1074. if self._toc is None:
  1075. self._toc = []
  1076. self._toc.append((level, id, self._unescape_special_chars(name)))
  1077. _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M)
  1078. def _setext_h_sub(self, match):
  1079. n = {"=": 1, "-": 2}[match.group(2)[0]]
  1080. demote_headers = self.extras.get("demote-headers")
  1081. if demote_headers:
  1082. n = min(n + demote_headers, 6)
  1083. header_id_attr = ""
  1084. if "header-ids" in self.extras:
  1085. header_id = self.header_id_from_text(match.group(1),
  1086. self.extras["header-ids"], n)
  1087. if header_id:
  1088. header_id_attr = ' id="%s"' % header_id
  1089. html = self._run_span_gamut(match.group(1))
  1090. if "toc" in self.extras and header_id:
  1091. self._toc_add_entry(n, header_id, html)
  1092. return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n)
  1093. _atx_h_re = re.compile(r'''
  1094. ^(\#{1,6}) # \1 = string of #'s
  1095. [ \t]+
  1096. (.+?) # \2 = Header text
  1097. [ \t]*
  1098. (?<!\\) # ensure not an escaped trailing '#'
  1099. \#* # optional closing #'s (not counted)
  1100. \n+
  1101. ''', re.X | re.M)
  1102. def _atx_h_sub(self, match):
  1103. n = len(match.group(1))
  1104. demote_headers = self.extras.get("demote-headers")
  1105. if demote_headers:
  1106. n = min(n + demote_headers, 6)
  1107. header_id_attr = ""
  1108. if "header-ids" in self.extras:
  1109. header_id = self.header_id_from_text(match.group(2),
  1110. self.extras["header-ids"], n)
  1111. if header_id:
  1112. header_id_attr = ' id="%s"' % header_id
  1113. html = self._run_span_gamut(match.group(2))
  1114. if "toc" in self.extras and header_id:
  1115. self._toc_add_entry(n, header_id, html)
  1116. return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n)
  1117. def _do_headers(self, text):
  1118. # Setext-style headers:
  1119. # Header 1
  1120. # ========
  1121. #
  1122. # Header 2
  1123. # --------
  1124. text = self._setext_h_re.sub(self._setext_h_sub, text)
  1125. # atx-style headers:
  1126. # # Header 1
  1127. # ## Header 2
  1128. # ## Header 2 with closing hashes ##
  1129. # ...
  1130. # ###### Header 6
  1131. text = self._atx_h_re.sub(self._atx_h_sub, text)
  1132. return text
  1133. _marker_ul_chars = '*+-'
  1134. _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars
  1135. _marker_ul = '(?:[%s])' % _marker_ul_chars
  1136. _marker_ol = r'(?:\d+\.)'
  1137. def _list_sub(self, match):
  1138. lst = match.group(1)
  1139. lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol"
  1140. result = self._process_list_items(lst)
  1141. if self.list_level:
  1142. return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type)
  1143. else:
  1144. return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type)
  1145. def _do_lists(self, text):
  1146. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  1147. # Iterate over each *non-overlapping* list match.
  1148. pos = 0
  1149. while True:
  1150. # Find the *first* hit for either list style (ul or ol). We
  1151. # match ul and ol separately to avoid adjacent lists of different
  1152. # types running into each other (see issue #16).
  1153. hits = []
  1154. for marker_pat in (self._marker_ul, self._marker_ol):
  1155. less_than_tab = self.tab_width - 1
  1156. whole_list = r'''
  1157. ( # \1 = whole list
  1158. ( # \2
  1159. [ ]{0,%d}
  1160. (%s) # \3 = first list item marker
  1161. [ \t]+
  1162. (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case.
  1163. )
  1164. (?:.+?)
  1165. ( # \4
  1166. \Z
  1167. |
  1168. \n{2,}
  1169. (?=\S)
  1170. (?! # Negative lookahead for another list item marker
  1171. [ \t]*
  1172. %s[ \t]+
  1173. )
  1174. )
  1175. )
  1176. ''' % (less_than_tab, marker_pat, marker_pat)
  1177. if self.list_level: # sub-list
  1178. list_re = re.compile("^"+whole_list, re.X | re.M | re.S)
  1179. else:
  1180. list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list,
  1181. re.X | re.M | re.S)
  1182. match = list_re.search(text, pos)
  1183. if match:
  1184. hits.append((match.start(), match))
  1185. if not hits:
  1186. break
  1187. hits.sort()
  1188. match = hits[0][1]
  1189. start, end = match.span()
  1190. text = text[:start] + self._list_sub(match) + text[end:]
  1191. pos = end
  1192. return text
  1193. _list_item_re = re.compile(r'''
  1194. (\n)? # leading line = \1
  1195. (^[ \t]*) # leading whitespace = \2
  1196. (?P<marker>%s) [ \t]+ # list marker = \3
  1197. ((?:.+?) # list item text = \4
  1198. (\n{1,2})) # eols = \5
  1199. (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+))
  1200. ''' % (_marker_any, _marker_any),
  1201. re.M | re.X | re.S)
  1202. _last_li_endswith_two_eols = False
  1203. def _list_item_sub(self, match):
  1204. item = match.group(4)
  1205. leading_line = match.group(1)
  1206. leading_space = match.group(2)
  1207. if leading_line or "\n\n" in item or self._last_li_endswith_two_eols:
  1208. item = self._run_block_gamut(self._outdent(item))
  1209. else:
  1210. # Recursion for sub-lists:
  1211. item = self._do_lists(self._outdent(item))
  1212. if item.endswith('\n'):
  1213. item = item[:-1]
  1214. item = self._run_span_gamut(item)
  1215. self._last_li_endswith_two_eols = (len(match.group(5)) == 2)
  1216. return "<li>%s</li>\n" % item
  1217. def _process_list_items(self, list_str):
  1218. # Process the contents of a single ordered or unordered list,
  1219. # splitting it into individual list items.
  1220. # The $g_list_level global keeps track of when we're inside a list.
  1221. # Each time we enter a list, we increment it; when we leave a list,
  1222. # we decrement. If it's zero, we're not in a list anymore.
  1223. #
  1224. # We do this because when we're not inside a list, we want to treat
  1225. # something like this:
  1226. #
  1227. # I recommend upgrading to version
  1228. # 8. Oops, now this line is treated
  1229. # as a sub-list.
  1230. #
  1231. # As a single paragraph, despite the fact that the second line starts
  1232. # with a digit-period-space sequence.
  1233. #
  1234. # Whereas when we're inside a list (or sub-list), that line will be
  1235. # treated as the start of a sub-list. What a kludge, huh? This is
  1236. # an aspect of Markdown's syntax that's hard to parse perfectly
  1237. # without resorting to mind-reading. Perhaps the solution is to
  1238. # change the syntax rules such that sub-lists must start with a
  1239. # starting cardinal number; e.g. "1." or "a.".
  1240. self.list_level += 1
  1241. self._last_li_endswith_two_eols = False
  1242. list_str = list_str.rstrip('\n') + '\n'
  1243. list_str = self._list_item_re.sub(self._list_item_sub, list_str)
  1244. self.list_level -= 1
  1245. return list_str
  1246. def _get_pygments_lexer(self, lexer_name):
  1247. try:
  1248. from pygments import lexers, util
  1249. except ImportError:
  1250. return None
  1251. try:
  1252. return lexers.get_lexer_by_name(lexer_name)
  1253. except util.ClassNotFound:
  1254. return None
  1255. def _color_with_pygments(self, codeblock, lexer, **formatter_opts):
  1256. import pygments
  1257. import pygments.formatters
  1258. class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
  1259. def _wrap_code(self, inner):
  1260. """A function for use in a Pygments Formatter which
  1261. wraps in <code> tags.
  1262. """
  1263. yield 0, "<code>"
  1264. for tup in inner:
  1265. yield tup
  1266. yield 0, "</code>"
  1267. def wrap(self, source, outfile):
  1268. """Return the source with a code, pre, and div."""
  1269. return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
  1270. formatter_opts.setdefault("cssclass", "codehilite")
  1271. formatter = HtmlCodeFormatter(**formatter_opts)
  1272. return pygments.highlight(codeblock, lexer, formatter)
  1273. def _code_block_sub(self, match, is_fenced_code_block=False):
  1274. lexer_name = None
  1275. if is_fenced_code_block:
  1276. lexer_name = match.group(1)
  1277. if lexer_name:
  1278. formatter_opts = self.extras['fenced-code-blocks'] or {}
  1279. codeblock = match.group(2)
  1280. codeblock = codeblock[:-1] # drop one trailing newline
  1281. else:
  1282. codeblock = match.group(1)
  1283. codeblock = self._outdent(codeblock)
  1284. codeblock = self._detab(codeblock)
  1285. codeblock = codeblock.lstrip('\n') # trim leading newlines
  1286. codeblock = codeblock.rstrip() # trim trailing whitespace
  1287. # Note: "code-color" extra is DEPRECATED.
  1288. if "code-color" in self.extras and codeblock.startswith(":::"):
  1289. lexer_name, rest = codeblock.split('\n', 1)
  1290. lexer_name = lexer_name[3:].strip()
  1291. codeblock = rest.lstrip("\n") # Remove lexer declaration line.
  1292. formatter_opts = self.extras['code-color'] or {}
  1293. if lexer_name:
  1294. lexer = self._get_pygments_lexer(lexer_name)
  1295. if lexer:
  1296. colored = self._color_with_pygments(codeblock, lexer,
  1297. **formatter_opts)
  1298. return "\n\n%s\n\n" % colored
  1299. codeblock = self._encode_code(codeblock)
  1300. pre_class_str = self._html_class_str_from_tag("pre")
  1301. code_class_str = self._html_class_str_from_tag("code")
  1302. return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % (
  1303. pre_class_str, code_class_str, codeblock)
  1304. def _html_class_str_from_tag(self, tag):
  1305. """Get the appropriate ' class="..."' string (note the leading
  1306. space), if any, for the given tag.
  1307. """
  1308. if "html-classes" not in self.extras:
  1309. return ""
  1310. try:
  1311. html_classes_from_tag = self.extras["html-classes"]
  1312. except TypeError:
  1313. return ""
  1314. else:
  1315. if tag in html_classes_from_tag:
  1316. return ' class="%s"' % html_classes_from_tag[tag]
  1317. return ""
  1318. def _do_code_blocks(self, text):
  1319. """Process Markdown `<pre><code>` blocks."""
  1320. code_block_re = re.compile(r'''
  1321. (?:\n\n|\A\n?)
  1322. ( # $1 = the code block -- one or more lines, starting with a space/tab
  1323. (?:
  1324. (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces
  1325. .*\n+
  1326. )+
  1327. )
  1328. ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  1329. ''' % (self.tab_width, self.tab_width),
  1330. re.M | re.X)
  1331. return code_block_re.sub(self._code_block_sub, text)
  1332. _fenced_code_block_re = re.compile(r'''
  1333. (?:\n\n|\A\n?)
  1334. ^```([\w+-]+)?[ \t]*\n # opening fence, $1 = optional lang
  1335. (.*?) # $2 = code block content
  1336. ^```[ \t]*\n # closing fence
  1337. ''', re.M | re.X | re.S)
  1338. def _fenced_code_block_sub(self, match):
  1339. return self._code_block_sub(match, is_fenced_code_block=True);
  1340. def _do_fenced_code_blocks(self, text):
  1341. """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra)."""
  1342. return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text)
  1343. # Rules for a code span:
  1344. # - backslash escapes are not interpreted in a code span
  1345. # - to include one or or a run of more backticks the delimiters must
  1346. # be a longer run of backticks
  1347. # - cannot start or end a code span with a backtick; pad with a
  1348. # space and that space will be removed in the emitted HTML
  1349. # See `test/tm-cases/escapes.text` for a number of edge-case
  1350. # examples.
  1351. _code_span_re = re.compile(r'''
  1352. (?<!\\)
  1353. (`+) # \1 = Opening run of `
  1354. (?!`) # See Note A test/tm-cases/escapes.text
  1355. (.+?) # \2 = The code block
  1356. (?<!`)
  1357. \1 # Matching closer
  1358. (?!`)
  1359. ''', re.X | re.S)
  1360. def _code_span_sub(self, match):
  1361. c = match.group(2).strip(" \t")
  1362. c = self._encode_code(c)
  1363. return "<code>%s</code>" % c
  1364. def _do_code_spans(self, text):
  1365. # * Backtick quotes are used for <code></code> spans.
  1366. #
  1367. # * You can use multiple backticks as the delimiters if you want to
  1368. # include literal backticks in the code span. So, this input:
  1369. #
  1370. # Just type ``foo `bar` baz`` at the prompt.
  1371. #
  1372. # Will translate to:
  1373. #
  1374. # <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  1375. #
  1376. # There's no arbitrary limit to the number of backticks you
  1377. # can use as delimters. If you need three consecutive backticks
  1378. # in your code, use four for delimiters, etc.
  1379. #
  1380. # * You can use spaces to get literal backticks at the edges:
  1381. #
  1382. # ... type `` `bar` `` ...
  1383. #
  1384. # Turns to:
  1385. #
  1386. # ... type <code>`bar`</code> ...
  1387. return self._code_span_re.sub(self._code_span_sub, text)
  1388. def _encode_code(self, text):
  1389. """Encode/escape certain characters inside Markdown code runs.
  1390. The point is that in code, these characters are literals,
  1391. and lose their special Markdown meanings.
  1392. """
  1393. replacements = [
  1394. # Encode all ampersands; HTML entities are not
  1395. # entities within a Markdown code span.
  1396. ('&', '&amp;'),
  1397. # Do the angle bracket song and dance:
  1398. ('<', '&lt;'),
  1399. ('>', '&gt;'),
  1400. ]
  1401. for before, after in replacements:
  1402. text = text.replace(before, after)
  1403. hashed = _hash_text(text)
  1404. self._escape_table[text] = hashed
  1405. return hashed
  1406. _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S)
  1407. _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S)
  1408. _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S)
  1409. _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S)
  1410. def _do_italics_and_bold(self, text):
  1411. # <strong> must go first:
  1412. if "code-friendly" in self.extras:
  1413. text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text)
  1414. text = self._code_friendly_em_re.sub(r"<em>\1</em>", text)
  1415. else:
  1416. text = self._strong_re.sub(r"<strong>\2</strong>", text)
  1417. text = self._em_re.sub(r"<em>\2</em>", text)
  1418. return text
  1419. # "smarty-pants" extra: Very liberal in interpreting a single prime as an
  1420. # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and
  1421. # "twixt" can be written without an initial apostrophe. This is fine because
  1422. # using scare quotes (single quotation marks) is rare.
  1423. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))")
  1424. _contractions = ["tis", "twas", "twer", "neath", "o", "n",
  1425. "round", "bout", "twixt", "nuff", "fraid", "sup"]
  1426. def _do_smart_contractions(self, text):
  1427. text = self._apostrophe_year_re.sub(r"&#8217;\1", text)
  1428. for c in self._contractions:
  1429. text = text.replace("'%s" % c, "&#8217;%s" % c)
  1430. text = text.replace("'%s" % c.capitalize(),
  1431. "&#8217;%s" % c.capitalize())
  1432. return text
  1433. # Substitute double-quotes before single-quotes.
  1434. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)")
  1435. _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)')
  1436. _closing_single_quote_re = re.compile(r"(?<=\S)'")
  1437. _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))')
  1438. def _do_smart_punctuation(self, text):
  1439. """Fancifies 'single quotes', "double quotes", and apostrophes.
  1440. Converts --, ---, and ... into en dashes, em dashes, and ellipses.
  1441. Inspiration is: <http://daringfireball.net/projects/smartypants/>
  1442. See "test/tm-cases/smarty_pants.text" for a full discussion of the
  1443. support here and
  1444. <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a
  1445. discussion of some diversion from the original SmartyPants.
  1446. """
  1447. if "'" in text: # guard for perf
  1448. text = self._do_smart_contractions(text)
  1449. text = self._opening_single_quote_re.sub("&#8216;", text)
  1450. text = self._closing_single_quote_re.sub("&#8217;", text)
  1451. if '"' in text: # guard for perf
  1452. text = self._opening_double_quote_re.sub("&#8220;", text)
  1453. text = self._closing_double_quote_re.sub("&#8221;", text)
  1454. text = text.replace("---", "&#8212;")
  1455. text = text.replace("--", "&#8211;")
  1456. text = text.replace("...", "&#8230;")
  1457. text = text.replace(" . . . ", "&#8230;")
  1458. text = text.replace(". . .", "&#8230;")
  1459. return text
  1460. _block_quote_re = re.compile(r'''
  1461. ( # Wrap whole match in \1
  1462. (
  1463. ^[ \t]*>[ \t]? # '>' at the start of a line
  1464. .+\n # rest of the first line
  1465. (.+\n)* # subsequent consecutive lines
  1466. \n* # blanks
  1467. )+
  1468. )
  1469. ''', re.M | re.X)
  1470. _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M);
  1471. _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S)
  1472. def _dedent_two_spaces_sub(self, match):
  1473. return re.sub(r'(?m)^ ', '', match.group(1))
  1474. def _block_quote_sub(self, match):
  1475. bq = match.group(1)
  1476. bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting
  1477. bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines
  1478. bq = self._run_block_gamut(bq) # recurse
  1479. bq = re.sub('(?m)^', ' ', bq)
  1480. # These leading spaces screw with <pre> content, so we need to fix that:
  1481. bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq)
  1482. return "<blockquote>\n%s\n</blockquote>\n\n" % bq
  1483. def _do_block_quotes(self, text):
  1484. if '>' not in text:
  1485. return text
  1486. return self._block_quote_re.sub(self._block_quote_sub, text)
  1487. def _form_paragraphs(self, text):
  1488. # Strip leading and trailing lines:
  1489. text = text.strip('\n')
  1490. # Wrap <p> tags.
  1491. grafs = []
  1492. for i, graf in enumerate(re.split(r"\n{2,}", text)):
  1493. if graf in self.html_blocks:
  1494. # Unhashify HTML blocks
  1495. grafs.append(self.html_blocks[graf])
  1496. else:
  1497. cuddled_list = None
  1498. if "cuddled-lists" in self.extras:
  1499. # Need to put back trailing '\n' for `_list_item_re`
  1500. # match at the end of the paragraph.
  1501. li = self._list_item_re.search(graf + '\n')
  1502. # Two of the same list marker in this paragraph: a likely
  1503. # candidate for a list cuddled to preceding paragraph
  1504. # text (issue 33). Note the `[-1]` is a quick way to
  1505. # consider numeric bullets (e.g. "1." and "2.") to be
  1506. # equal.
  1507. if (li and len(li.group(2)) <= 3 and li.group("next_marker")
  1508. and li.group("marker")[-1] == li.group("next_marker")[-1]):
  1509. start = li.start()
  1510. cuddled_list = self._do_lists(graf[start:]).rstrip("\n")
  1511. assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>")
  1512. graf = graf[:start]
  1513. # Wrap <p> tags.
  1514. graf = self._run_span_gamut(graf)
  1515. grafs.append("<p>" + graf.lstrip(" \t") + "</p>")
  1516. if cuddled_list:
  1517. grafs.append(cuddled_list)
  1518. return "\n\n".join(grafs)
  1519. def _add_footnotes(self, text):
  1520. if self.footnotes:
  1521. footer = [
  1522. '<div class="footnotes">',
  1523. '<hr' + self.empty_element_suffix,
  1524. '<ol>',
  1525. ]
  1526. for i, id in enumerate(self.footnote_ids):
  1527. if i != 0:
  1528. footer.append('')
  1529. footer.append('<li id="fn-%s">' % id)
  1530. footer.append(self._run_block_gamut(self.footnotes[id]))
  1531. backlink = ('<a href="#fnref-%s" '
  1532. 'class="footnoteBackLink" '
  1533. 'title="Jump back to footnote %d in the text.">'
  1534. '&#8617;</a>' % (id, i+1))
  1535. if footer[-1].endswith("</p>"):
  1536. footer[-1] = footer[-1][:-len("</p>")] \
  1537. + '&nbsp;' + backlink + "</p>"
  1538. else:
  1539. footer.append("\n<p>%s</p>" % backlink)
  1540. footer.append('</li>')
  1541. footer.append('</ol>')
  1542. footer.append('</div>')
  1543. return text + '\n\n' + '\n'.join(footer)
  1544. else:
  1545. return text
  1546. # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  1547. # http://bumppo.net/projects/amputator/
  1548. _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)')
  1549. _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I)
  1550. _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I)
  1551. def _encode_amps_and_angles(self, text):
  1552. # Smart processing for ampersands and angle brackets that need
  1553. # to be encoded.
  1554. text = self._ampersand_re.sub('&amp;', text)
  1555. # Encode naked <'s
  1556. text = self._naked_lt_re.sub('&lt;', text)
  1557. # Encode naked >'s
  1558. # Note: Other markdown implementations (e.g. Markdown.pl, PHP
  1559. # Markdown) don't do this.
  1560. text = self._naked_gt_re.sub('&gt;', text)
  1561. return text
  1562. def _encode_backslash_escapes(self, text):
  1563. for ch, escape in list(self._escape_table.items()):
  1564. text = text.replace("\\"+ch, escape)
  1565. return text
  1566. _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I)
  1567. def _auto_link_sub(self, match):
  1568. g1 = match.group(1)
  1569. return '<a href="%s">%s</a>' % (g1, g1)
  1570. _auto_email_link_re = re.compile(r"""
  1571. <
  1572. (?:mailto:)?
  1573. (
  1574. [-.\w]+
  1575. \@
  1576. [-\w]+(\.[-\w]+)*\.[a-z]+
  1577. )
  1578. >
  1579. """, re.I | re.X | re.U)
  1580. def _auto_email_link_sub(self, match):
  1581. return self._encode_email_address(
  1582. self._unescape_special_chars(match.group(1)))
  1583. def _do_auto_links(self, text):
  1584. text = self._auto_link_re.sub(self._auto_link_sub, text)
  1585. text = self._auto_email_link_re.sub(self._auto_email_link_sub, text)
  1586. return text
  1587. def _encode_email_address(self, addr):
  1588. # Input: an email address, e.g. "foo@example.com"
  1589. #
  1590. # Output: the email address as a mailto link, with each character
  1591. # of the address encoded as either a decimal or hex entity, in
  1592. # the hopes of foiling most address harvesting spam bots. E.g.:
  1593. #
  1594. # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  1595. # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  1596. # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  1597. #
  1598. # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  1599. # mailing list: <http://tinyurl.com/yu7ue>
  1600. chars = [_xml_encode_email_char_at_random(ch)
  1601. for ch in "mailto:" + addr]
  1602. # Strip the mailto: from the visible part.
  1603. addr = '<a href="%s">%s</a>' \
  1604. % (''.join(chars), ''.join(chars[7:]))
  1605. return addr
  1606. def _do_link_patterns(self, text):
  1607. """Caveat emptor: there isn't much guarding against link
  1608. patterns being formed inside other standard Markdown links, e.g.
  1609. inside a [link def][like this].
  1610. Dev Notes: *Could* consider prefixing regexes with a negative
  1611. lookbehind assertion to attempt to guard against this.
  1612. """
  1613. link_from_hash = {}
  1614. for regex, repl in self.link_patterns:
  1615. replacements = []
  1616. for match in regex.finditer(text):
  1617. if hasattr(repl, "__call__"):
  1618. href = repl(match)
  1619. else:
  1620. href = match.expand(repl)
  1621. replacements.append((match.span(), href))
  1622. for (start, end), href in reversed(replacements):
  1623. escaped_href = (
  1624. href.replace('"', '&quot;') # b/c of attr quote
  1625. # To avoid markdown <em> and <strong>:
  1626. .replace('*', self._escape_table['*'])
  1627. .replace('_', self._escape_table['_']))
  1628. link = '<a href="%s">%s</a>' % (escaped_href, text[start:end])
  1629. hash = _hash_text(link)
  1630. link_from_hash[hash] = link
  1631. text = text[:start] + hash + text[end:]
  1632. for hash, link in list(link_from_hash.items()):
  1633. text = text.replace(hash, link)
  1634. return text
  1635. def _unescape_special_chars(self, text):
  1636. # Swap back in all the special characters we've hidden.
  1637. for ch, hash in list(self._escape_table.items()):
  1638. text = text.replace(hash, ch)
  1639. return text
  1640. def _outdent(self, text):
  1641. # Remove one level of line-leading tabs or spaces
  1642. return self._outdent_re.sub('', text)
  1643. class MarkdownWithExtras(Markdown):
  1644. """A markdowner class that enables most extras:
  1645. - footnotes
  1646. - code-color (only has effect if 'pygments' Python module on path)
  1647. These are not included:
  1648. - pyshell (specific to Python-related documenting)
  1649. - code-friendly (because it *disables* part of the syntax)
  1650. - link-patterns (because you need to specify some actual
  1651. link-patterns anyway)
  1652. """
  1653. extras = ["footnotes", "code-color"]
  1654. #---- internal support functions
  1655. class UnicodeWithAttrs(unicode):
  1656. """A subclass of unicode used for the return value of conversion to
  1657. possibly attach some attributes. E.g. the "toc_html" attribute when
  1658. the "toc" extra is used.
  1659. """
  1660. metadata = None
  1661. _toc = None
  1662. def toc_html(self):
  1663. """Return the HTML for the current TOC.
  1664. This expects the `_toc` attribute to have been set on this instance.
  1665. """
  1666. if self._toc is None:
  1667. return None
  1668. def indent():
  1669. return ' ' * (len(h_stack) - 1)
  1670. lines = []
  1671. h_stack = [0] # stack of header-level numbers
  1672. for level, id, name in self._toc:
  1673. if level > h_stack[-1]:
  1674. lines.append("%s<ul>" % indent())
  1675. h_stack.append(level)
  1676. elif level == h_stack[-1]:
  1677. lines[-1] += "</li>"
  1678. else:
  1679. while level < h_stack[-1]:
  1680. h_stack.pop()
  1681. if not lines[-1].endswith("</li>"):
  1682. lines[-1] += "</li>"
  1683. lines.append("%s</ul></li>" % indent())
  1684. lines.append('%s<li><a href="#%s">%s</a>' % (
  1685. indent(), id, name))
  1686. while len(h_stack) > 1:
  1687. h_stack.pop()
  1688. if not lines[-1].endswith("</li>"):
  1689. lines[-1] += "</li>"
  1690. lines.append("%s</ul>" % indent())
  1691. return '\n'.join(lines) + '\n'
  1692. toc_html = property(toc_html)
  1693. ## {{{ http://code.activestate.com/recipes/577257/ (r1)
  1694. _slugify_strip_re = re.compile(r'[^\w\s-]')
  1695. _slugify_hyphenate_re = re.compile(r'[-\s]+')
  1696. def _slugify(value):
  1697. """
  1698. Normalizes string, converts to lowercase, removes non-alpha characters,
  1699. and converts spaces to hyphens.
  1700. From Django's "django/template/defaultfilters.py".
  1701. """
  1702. try:
  1703. import unicodedata
  1704. value = unicodedata.normalize('NFKD', value)
  1705. except ImportError:
  1706. pass
  1707. value = value.encode('ascii', 'ignore').decode()
  1708. value = _slugify_strip_re.sub('', value).strip().lower()
  1709. return _slugify_hyphenate_re.sub('-', value)
  1710. ## end of http://code.activestate.com/recipes/577257/ }}}
  1711. # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
  1712. def _curry(*args, **kwargs):
  1713. function, args = args[0], args[1:]
  1714. def result(*rest, **kwrest):
  1715. combined = kwargs.copy()
  1716. combined.update(kwrest)
  1717. return function(*args + rest, **combined)
  1718. return result
  1719. # Recipe: regex_from_encoded_pattern (1.0)
  1720. def _regex_from_encoded_pattern(s):
  1721. """'foo' -> re.compile(re.escape('foo'))
  1722. '/foo/' -> re.compile('foo')
  1723. '/foo/i' -> re.compile('foo', re.I)
  1724. """
  1725. if s.startswith('/') and s.rfind('/') != 0:
  1726. # Parse it: /PATTERN/FLAGS
  1727. idx = s.rfind('/')
  1728. pattern, flags_str = s[1:idx], s[idx+1:]
  1729. flag_from_char = {
  1730. "i": re.IGNORECASE,
  1731. "l": re.LOCALE,
  1732. "s": re.DOTALL,
  1733. "m": re.MULTILINE,
  1734. "u": re.UNICODE,
  1735. }
  1736. flags = 0
  1737. for char in flags_str:
  1738. try:
  1739. flags |= flag_from_char[char]
  1740. except KeyError:
  1741. raise ValueError("unsupported regex flag: '%s' in '%s' "
  1742. "(must be one of '%s')"
  1743. % (char, s, ''.join(list(flag_from_char.keys()))))
  1744. return re.compile(s[1:idx], flags)
  1745. else: # not an encoded regex
  1746. return re.compile(re.escape(s))
  1747. # Recipe: dedent (0.1.2)
  1748. def _dedentlines(lines, tabsize=8, skip_first_line=False):
  1749. """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
  1750. "lines" is a list of lines to dedent.
  1751. "tabsize" is the tab width to use for indent width calculations.
  1752. "skip_first_line" is a boolean indicating if the first line should
  1753. be skipped for calculating the indent width and for dedenting.
  1754. This is sometimes useful for docstrings and similar.
  1755. Same as dedent() except operates on a sequence of lines. Note: the
  1756. lines list is modified **in-place**.
  1757. """
  1758. DEBUG = False
  1759. if DEBUG:
  1760. print("dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\
  1761. % (tabsize, skip_first_line))
  1762. indents = []
  1763. margin = None
  1764. for i, line in enumerate(lines):
  1765. if i == 0 and skip_first_line: continue
  1766. indent = 0
  1767. for ch in line:
  1768. if ch == ' ':
  1769. indent += 1
  1770. elif ch == '\t':
  1771. indent += tabsize - (indent % tabsize)
  1772. elif ch in '\r\n':
  1773. continue # skip all-whitespace lines
  1774. else:
  1775. break
  1776. else:
  1777. continue # skip all-whitespace lines
  1778. if DEBUG: print("dedent: indent=%d: %r" % (indent, line))
  1779. if margin is None:
  1780. margin = indent
  1781. else:
  1782. margin = min(margin, indent)
  1783. if DEBUG: print("dedent: margin=%r" % margin)
  1784. if margin is not None and margin > 0:
  1785. for i, line in enumerate(lines):
  1786. if i == 0 and skip_first_line: continue
  1787. removed = 0
  1788. for j, ch in enumerate(line):
  1789. if ch == ' ':
  1790. removed += 1
  1791. elif ch == '\t':
  1792. removed += tabsize - (removed % tabsize)
  1793. elif ch in '\r\n':
  1794. if DEBUG: print("dedent: %r: EOL -> strip up to EOL" % line)
  1795. lines[i] = lines[i][j:]
  1796. break
  1797. else:
  1798. raise ValueError("unexpected non-whitespace char %r in "
  1799. "line %r while removing %d-space margin"
  1800. % (ch, line, margin))
  1801. if DEBUG:
  1802. print("dedent: %r: %r -> removed %d/%d"\
  1803. % (line, ch, removed, margin))
  1804. if removed == margin:
  1805. lines[i] = lines[i][j+1:]
  1806. break
  1807. elif removed > margin:
  1808. lines[i] = ' '*(removed-margin) + lines[i][j+1:]
  1809. break
  1810. else:
  1811. if removed:
  1812. lines[i] = lines[i][removed:]
  1813. return lines
  1814. def _dedent(text, tabsize=8, skip_first_line=False):
  1815. """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
  1816. "text" is the text to dedent.
  1817. "tabsize" is the tab width to use for indent width calculations.
  1818. "skip_first_line" is a boolean indicating if the first line should
  1819. be skipped for calculating the indent width and for dedenting.
  1820. This is sometimes useful for docstrings and similar.
  1821. textwrap.dedent(s), but don't expand tabs to spaces
  1822. """
  1823. lines = text.splitlines(1)
  1824. _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)
  1825. return ''.join(lines)
  1826. class _memoized(object):
  1827. """Decorator that caches a function's return value each time it is called.
  1828. If called later with the same arguments, the cached value is returned, and
  1829. not re-evaluated.
  1830. http://wiki.python.org/moin/PythonDecoratorLibrary
  1831. """
  1832. def __init__(self, func):
  1833. self.func = func
  1834. self.cache = {}
  1835. def __call__(self, *args):
  1836. try:
  1837. return self.cache[args]
  1838. except KeyError:
  1839. self.cache[args] = value = self.func(*args)
  1840. return value
  1841. except TypeError:
  1842. # uncachable -- for instance, passing a list as an argument.
  1843. # Better to not cache than to blow up entirely.
  1844. return self.func(*args)
  1845. def __repr__(self):
  1846. """Return the function's docstring."""
  1847. return self.func.__doc__
  1848. def _xml_oneliner_re_from_tab_width(tab_width):
  1849. """Standalone XML processing instruction regex."""
  1850. return re.compile(r"""
  1851. (?:
  1852. (?<=\n\n) # Starting after a blank line
  1853. | # or
  1854. \A\n? # the beginning of the doc
  1855. )
  1856. ( # save in $1
  1857. [ ]{0,%d}
  1858. (?:
  1859. <\?\w+\b\s+.*?\?> # XML processing instruction
  1860. |
  1861. <\w+:\w+\b\s+.*?/> # namespaced single tag
  1862. )
  1863. [ \t]*
  1864. (?=\n{2,}|\Z) # followed by a blank line or end of document
  1865. )
  1866. """ % (tab_width - 1), re.X)
  1867. _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width)
  1868. def _hr_tag_re_from_tab_width(tab_width):
  1869. return re.compile(r"""
  1870. (?:
  1871. (?<=\n\n) # Starting after a blank line
  1872. | # or
  1873. \A\n? # the beginning of the doc
  1874. )
  1875. ( # save in \1
  1876. [ ]{0,%d}
  1877. <(hr) # start tag = \2
  1878. \b # word break
  1879. ([^<>])*? #
  1880. /?> # the matching end tag
  1881. [ \t]*
  1882. (?=\n{2,}|\Z) # followed by a blank line or end of document
  1883. )
  1884. """ % (tab_width - 1), re.X)
  1885. _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width)
  1886. def _xml_escape_attr(attr, skip_single_quote=True):
  1887. """Escape the given string for use in an HTML/XML tag attribute.
  1888. By default this doesn't bother with escaping `'` to `&#39;`, presuming that
  1889. the tag attribute is surrounded by double quotes.
  1890. """
  1891. escaped = (attr
  1892. .replace('&', '&amp;')
  1893. .replace('"', '&quot;')
  1894. .replace('<', '&lt;')
  1895. .replace('>', '&gt;'))
  1896. if not skip_single_quote:
  1897. escaped = escaped.replace("'", "&#39;")
  1898. return escaped
  1899. def _xml_encode_email_char_at_random(ch):
  1900. r = random()
  1901. # Roughly 10% raw, 45% hex, 45% dec.
  1902. # '@' *must* be encoded. I [John Gruber] insist.
  1903. # Issue 26: '_' must be encoded.
  1904. if r > 0.9 and ch not in "@_":
  1905. return ch
  1906. elif r < 0.45:
  1907. # The [1:] is to drop leading '0': 0x63 -> x63
  1908. return '&#%s;' % hex(ord(ch))[1:]
  1909. else:
  1910. return '&#%s;' % ord(ch)
  1911. #---- mainline
  1912. class _NoReflowFormatter(optparse.IndentedHelpFormatter):
  1913. """An optparse formatter that does NOT reflow the description."""
  1914. def format_description(self, description):
  1915. return description or ""
  1916. def _test():
  1917. import doctest
  1918. doctest.testmod()
  1919. def main(argv=None):
  1920. if argv is None:
  1921. argv = sys.argv
  1922. if not logging.root.handlers:
  1923. logging.basicConfig()
  1924. usage = "usage: %prog [PATHS...]"
  1925. version = "%prog "+__version__
  1926. parser = optparse.OptionParser(prog="markdown2", usage=usage,
  1927. version=version, description=cmdln_desc,
  1928. formatter=_NoReflowFormatter())
  1929. parser.add_option("-v", "--verbose", dest="log_level",
  1930. action="store_const", const=logging.DEBUG,
  1931. help="more verbose output")
  1932. parser.add_option("--encoding",
  1933. help="specify encoding of text content")
  1934. parser.add_option("--html4tags", action="store_true", default=False,
  1935. help="use HTML 4 style for empty element tags")
  1936. parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode",
  1937. help="sanitize literal HTML: 'escape' escapes "
  1938. "HTML meta chars, 'replace' replaces with an "
  1939. "[HTML_REMOVED] note")
  1940. parser.add_option("-x", "--extras", action="append",
  1941. help="Turn on specific extra features (not part of "
  1942. "the core Markdown spec). See above.")
  1943. parser.add_option("--use-file-vars",
  1944. help="Look for and use Emacs-style 'markdown-extras' "
  1945. "file var to turn on extras. See "
  1946. "<https://github.com/trentm/python-markdown2/wiki/Extras>")
  1947. parser.add_option("--link-patterns-file",
  1948. help="path to a link pattern file")
  1949. parser.add_option("--self-test", action="store_true",
  1950. help="run internal self-tests (some doctests)")
  1951. parser.add_option("--compare", action="store_true",
  1952. help="run against Markdown.pl as well (for testing)")
  1953. parser.set_defaults(log_level=logging.INFO, compare=False,
  1954. encoding="utf-8", safe_mode=None, use_file_vars=False)
  1955. opts, paths = parser.parse_args()
  1956. log.setLevel(opts.log_level)
  1957. if opts.self_test:
  1958. return _test()
  1959. if opts.extras:
  1960. extras = {}
  1961. for s in opts.extras:
  1962. splitter = re.compile("[,;: ]+")
  1963. for e in splitter.split(s):
  1964. if '=' in e:
  1965. ename, earg = e.split('=', 1)
  1966. try:
  1967. earg = int(earg)
  1968. except ValueError:
  1969. pass
  1970. else:
  1971. ename, earg = e, None
  1972. extras[ename] = earg
  1973. else:
  1974. extras = None
  1975. if opts.link_patterns_file:
  1976. link_patterns = []
  1977. f = open(opts.link_patterns_file)
  1978. try:
  1979. for i, line in enumerate(f.readlines()):
  1980. if not line.strip(): continue
  1981. if line.lstrip().startswith("#"): continue
  1982. try:
  1983. pat, href = line.rstrip().rsplit(None, 1)
  1984. except ValueError:
  1985. raise MarkdownError("%s:%d: invalid link pattern line: %r"
  1986. % (opts.link_patterns_file, i+1, line))
  1987. link_patterns.append(
  1988. (_regex_from_encoded_pattern(pat), href))
  1989. finally:
  1990. f.close()
  1991. else:
  1992. link_patterns = None
  1993. from os.path import join, dirname, abspath, exists
  1994. markdown_pl = join(dirname(dirname(abspath(__file__))), "test",
  1995. "Markdown.pl")
  1996. if not paths:
  1997. paths = ['-']
  1998. for path in paths:
  1999. if path == '-':
  2000. text = sys.stdin.read()
  2001. else:
  2002. fp = codecs.open(path, 'r', opts.encoding)
  2003. text = fp.read()
  2004. fp.close()
  2005. if opts.compare:
  2006. from subprocess import Popen, PIPE
  2007. print("==== Markdown.pl ====")
  2008. p = Popen('perl %s' % markdown_pl, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True)
  2009. p.stdin.write(text.encode('utf-8'))
  2010. p.stdin.close()
  2011. perl_html = p.stdout.read().decode('utf-8')
  2012. if py3:
  2013. sys.stdout.write(perl_html)
  2014. else:
  2015. sys.stdout.write(perl_html.encode(
  2016. sys.stdout.encoding or "utf-8", 'xmlcharrefreplace'))
  2017. print("==== markdown2.py ====")
  2018. html = markdown(text,
  2019. html4tags=opts.html4tags,
  2020. safe_mode=opts.safe_mode,
  2021. extras=extras, link_patterns=link_patterns,
  2022. use_file_vars=opts.use_file_vars)
  2023. if py3:
  2024. sys.stdout.write(html)
  2025. else:
  2026. sys.stdout.write(html.encode(
  2027. sys.stdout.encoding or "utf-8", 'xmlcharrefreplace'))
  2028. if extras and "toc" in extras:
  2029. log.debug("toc_html: " +
  2030. html.toc_html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace'))
  2031. if opts.compare:
  2032. test_dir = join(dirname(dirname(abspath(__file__))), "test")
  2033. if exists(join(test_dir, "test_markdown2.py")):
  2034. sys.path.insert(0, test_dir)
  2035. from test_markdown2 import norm_html_from_html
  2036. norm_html = norm_html_from_html(html)
  2037. norm_perl_html = norm_html_from_html(perl_html)
  2038. else:
  2039. norm_html = html
  2040. norm_perl_html = perl_html
  2041. print("==== match? %r ====" % (norm_perl_html == norm_html))
  2042. if __name__ == "__main__":
  2043. sys.exit( main(sys.argv) )