PageRenderTime 65ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/markdown2.py

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