PageRenderTime 67ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/markdown2.py

https://github.com/revolunet/python-markdown2
Python | 2321 lines | 2196 code | 39 blank | 86 comment | 73 complexity | 489c08b2d5bc6823f5bdbb0aaa1bbe72 MD5 | raw file
Possible License(s): MIT

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, 1, 1)
  74. __version__ = '.'.join(map(str, __version_info__))
  75. __author__ = "Trent Mick"
  76. import os
  77. import sys
  78. from pprint import pprint
  79. import re
  80. import logging
  81. try:
  82. from hashlib import md5
  83. except ImportError:
  84. from md5 import md5
  85. import optparse
  86. from random import random, randint
  87. import codecs
  88. #---- Python version compat
  89. try:
  90. from urllib.parse import quote # python3
  91. except ImportError:
  92. from urllib import quote # python2
  93. if sys.version_info[:2] < (2,4):
  94. from sets import Set as set
  95. def reversed(sequence):
  96. for i in sequence[::-1]:
  97. yield i
  98. # Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3).
  99. if sys.version_info[0] <= 2:
  100. py3 = False
  101. try:
  102. bytes
  103. except NameError:
  104. bytes = str
  105. base_string_type = basestring
  106. elif sys.version_info[0] >= 3:
  107. py3 = True
  108. unicode = str
  109. base_string_type = str
  110. #---- globals
  111. DEBUG = False
  112. log = logging.getLogger("markdown")
  113. DEFAULT_TAB_WIDTH = 4
  114. SECRET_SALT = bytes(randint(0, 1000000))
  115. def _hash_text(s):
  116. return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest()
  117. # Table of hash values for escaped characters:
  118. g_escape_table = dict([(ch, _hash_text(ch))
  119. for ch in '\\`*_{}[]()>#+-.!'])
  120. #---- exceptions
  121. class MarkdownError(Exception):
  122. pass
  123. #---- public api
  124. def markdown_path(path, encoding="utf-8",
  125. html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
  126. safe_mode=None, extras=None, link_patterns=None,
  127. use_file_vars=False):
  128. fp = codecs.open(path, 'r', encoding)
  129. text = fp.read()
  130. fp.close()
  131. return Markdown(html4tags=html4tags, tab_width=tab_width,
  132. safe_mode=safe_mode, extras=extras,
  133. link_patterns=link_patterns,
  134. use_file_vars=use_file_vars).convert(text)
  135. def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
  136. safe_mode=None, extras=None, link_patterns=None,
  137. use_file_vars=False):
  138. return Markdown(html4tags=html4tags, tab_width=tab_width,
  139. safe_mode=safe_mode, extras=extras,
  140. link_patterns=link_patterns,
  141. use_file_vars=use_file_vars).convert(text)
  142. class Markdown(object):
  143. # The dict of "extras" to enable in processing -- a mapping of
  144. # extra name to argument for the extra. Most extras do not have an
  145. # argument, in which case the value is None.
  146. #
  147. # This can be set via (a) subclassing and (b) the constructor
  148. # "extras" argument.
  149. extras = None
  150. urls = None
  151. titles = None
  152. html_blocks = None
  153. html_spans = None
  154. html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py
  155. # Used to track when we're inside an ordered or unordered list
  156. # (see _ProcessListItems() for details):
  157. list_level = 0
  158. _ws_only_line_re = re.compile(r"^[ \t]+$", re.M)
  159. def __init__(self, html4tags=False, tab_width=4, safe_mode=None,
  160. extras=None, link_patterns=None, use_file_vars=False):
  161. if html4tags:
  162. self.empty_element_suffix = ">"
  163. else:
  164. self.empty_element_suffix = " />"
  165. self.tab_width = tab_width
  166. # For compatibility with earlier markdown2.py and with
  167. # markdown.py's safe_mode being a boolean,
  168. # safe_mode == True -> "replace"
  169. if safe_mode is True:
  170. self.safe_mode = "replace"
  171. else:
  172. self.safe_mode = safe_mode
  173. # Massaging and building the "extras" info.
  174. if self.extras is None:
  175. self.extras = {}
  176. elif not isinstance(self.extras, dict):
  177. self.extras = dict([(e, None) for e in self.extras])
  178. if extras:
  179. if not isinstance(extras, dict):
  180. extras = dict([(e, None) for e in extras])
  181. self.extras.update(extras)
  182. assert isinstance(self.extras, dict)
  183. if "toc" in self.extras and not "header-ids" in self.extras:
  184. self.extras["header-ids"] = None # "toc" implies "header-ids"
  185. self._instance_extras = self.extras.copy()
  186. self.link_patterns = link_patterns
  187. self.use_file_vars = use_file_vars
  188. self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M)
  189. self._escape_table = g_escape_table.copy()
  190. if "smarty-pants" in self.extras:
  191. self._escape_table['"'] = _hash_text('"')
  192. self._escape_table["'"] = _hash_text("'")
  193. def reset(self):
  194. self.urls = {}
  195. self.titles = {}
  196. self.html_blocks = {}
  197. self.html_spans = {}
  198. self.list_level = 0
  199. self.extras = self._instance_extras.copy()
  200. if "footnotes" in self.extras:
  201. self.footnotes = {}
  202. self.footnote_ids = []
  203. if "header-ids" in self.extras:
  204. self._count_from_header_id = {} # no `defaultdict` in Python 2.4
  205. if "metadata" in self.extras:
  206. self.metadata = {}
  207. # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel"
  208. # should only be used in <a> tags with an "href" attribute.
  209. _a_nofollow = re.compile(r"<(a)([^>]*href=)", re.IGNORECASE)
  210. def convert(self, text):
  211. """Convert the given text."""
  212. # Main function. The order in which other subs are called here is
  213. # essential. Link and image substitutions need to happen before
  214. # _EscapeSpecialChars(), so that any *'s or _'s in the <a>
  215. # and <img> tags get encoded.
  216. # Clear the global hashes. If we don't clear these, you get conflicts
  217. # from other articles when generating a page which contains more than
  218. # one article (e.g. an index page that shows the N most recent
  219. # articles):
  220. self.reset()
  221. if not isinstance(text, unicode):
  222. #TODO: perhaps shouldn't presume UTF-8 for string input?
  223. text = unicode(text, 'utf-8')
  224. if self.use_file_vars:
  225. # Look for emacs-style file variable hints.
  226. emacs_vars = self._get_emacs_vars(text)
  227. if "markdown-extras" in emacs_vars:
  228. splitter = re.compile("[ ,]+")
  229. for e in splitter.split(emacs_vars["markdown-extras"]):
  230. if '=' in e:
  231. ename, earg = e.split('=', 1)
  232. try:
  233. earg = int(earg)
  234. except ValueError:
  235. pass
  236. else:
  237. ename, earg = e, None
  238. self.extras[ename] = earg
  239. # Standardize line endings:
  240. text = re.sub("\r\n|\r", "\n", text)
  241. # Make sure $text ends with a couple of newlines:
  242. text += "\n\n"
  243. # Convert all tabs to spaces.
  244. text = self._detab(text)
  245. # Strip any lines consisting only of spaces and tabs.
  246. # This makes subsequent regexen easier to write, because we can
  247. # match consecutive blank lines with /\n+/ instead of something
  248. # contorted like /[ \t]*\n+/ .
  249. text = self._ws_only_line_re.sub("", text)
  250. # strip metadata from head and extract
  251. if "metadata" in self.extras:
  252. text = self._extract_metadata(text)
  253. text = self.preprocess(text)
  254. if self.safe_mode:
  255. text = self._hash_html_spans(text)
  256. # Turn block-level HTML blocks into hash entries
  257. text = self._hash_html_blocks(text, raw=True)
  258. # Strip link definitions, store in hashes.
  259. if "footnotes" in self.extras:
  260. # Must do footnotes first because an unlucky footnote defn
  261. # looks like a link defn:
  262. # [^4]: this "looks like a link defn"
  263. text = self._strip_footnote_definitions(text)
  264. text = self._strip_link_definitions(text)
  265. text = self._run_block_gamut(text)
  266. if "footnotes" in self.extras:
  267. text = self._add_footnotes(text)
  268. text = self.postprocess(text)
  269. text = self._unescape_special_chars(text)
  270. if self.safe_mode:
  271. text = self._unhash_html_spans(text)
  272. if "nofollow" in self.extras:
  273. text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text)
  274. text += "\n"
  275. rv = UnicodeWithAttrs(text)
  276. if "toc" in self.extras:
  277. rv._toc = self._toc
  278. if "metadata" in self.extras:
  279. rv.metadata = self.metadata
  280. return rv
  281. def postprocess(self, text):
  282. """A hook for subclasses to do some postprocessing of the html, if
  283. desired. This is called before unescaping of special chars and
  284. unhashing of raw HTML spans.
  285. """
  286. return text
  287. def preprocess(self, text):
  288. """A hook for subclasses to do some preprocessing of the Markdown, if
  289. desired. This is called after basic formatting of the text, but prior
  290. to any extras, safe mode, etc. processing.
  291. """
  292. return text
  293. # Is metadata if the content starts with '---'-fenced `key: value`
  294. # pairs. E.g. (indented for presentation):
  295. # ---
  296. # foo: bar
  297. # another-var: blah blah
  298. # ---
  299. _metadata_pat = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""")
  300. def _extract_metadata(self, text):
  301. # fast test
  302. if not text.startswith("---"):
  303. return text
  304. match = self._metadata_pat.match(text)
  305. if not match:
  306. return text
  307. tail = text[len(match.group(0)):]
  308. metadata_str = match.group(1).strip()
  309. for line in metadata_str.split('\n'):
  310. key, value = line.split(':', 1)
  311. self.metadata[key.strip()] = value.strip()
  312. return tail
  313. _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE)
  314. # This regular expression is intended to match blocks like this:
  315. # PREFIX Local Variables: SUFFIX
  316. # PREFIX mode: Tcl SUFFIX
  317. # PREFIX End: SUFFIX
  318. # Some notes:
  319. # - "[ \t]" is used instead of "\s" to specifically exclude newlines
  320. # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does
  321. # not like anything other than Unix-style line terminators.
  322. _emacs_local_vars_pat = re.compile(r"""^
  323. (?P<prefix>(?:[^\r\n|\n|\r])*?)
  324. [\ \t]*Local\ Variables:[\ \t]*
  325. (?P<suffix>.*?)(?:\r\n|\n|\r)
  326. (?P<content>.*?\1End:)
  327. """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)
  328. def _get_emacs_vars(self, text):
  329. """Return a dictionary of emacs-style local variables.
  330. Parsing is done loosely according to this spec (and according to
  331. some in-practice deviations from this):
  332. http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables
  333. """
  334. emacs_vars = {}
  335. SIZE = pow(2, 13) # 8kB
  336. # Search near the start for a '-*-'-style one-liner of variables.
  337. head = text[:SIZE]
  338. if "-*-" in head:
  339. match = self._emacs_oneliner_vars_pat.search(head)
  340. if match:
  341. emacs_vars_str = match.group(1)
  342. assert '\n' not in emacs_vars_str
  343. emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';')
  344. if s.strip()]
  345. if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]:
  346. # While not in the spec, this form is allowed by emacs:
  347. # -*- Tcl -*-
  348. # where the implied "variable" is "mode". This form
  349. # is only allowed if there are no other variables.
  350. emacs_vars["mode"] = emacs_var_strs[0].strip()
  351. else:
  352. for emacs_var_str in emacs_var_strs:
  353. try:
  354. variable, value = emacs_var_str.strip().split(':', 1)
  355. except ValueError:
  356. log.debug("emacs variables error: malformed -*- "
  357. "line: %r", emacs_var_str)
  358. continue
  359. # Lowercase the variable name because Emacs allows "Mode"
  360. # or "mode" or "MoDe", etc.
  361. emacs_vars[variable.lower()] = value.strip()
  362. tail = text[-SIZE:]
  363. if "Local Variables" in tail:
  364. match = self._emacs_local_vars_pat.search(tail)
  365. if match:
  366. prefix = match.group("prefix")
  367. suffix = match.group("suffix")
  368. lines = match.group("content").splitlines(0)
  369. #print "prefix=%r, suffix=%r, content=%r, lines: %s"\
  370. # % (prefix, suffix, match.group("content"), lines)
  371. # Validate the Local Variables block: proper prefix and suffix
  372. # usage.
  373. for i, line in enumerate(lines):
  374. if not line.startswith(prefix):
  375. log.debug("emacs variables error: line '%s' "
  376. "does not use proper prefix '%s'"
  377. % (line, prefix))
  378. return {}
  379. # Don't validate suffix on last line. Emacs doesn't care,
  380. # neither should we.
  381. if i != len(lines)-1 and not line.endswith(suffix):
  382. log.debug("emacs variables error: line '%s' "
  383. "does not use proper suffix '%s'"
  384. % (line, suffix))
  385. return {}
  386. # Parse out one emacs var per line.
  387. continued_for = None
  388. for line in lines[:-1]: # no var on the last line ("PREFIX End:")
  389. if prefix: line = line[len(prefix):] # strip prefix
  390. if suffix: line = line[:-len(suffix)] # strip suffix
  391. line = line.strip()
  392. if continued_for:
  393. variable = continued_for
  394. if line.endswith('\\'):
  395. line = line[:-1].rstrip()
  396. else:
  397. continued_for = None
  398. emacs_vars[variable] += ' ' + line
  399. else:
  400. try:
  401. variable, value = line.split(':', 1)
  402. except ValueError:
  403. log.debug("local variables error: missing colon "
  404. "in local variables entry: '%s'" % line)
  405. continue
  406. # Do NOT lowercase the variable name, because Emacs only
  407. # allows "mode" (and not "Mode", "MoDe", etc.) in this block.
  408. value = value.strip()
  409. if value.endswith('\\'):
  410. value = value[:-1].rstrip()
  411. continued_for = variable
  412. else:
  413. continued_for = None
  414. emacs_vars[variable] = value
  415. # Unquote values.
  416. for var, val in list(emacs_vars.items()):
  417. if len(val) > 1 and (val.startswith('"') and val.endswith('"')
  418. or val.startswith('"') and val.endswith('"')):
  419. emacs_vars[var] = val[1:-1]
  420. return emacs_vars
  421. # Cribbed from a post by Bart Lateur:
  422. # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154>
  423. _detab_re = re.compile(r'(.*?)\t', re.M)
  424. def _detab_sub(self, match):
  425. g1 = match.group(1)
  426. return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width))
  427. def _detab(self, text):
  428. r"""Remove (leading?) tabs from a file.
  429. >>> m = Markdown()
  430. >>> m._detab("\tfoo")
  431. ' foo'
  432. >>> m._detab(" \tfoo")
  433. ' foo'
  434. >>> m._detab("\t foo")
  435. ' foo'
  436. >>> m._detab(" foo")
  437. ' foo'
  438. >>> m._detab(" foo\n\tbar\tblam")
  439. ' foo\n bar blam'
  440. """
  441. if '\t' not in text:
  442. return text
  443. return self._detab_re.subn(self._detab_sub, text)[0]
  444. # I broke out the html5 tags here and add them to _block_tags_a and
  445. # _block_tags_b. This way html5 tags are easy to keep track of.
  446. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption'
  447. _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del'
  448. _block_tags_a += _html5tags
  449. _strict_tag_block_re = re.compile(r"""
  450. ( # save in \1
  451. ^ # start of line (with re.M)
  452. <(%s) # start tag = \2
  453. \b # word break
  454. (.*\n)*? # any number of lines, minimally matching
  455. </\2> # the matching end tag
  456. [ \t]* # trailing spaces/tabs
  457. (?=\n+|\Z) # followed by a newline or end of document
  458. )
  459. """ % _block_tags_a,
  460. re.X | re.M)
  461. _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math'
  462. _block_tags_b += _html5tags
  463. _liberal_tag_block_re = re.compile(r"""
  464. ( # save in \1
  465. ^ # start of line (with re.M)
  466. <(%s) # start tag = \2
  467. \b # word break
  468. (.*\n)*? # any number of lines, minimally matching
  469. .*</\2> # the matching end tag
  470. [ \t]* # trailing spaces/tabs
  471. (?=\n+|\Z) # followed by a newline or end of document
  472. )
  473. """ % _block_tags_b,
  474. re.X | re.M)
  475. _html_markdown_attr_re = re.compile(
  476. r'''\s+markdown=("1"|'1')''')
  477. def _hash_html_block_sub(self, match, raw=False):
  478. html = match.group(1)
  479. if raw and self.safe_mode:
  480. html = self._sanitize_html(html)
  481. elif 'markdown-in-html' in self.extras and 'markdown=' in html:
  482. first_line = html.split('\n', 1)[0]
  483. m = self._html_markdown_attr_re.search(first_line)
  484. if m:
  485. lines = html.split('\n')
  486. middle = '\n'.join(lines[1:-1])
  487. last_line = lines[-1]
  488. first_line = first_line[:m.start()] + first_line[m.end():]
  489. f_key = _hash_text(first_line)
  490. self.html_blocks[f_key] = first_line
  491. l_key = _hash_text(last_line)
  492. self.html_blocks[l_key] = last_line
  493. return ''.join(["\n\n", f_key,
  494. "\n\n", middle, "\n\n",
  495. l_key, "\n\n"])
  496. key = _hash_text(html)
  497. self.html_blocks[key] = html
  498. return "\n\n" + key + "\n\n"
  499. def _hash_html_blocks(self, text, raw=False):
  500. """Hashify HTML blocks
  501. We only want to do this for block-level HTML tags, such as headers,
  502. lists, and tables. That's because we still want to wrap <p>s around
  503. "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  504. phrase emphasis, and spans. The list of tags we're looking for is
  505. hard-coded.
  506. @param raw {boolean} indicates if these are raw HTML blocks in
  507. the original source. It makes a difference in "safe" mode.
  508. """
  509. if '<' not in text:
  510. return text
  511. # Pass `raw` value into our calls to self._hash_html_block_sub.
  512. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw)
  513. # First, look for nested blocks, e.g.:
  514. # <div>
  515. # <div>
  516. # tags for inner block must be indented.
  517. # </div>
  518. # </div>
  519. #
  520. # The outermost tags must start at the left margin for this to match, and
  521. # the inner nested divs must be indented.
  522. # We need to do this before the next, more liberal match, because the next
  523. # match will start at the first `<div>` and stop at the first `</div>`.
  524. text = self._strict_tag_block_re.sub(hash_html_block_sub, text)
  525. # Now match more liberally, simply from `\n<tag>` to `</tag>\n`
  526. text = self._liberal_tag_block_re.sub(hash_html_block_sub, text)
  527. # Special case just for <hr />. It was easier to make a special
  528. # case than to make the other regex more complicated.
  529. if "<hr" in text:
  530. _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width)
  531. text = _hr_tag_re.sub(hash_html_block_sub, text)
  532. # Special case for standalone HTML comments:
  533. if "<!--" in text:
  534. start = 0
  535. while True:
  536. # Delimiters for next comment block.
  537. try:
  538. start_idx = text.index("<!--", start)
  539. except ValueError:
  540. break
  541. try:
  542. end_idx = text.index("-->", start_idx) + 3
  543. except ValueError:
  544. break
  545. # Start position for next comment block search.
  546. start = end_idx
  547. # Validate whitespace before comment.
  548. if start_idx:
  549. # - Up to `tab_width - 1` spaces before start_idx.
  550. for i in range(self.tab_width - 1):
  551. if text[start_idx - 1] != ' ':
  552. break
  553. start_idx -= 1
  554. if start_idx == 0:
  555. break
  556. # - Must be preceded by 2 newlines or hit the start of
  557. # the document.
  558. if start_idx == 0:
  559. pass
  560. elif start_idx == 1 and text[0] == '\n':
  561. start_idx = 0 # to match minute detail of Markdown.pl regex
  562. elif text[start_idx-2:start_idx] == '\n\n':
  563. pass
  564. else:
  565. break
  566. # Validate whitespace after comment.
  567. # - Any number of spaces and tabs.
  568. while end_idx < len(text):
  569. if text[end_idx] not in ' \t':
  570. break
  571. end_idx += 1
  572. # - Must be following by 2 newlines or hit end of text.
  573. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'):
  574. continue
  575. # Escape and hash (must match `_hash_html_block_sub`).
  576. html = text[start_idx:end_idx]
  577. if raw and self.safe_mode:
  578. html = self._sanitize_html(html)
  579. key = _hash_text(html)
  580. self.html_blocks[key] = html
  581. text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:]
  582. if "xml" in self.extras:
  583. # Treat XML processing instructions and namespaced one-liner
  584. # tags as if they were block HTML tags. E.g., if standalone
  585. # (i.e. are their own paragraph), the following do not get
  586. # wrapped in a <p> tag:
  587. # <?foo bar?>
  588. #
  589. # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/>
  590. _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width)
  591. text = _xml_oneliner_re.sub(hash_html_block_sub, text)
  592. return text
  593. def _strip_link_definitions(self, text):
  594. # Strips link definitions from text, stores the URLs and titles in
  595. # hash references.
  596. less_than_tab = self.tab_width - 1
  597. # Link defs are in the form:
  598. # [id]: url "optional title"
  599. _link_def_re = re.compile(r"""
  600. ^[ ]{0,%d}\[(.+)\]: # id = \1
  601. [ \t]*
  602. \n? # maybe *one* newline
  603. [ \t]*
  604. <?(.+?)>? # url = \2
  605. [ \t]*
  606. (?:
  607. \n? # maybe one newline
  608. [ \t]*
  609. (?<=\s) # lookbehind for whitespace
  610. ['"(]
  611. ([^\n]*) # title = \3
  612. ['")]
  613. [ \t]*
  614. )? # title is optional
  615. (?:\n+|\Z)
  616. """ % less_than_tab, re.X | re.M | re.U)
  617. return _link_def_re.sub(self._extract_link_def_sub, text)
  618. def _extract_link_def_sub(self, match):
  619. id, url, title = match.groups()
  620. key = id.lower() # Link IDs are case-insensitive
  621. self.urls[key] = self._encode_amps_and_angles(url)
  622. if title:
  623. self.titles[key] = title
  624. return ""
  625. def _extract_footnote_def_sub(self, match):
  626. id, text = match.groups()
  627. text = _dedent(text, skip_first_line=not text.startswith('\n')).strip()
  628. normed_id = re.sub(r'\W', '-', id)
  629. # Ensure footnote text ends with a couple newlines (for some
  630. # block gamut matches).
  631. self.footnotes[normed_id] = text + "\n\n"
  632. return ""
  633. def _strip_footnote_definitions(self, text):
  634. """A footnote definition looks like this:
  635. [^note-id]: Text of the note.
  636. May include one or more indented paragraphs.
  637. Where,
  638. - The 'note-id' can be pretty much anything, though typically it
  639. is the number of the footnote.
  640. - The first paragraph may start on the next line, like so:
  641. [^note-id]:
  642. Text of the note.
  643. """
  644. less_than_tab = self.tab_width - 1
  645. footnote_def_re = re.compile(r'''
  646. ^[ ]{0,%d}\[\^(.+)\]: # id = \1
  647. [ \t]*
  648. ( # footnote text = \2
  649. # First line need not start with the spaces.
  650. (?:\s*.*\n+)
  651. (?:
  652. (?:[ ]{%d} | \t) # Subsequent lines must be indented.
  653. .*\n+
  654. )*
  655. )
  656. # Lookahead for non-space at line-start, or end of doc.
  657. (?:(?=^[ ]{0,%d}\S)|\Z)
  658. ''' % (less_than_tab, self.tab_width, self.tab_width),
  659. re.X | re.M)
  660. return footnote_def_re.sub(self._extract_footnote_def_sub, text)
  661. _hr_data = [
  662. ('*', re.compile(r"^[ ]{0,3}\*(.*?)$", re.M)),
  663. ('-', re.compile(r"^[ ]{0,3}\-(.*?)$", re.M)),
  664. ('_', re.compile(r"^[ ]{0,3}\_(.*?)$", re.M)),
  665. ]
  666. def _run_block_gamut(self, text):
  667. # These are all the transformations that form block-level
  668. # tags like paragraphs, headers, and list items.
  669. if "fenced-code-blocks" in self.extras:
  670. text = self._do_fenced_code_blocks(text)
  671. text = self._do_headers(text)
  672. # Do Horizontal Rules:
  673. # On the number of spaces in horizontal rules: The spec is fuzzy: "If
  674. # you wish, you may use spaces between the hyphens or asterisks."
  675. # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the
  676. # hr chars to one or two. We'll reproduce that limit here.
  677. hr = "\n<hr"+self.empty_element_suffix+"\n"
  678. for ch, regex in self._hr_data:
  679. if ch in text:
  680. for m in reversed(list(regex.finditer(text))):
  681. tail = m.group(1).rstrip()
  682. if not tail.strip(ch + ' ') and tail.count(" ") == 0:
  683. start, end = m.span()
  684. text = text[:start] + hr + text[end:]
  685. text = self._do_lists(text)
  686. if "pyshell" in self.extras:
  687. text = self._prepare_pyshell_blocks(text)
  688. if "wiki-tables" in self.extras:
  689. text = self._do_wiki_tables(text)
  690. text = self._do_code_blocks(text)
  691. text = self._do_block_quotes(text)
  692. # We already ran _HashHTMLBlocks() before, in Markdown(), but that
  693. # was to escape raw HTML in the original Markdown source. This time,
  694. # we're escaping the markup we've just created, so that we don't wrap
  695. # <p> tags around block-level tags.
  696. text = self._hash_html_blocks(text)
  697. text = self._form_paragraphs(text)
  698. return text
  699. def _pyshell_block_sub(self, match):
  700. lines = match.group(0).splitlines(0)
  701. _dedentlines(lines)
  702. indent = ' ' * self.tab_width
  703. s = ('\n' # separate from possible cuddled paragraph
  704. + indent + ('\n'+indent).join(lines)
  705. + '\n\n')
  706. return s
  707. def _prepare_pyshell_blocks(self, text):
  708. """Ensure that Python interactive shell sessions are put in
  709. code blocks -- even if not properly indented.
  710. """
  711. if ">>>" not in text:
  712. return text
  713. less_than_tab = self.tab_width - 1
  714. _pyshell_block_re = re.compile(r"""
  715. ^([ ]{0,%d})>>>[ ].*\n # first line
  716. ^(\1.*\S+.*\n)* # any number of subsequent lines
  717. ^\n # ends with a blank line
  718. """ % less_than_tab, re.M | re.X)
  719. return _pyshell_block_re.sub(self._pyshell_block_sub, text)
  720. def _wiki_table_sub(self, match):
  721. ttext = match.group(0).strip()
  722. #print 'wiki table: %r' % match.group(0)
  723. rows = []
  724. for line in ttext.splitlines(0):
  725. line = line.strip()[2:-2].strip()
  726. row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)]
  727. rows.append(row)
  728. #pprint(rows)
  729. hlines = ['<table>', '<tbody>']
  730. for row in rows:
  731. hrow = ['<tr>']
  732. for cell in row:
  733. hrow.append('<td>')
  734. hrow.append(self._run_span_gamut(cell))
  735. hrow.append('</td>')
  736. hrow.append('</tr>')
  737. hlines.append(''.join(hrow))
  738. hlines += ['</tbody>', '</table>']
  739. return '\n'.join(hlines) + '\n'
  740. def _do_wiki_tables(self, text):
  741. # Optimization.
  742. if "||" not in text:
  743. return text
  744. less_than_tab = self.tab_width - 1
  745. wiki_table_re = re.compile(r'''
  746. (?:(?<=\n\n)|\A\n?) # leading blank line
  747. ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line
  748. (^\1\|\|.+?\|\|\n)* # any number of subsequent lines
  749. ''' % less_than_tab, re.M | re.X)
  750. return wiki_table_re.sub(self._wiki_table_sub, text)
  751. def _run_span_gamut(self, text):
  752. # These are all the transformations that occur *within* block-level
  753. # tags like paragraphs, headers, and list items.
  754. text = self._do_code_spans(text)
  755. text = self._escape_special_chars(text)
  756. # Process anchor and image tags.
  757. text = self._do_links(text)
  758. # Make links out of things like `<http://example.com/>`
  759. # Must come after _do_links(), because you can use < and >
  760. # delimiters in inline links like [this](<url>).
  761. text = self._do_auto_links(text)
  762. if "link-patterns" in self.extras:
  763. text = self._do_link_patterns(text)
  764. text = self._encode_amps_and_angles(text)
  765. text = self._do_italics_and_bold(text)
  766. if "smarty-pants" in self.extras:
  767. text = self._do_smart_punctuation(text)
  768. # Do hard breaks:
  769. text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text)
  770. return text
  771. # "Sorta" because auto-links are identified as "tag" tokens.
  772. _sorta_html_tokenize_re = re.compile(r"""
  773. (
  774. # tag
  775. </?
  776. (?:\w+) # tag name
  777. (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes
  778. \s*/?>
  779. |
  780. # auto-link (e.g., <http://www.activestate.com/>)
  781. <\w+[^>]*>
  782. |
  783. <!--.*?--> # comment
  784. |
  785. <\?.*?\?> # processing instruction
  786. )
  787. """, re.X)
  788. def _escape_special_chars(self, text):
  789. # Python markdown note: the HTML tokenization here differs from
  790. # that in Markdown.pl, hence the behaviour for subtle cases can
  791. # differ (I believe the tokenizer here does a better job because
  792. # it isn't susceptible to unmatched '<' and '>' in HTML tags).
  793. # Note, however, that '>' is not allowed in an auto-link URL
  794. # here.
  795. escaped = []
  796. is_html_markup = False
  797. for token in self._sorta_html_tokenize_re.split(text):
  798. if is_html_markup:
  799. # Within tags/HTML-comments/auto-links, encode * and _
  800. # so they don't conflict with their use in Markdown for
  801. # italics and strong. We're replacing each such
  802. # character with its corresponding MD5 checksum value;
  803. # this is likely overkill, but it should prevent us from
  804. # colliding with the escape values by accident.
  805. escaped.append(token.replace('*', self._escape_table['*'])
  806. .replace('_', self._escape_table['_']))
  807. else:
  808. escaped.append(self._encode_backslash_escapes(token))
  809. is_html_markup = not is_html_markup
  810. return ''.join(escaped)
  811. def _hash_html_spans(self, text):
  812. # Used for safe_mode.
  813. def _is_auto_link(s):
  814. if ':' in s and self._auto_link_re.match(s):
  815. return True
  816. elif '@' in s and self._auto_email_link_re.match(s):
  817. return True
  818. return False
  819. tokens = []
  820. is_html_markup = False
  821. for token in self._sorta_html_tokenize_re.split(text):
  822. if is_html_markup and not _is_auto_link(token):
  823. sanitized = self._sanitize_html(token)
  824. key = _hash_text(sanitized)
  825. self.html_spans[key] = sanitized
  826. tokens.append(key)
  827. else:
  828. tokens.append(token)
  829. is_html_markup = not is_html_markup
  830. return ''.join(tokens)
  831. def _unhash_html_spans(self, text):
  832. for key, sanitized in list(self.html_spans.items()):
  833. text = text.replace(key, sanitized)
  834. return text
  835. def _sanitize_html(self, s):
  836. if self.safe_mode == "replace":
  837. return self.html_removed_text
  838. elif self.safe_mode == "escape":
  839. replacements = [
  840. ('&', '&amp;'),
  841. ('<', '&lt;'),
  842. ('>', '&gt;'),
  843. ]
  844. for before, after in replacements:
  845. s = s.replace(before, after)
  846. return s
  847. else:
  848. raise MarkdownError("invalid value for 'safe_mode': %r (must be "
  849. "'escape' or 'replace')" % self.safe_mode)
  850. _tail_of_inline_link_re = re.compile(r'''
  851. # Match tail of: [text](/url/) or [text](/url/ "title")
  852. \( # literal paren
  853. [ \t]*
  854. (?P<url> # \1
  855. <.*?>
  856. |
  857. .*?
  858. )
  859. [ \t]*
  860. ( # \2
  861. (['"]) # quote char = \3
  862. (?P<title>.*?)
  863. \3 # matching quote
  864. )? # title is optional
  865. \)
  866. ''', re.X | re.S)
  867. _tail_of_reference_link_re = re.compile(r'''
  868. # Match tail of: [text][id]
  869. [ ]? # one optional space
  870. (?:\n[ ]*)? # one optional newline followed by spaces
  871. \[
  872. (?P<id>.*?)
  873. \]
  874. ''', re.X | re.S)
  875. def _do_links(self, text):
  876. """Turn Markdown link shortcuts into XHTML <a> and <img> tags.
  877. This is a combination of Markdown.pl's _DoAnchors() and
  878. _DoImages(). They are done together because that simplified the
  879. approach. It was necessary to use a different approach than
  880. Markdown.pl because of the lack of atomic matching support in
  881. Python's regex engine used in $g_nested_brackets.
  882. """
  883. MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24
  884. # `anchor_allowed_pos` is used to support img links inside
  885. # anchors, but not anchors inside anchors. An anchor's start
  886. # pos must be `>= anchor_allowed_pos`.
  887. anchor_allowed_pos = 0
  888. curr_pos = 0
  889. while True: # Handle the next link.
  890. # The next '[' is the start of:
  891. # - an inline anchor: [text](url "title")
  892. # - a reference anchor: [text][id]
  893. # - an inline img: ![text](url "title")
  894. # - a reference img: ![text][id]
  895. # - a footnote ref: [^id]
  896. # (Only if 'footnotes' extra enabled)
  897. # - a footnote defn: [^id]: ...
  898. # (Only if 'footnotes' extra enabled) These have already
  899. # been stripped in _strip_footnote_definitions() so no
  900. # need to watch for them.
  901. # - a link definition: [id]: url "title"
  902. # These have already been stripped in
  903. # _strip_link_definitions() so no need to watch for them.
  904. # - not markup: [...anything else...
  905. try:
  906. start_idx = text.index('[', curr_pos)
  907. except ValueError:
  908. break
  909. text_length = len(text)
  910. # Find the matching closing ']'.
  911. # Markdown.pl allows *matching* brackets in link text so we
  912. # will here too. Markdown.pl *doesn't* currently allow
  913. # matching brackets in img alt text -- we'll differ in that
  914. # regard.
  915. bracket_depth = 0
  916. for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL,
  917. text_length)):
  918. ch = text[p]
  919. if ch == ']':
  920. bracket_depth -= 1
  921. if bracket_depth < 0:
  922. break
  923. elif ch == '[':
  924. bracket_depth += 1
  925. else:
  926. # Closing bracket not found within sentinel length.
  927. # This isn't markup.
  928. curr_pos = start_idx + 1
  929. continue
  930. link_text = text[start_idx+1:p]
  931. # Possibly a footnote ref?
  932. if "footnotes" in self.extras and link_text.startswith("^"):
  933. normed_id = re.sub(r'\W', '-', link_text[1:])
  934. if normed_id in self.footnotes:
  935. self.footnote_ids.append(normed_id)
  936. result = '<sup class="footnote-ref" id="fnref-%s">' \
  937. '<a href="#fn-%s">%s</a></sup>' \
  938. % (normed_id, normed_id, len(self.footnote_ids))
  939. text = text[:start_idx] + result + text[p+1:]
  940. else:
  941. # This id isn't defined, leave the markup alone.
  942. curr_pos = p+1
  943. continue
  944. # Now determine what this is by the remainder.
  945. p += 1
  946. if p == text_length:
  947. return text
  948. # Inline anchor or img?
  949. if text[p] == '(': # attempt at perf improvement
  950. match = self._tail_of_inline_link_re.match(text, p)
  951. if match:
  952. # Handle an inline anchor or img.
  953. is_img = start_idx > 0 and text[start_idx-1] == "!"
  954. if is_img:
  955. start_idx -= 1
  956. url, title = match.group("url"), match.group("title")
  957. if url and url[0] == '<':
  958. url = url[1:-1] # '<url>' -> 'url'
  959. # We've got to encode these to avoid conflicting
  960. # with italics/bold.
  961. url = url.replace('*', self._escape_table['*']) \
  962. .replace('_', self._escape_table['_'])
  963. if title:
  964. title_str = ' title="%s"' % (
  965. _xml_escape_attr(title)
  966. .replace('*', self._escape_table['*'])
  967. .replace('_', self._escape_table['_']))
  968. else:
  969. title_str = ''
  970. if is_img:
  971. result = '<img src="%s" alt="%s"%s%s' \
  972. % (url.replace('"', '&quot;'),
  973. _xml_escape_attr(link_text),
  974. title_str, self.empty_element_suffix)
  975. if "smarty-pants" in self.extras:
  976. result = result.replace('"', self._escape_table['"'])
  977. curr_pos = start_idx + len(result)
  978. text = text[:start_idx] + result + text[match.end():]
  979. elif start_idx >= anchor_allowed_pos:
  980. result_head = '<a href="%s"%s>' % (url, title_str)
  981. result = '%s%s</a>' % (result_head, link_text)
  982. if "smarty-pants" in self.extras:
  983. result = result.replace('"', self._escape_table['"'])
  984. # <img> allowed from curr_pos on, <a> from
  985. # anchor_allowed_pos on.
  986. curr_pos = start_idx + len(result_head)
  987. anchor_allowed_pos = start_idx + len(result)
  988. text = text[:start_idx] + result + text[match.end():]
  989. else:
  990. # Anchor not allowed here.
  991. curr_pos = start_idx + 1
  992. continue
  993. # Reference anchor or img?
  994. else:
  995. match = self._tail_of_reference_link_re.match(text, p)
  996. if match:
  997. # Handle a reference-style anchor or img.
  998. is_img = start_idx > 0 and text[start_idx-1] == "!"
  999. if is_img:
  1000. start_idx -= 1
  1001. link_id = match.group("id").lower()
  1002. if not link_id:
  1003. link_id = link_text.lower() # for links like [this][]
  1004. if link_id in self.urls:
  1005. url = self.urls[link_id]
  1006. # We've got to encode these to avoid conflicting
  1007. # with italics/bold.
  1008. url = url.replace('*', self._escape_table['*']) \
  1009. .replace('_', self._escape_table['_'])
  1010. title = self.titles.get(link_id)
  1011. if title:
  1012. before = title
  1013. title = _xml_escape_attr(title) \
  1014. .replace('*', self._escape_table['*']) \
  1015. .replace('_', self._escape_table['_'])
  1016. title_str = ' title="%s"' % title
  1017. else:
  1018. title_str = ''
  1019. if is_img:
  1020. result = '<img src="%s" alt="%s"%s%s' \
  1021. % (url.replace('"', '&quot;'),
  1022. link_text.replace('"', '&quot;'),
  1023. title_str, self.empty_element_suffix)
  1024. if "smarty-pants" in self.extras:
  1025. result = result.replace('"', self._escape_table['"'])
  1026. curr_pos = start_idx + len(result)
  1027. text = text[:start_idx] + result + text[match.end():]
  1028. elif start_idx >= anchor_allowed_pos:
  1029. result = '<a href="%s"%s>%s</a>' \
  1030. % (url, title_str, link_text)
  1031. result_head = '<a href="%s"%s>' % (url, title_str)
  1032. result = '%s%s</a>' % (result_head, link_text)
  1033. if "smarty-pants" in self.extras:
  1034. result = result.replace('"', self._escape_table['"'])
  1035. # <img> allowed from curr_pos on, <a> from
  1036. # anchor_allowed_pos on.
  1037. curr_pos = start_idx + len(result_head)
  1038. anchor_allowed_pos = start_idx + len(result)
  1039. text = text[:start_idx] + result + text[match.end():]
  1040. else:
  1041. # Anchor not allowed here.
  1042. curr_pos = start_idx + 1
  1043. else:
  1044. # This id isn't defined, leave the markup alone.
  1045. curr_pos = match.end()
  1046. continue
  1047. # Otherwise, it isn't markup.
  1048. curr_pos = start_idx + 1
  1049. return text
  1050. def header_id_from_text(self, text, prefix, n):
  1051. """Generate a header id attribute value from the given header
  1052. HTML content.
  1053. This is only called if the "header-ids" extra is enabled.
  1054. Subclasses may override this for different header ids.
  1055. @param text {str} The text of the header tag
  1056. @param prefix {str} The requested prefix for header ids. This is the
  1057. value of the "header-ids" extra key, if any. Otherwise, None.
  1058. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag.
  1059. @returns {str} The value for the header tag's "id" attribute. Return
  1060. None to not have an id attribute and to exclude this header from
  1061. the TOC (if the "toc" extra is specified).
  1062. """
  1063. header_id = _slugify(text)
  1064. if prefix and isinstance(prefix, base_string_type):
  1065. header_id = prefix + '-' + header_id
  1066. if header_id in self._count_from_header_id:
  1067. self._count_from_header_id[header_id] += 1
  1068. header_id += '-%s' % self._count_from_header_id[header_id]
  1069. else:
  1070. self._count_from_hea

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