PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/markdown2.py

https://bitbucket.org/abernier/pocasi
Python | 1913 lines | 1692 code | 65 blank | 156 comment | 83 complexity | c5d3a16106503471a0371254d2d73577 MD5 | raw file

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

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