PageRenderTime 48ms CodeModel.GetById 4ms RepoModel.GetById 1ms app.codeStats 0ms

/gluon/contrib/markdown/markdown2.py

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