PageRenderTime 57ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/markdown2.py

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

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