PageRenderTime 60ms CodeModel.GetById 16ms 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

Large files files are truncated, but you can click here to view the full file

  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.

Large files files are truncated, but you can click here to view the full file