PageRenderTime 75ms CodeModel.GetById 28ms 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
  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. lexer_name = lexer_name[3:].strip()
  1078. lexer = self._get_pygments_lexer(lexer_name)
  1079. codeblock = rest.lstrip("\n") # Remove lexer declaration line.
  1080. if lexer:
  1081. formatter_opts = self.extras['code-color'] or {}
  1082. colored = self._color_with_pygments(codeblock, lexer,
  1083. **formatter_opts)
  1084. return "\n\n%s\n\n" % colored
  1085. codeblock = self._encode_code(codeblock)
  1086. return "\n\n<pre><code>%s\n</code></pre>\n\n" % codeblock
  1087. def _do_code_blocks(self, text):
  1088. """Process Markdown `<pre><code>` blocks."""
  1089. code_block_re = re.compile(r'''
  1090. (?:\n\n|\A)
  1091. ( # $1 = the code block -- one or more lines, starting with a space/tab
  1092. (?:
  1093. (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces
  1094. .*\n+
  1095. )+
  1096. )
  1097. ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  1098. ''' % (self.tab_width, self.tab_width),
  1099. re.M | re.X)
  1100. return code_block_re.sub(self._code_block_sub, text)
  1101. # Rules for a code span:
  1102. # - backslash escapes are not interpreted in a code span
  1103. # - to include one or or a run of more backticks the delimiters must
  1104. # be a longer run of backticks
  1105. # - cannot start or end a code span with a backtick; pad with a
  1106. # space and that space will be removed in the emitted HTML
  1107. # See `test/tm-cases/escapes.text` for a number of edge-case
  1108. # examples.
  1109. _code_span_re = re.compile(r'''
  1110. (?<!\\)
  1111. (`+) # \1 = Opening run of `
  1112. (?!`) # See Note A test/tm-cases/escapes.text
  1113. (.+?) # \2 = The code block
  1114. (?<!`)
  1115. \1 # Matching closer
  1116. (?!`)
  1117. ''', re.X | re.S)
  1118. def _code_span_sub(self, match):
  1119. c = match.group(2).strip(" \t")
  1120. c = self._encode_code(c)
  1121. return "<code>%s</code>" % c
  1122. def _do_code_spans(self, text):
  1123. # * Backtick quotes are used for <code></code> spans.
  1124. #
  1125. # * You can use multiple backticks as the delimiters if you want to
  1126. # include literal backticks in the code span. So, this input:
  1127. #
  1128. # Just type ``foo `bar` baz`` at the prompt.
  1129. #
  1130. # Will translate to:
  1131. #
  1132. # <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  1133. #
  1134. # There's no arbitrary limit to the number of backticks you
  1135. # can use as delimters. If you need three consecutive backticks
  1136. # in your code, use four for delimiters, etc.
  1137. #
  1138. # * You can use spaces to get literal backticks at the edges:
  1139. #
  1140. # ... type `` `bar` `` ...
  1141. #
  1142. # Turns to:
  1143. #
  1144. # ... type <code>`bar`</code> ...
  1145. return self._code_span_re.sub(self._code_span_sub, text)
  1146. def _encode_code(self, text):
  1147. """Encode/escape certain characters inside Markdown code runs.
  1148. The point is that in code, these characters are literals,
  1149. and lose their special Markdown meanings.
  1150. """
  1151. replacements = [
  1152. # Encode all ampersands; HTML entities are not
  1153. # entities within a Markdown code span.
  1154. ('&', '&amp;'),
  1155. # Do the angle bracket song and dance:
  1156. ('<', '&lt;'),
  1157. ('>', '&gt;'),
  1158. # Now, escape characters that are magic in Markdown:
  1159. ('*', g_escape_table['*']),
  1160. ('_', g_escape_table['_']),
  1161. ('{', g_escape_table['{']),
  1162. ('}', g_escape_table['}']),
  1163. ('[', g_escape_table['[']),
  1164. (']', g_escape_table[']']),
  1165. ('\\', g_escape_table['\\']),
  1166. ]
  1167. for before, after in replacements:
  1168. text = text.replace(before, after)
  1169. return text
  1170. _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S)
  1171. _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S)
  1172. _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S)
  1173. _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S)
  1174. def _do_italics_and_bold(self, text):
  1175. # <strong> must go first:
  1176. if "code-friendly" in self.extras:
  1177. text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text)
  1178. text = self._code_friendly_em_re.sub(r"<em>\1</em>", text)
  1179. else:
  1180. text = self._strong_re.sub(r"<strong>\2</strong>", text)
  1181. text = self._em_re.sub(r"<em>\2</em>", text)
  1182. return text
  1183. _block_quote_re = re.compile(r'''
  1184. ( # Wrap whole match in \1
  1185. (
  1186. ^[ \t]*>[ \t]? # '>' at the start of a line
  1187. .+\n # rest of the first line
  1188. (.+\n)* # subsequent consecutive lines
  1189. \n* # blanks
  1190. )+
  1191. )
  1192. ''', re.M | re.X)
  1193. _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M);
  1194. _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S)
  1195. def _dedent_two_spaces_sub(self, match):
  1196. return re.sub(r'(?m)^ ', '', match.group(1))
  1197. def _block_quote_sub(self, match):
  1198. bq = match.group(1)
  1199. bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting
  1200. bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines
  1201. bq = self._run_block_gamut(bq) # recurse
  1202. bq = re.sub('(?m)^', ' ', bq)
  1203. # These leading spaces screw with <pre> content, so we need to fix that:
  1204. bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq)
  1205. return "<blockquote>\n%s\n</blockquote>\n\n" % bq
  1206. def _do_block_quotes(self, text):
  1207. if '>' not in text:
  1208. return text
  1209. return self._block_quote_re.sub(self._block_quote_sub, text)
  1210. def _form_paragraphs(self, text):
  1211. # Strip leading and trailing lines:
  1212. text = text.strip('\n')
  1213. # Wrap <p> tags.
  1214. grafs = []
  1215. for i, graf in enumerate(re.split(r"\n{2,}", text)):
  1216. if graf in self.html_blocks:
  1217. # Unhashify HTML blocks
  1218. grafs.append(self.html_blocks[graf])
  1219. else:
  1220. cuddled_list = None
  1221. if "cuddled-lists" in self.extras:
  1222. # Need to put back trailing '\n' for `_list_item_re`
  1223. # match at the end of the paragraph.
  1224. li = self._list_item_re.search(graf + '\n')
  1225. # Two of the same list marker in this paragraph: a likely
  1226. # candidate for a list cuddled to preceding paragraph
  1227. # text (issue 33). Note the `[-1]` is a quick way to
  1228. # consider numeric bullets (e.g. "1." and "2.") to be
  1229. # equal.
  1230. if (li and li.group("next_marker")
  1231. and li.group("marker")[-1] == li.group("next_marker")[-1]):
  1232. start = li.start()
  1233. cuddled_list = self._do_lists(graf[start:]).rstrip("\n")
  1234. assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>")
  1235. graf = graf[:start]
  1236. # Wrap <p> tags.
  1237. graf = self._run_span_gamut(graf)
  1238. grafs.append("<p>" + graf.lstrip(" \t") + "</p>")
  1239. if cuddled_list:
  1240. grafs.append(cuddled_list)
  1241. return "\n\n".join(grafs)
  1242. def _add_footnotes(self, text):
  1243. if self.footnotes:
  1244. footer = [
  1245. '<div class="footnotes">',
  1246. '<hr' + self.empty_element_suffix,
  1247. '<ol>',
  1248. ]
  1249. for i, id in enumerate(self.footnote_ids):
  1250. if i != 0:
  1251. footer.append('')
  1252. footer.append('<li id="fn-%s">' % id)
  1253. footer.append(self._run_block_gamut(self.footnotes[id]))
  1254. backlink = ('<a href="#fnref-%s" '
  1255. 'class="footnoteBackLink" '
  1256. 'title="Jump back to footnote %d in the text.">'
  1257. '&#8617;</a>' % (id, i+1))
  1258. if footer[-1].endswith("</p>"):
  1259. footer[-1] = footer[-1][:-len("</p>")] \
  1260. + '&nbsp;' + backlink + "</p>"
  1261. else:
  1262. footer.append("\n<p>%s</p>" % backlink)
  1263. footer.append('</li>')
  1264. footer.append('</ol>')
  1265. footer.append('</div>')
  1266. return text + '\n\n' + '\n'.join(footer)
  1267. else:
  1268. return text
  1269. # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  1270. # http://bumppo.net/projects/amputator/
  1271. _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)')
  1272. _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I)
  1273. _naked_gt_re = re.compile(r'''(?<![a-z?!/'"-])>''', re.I)
  1274. def _encode_amps_and_angles(self, text):
  1275. # Smart processing for ampersands and angle brackets that need
  1276. # to be encoded.
  1277. text = self._ampersand_re.sub('&amp;', text)
  1278. # Encode naked <'s
  1279. text = self._naked_lt_re.sub('&lt;', text)
  1280. # Encode naked >'s
  1281. # Note: Other markdown implementations (e.g. Markdown.pl, PHP
  1282. # Markdown) don't do this.
  1283. text = self._naked_gt_re.sub('&gt;', text)
  1284. return text
  1285. def _encode_backslash_escapes(self, text):
  1286. for ch, escape in g_escape_table.items():
  1287. text = text.replace("\\"+ch, escape)
  1288. return text
  1289. _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I)
  1290. def _auto_link_sub(self, match):
  1291. g1 = match.group(1)
  1292. return '<a href="%s">%s</a>' % (g1, g1)
  1293. _auto_email_link_re = re.compile(r"""
  1294. <
  1295. (?:mailto:)?
  1296. (
  1297. [-.\w]+
  1298. \@
  1299. [-\w]+(\.[-\w]+)*\.[a-z]+
  1300. )
  1301. >
  1302. """, re.I | re.X | re.U)
  1303. def _auto_email_link_sub(self, match):
  1304. return self._encode_email_address(
  1305. self._unescape_special_chars(match.group(1)))
  1306. def _do_auto_links(self, text):
  1307. text = self._auto_link_re.sub(self._auto_link_sub, text)
  1308. text = self._auto_email_link_re.sub(self._auto_email_link_sub, text)
  1309. return text
  1310. def _encode_email_address(self, addr):
  1311. # Input: an email address, e.g. "foo@example.com"
  1312. #
  1313. # Output: the email address as a mailto link, with each character
  1314. # of the address encoded as either a decimal or hex entity, in
  1315. # the hopes of foiling most address harvesting spam bots. E.g.:
  1316. #
  1317. # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  1318. # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  1319. # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  1320. #
  1321. # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  1322. # mailing list: <http://tinyurl.com/yu7ue>
  1323. chars = [_xml_encode_email_char_at_random(ch)
  1324. for ch in "mailto:" + addr]
  1325. # Strip the mailto: from the visible part.
  1326. addr = '<a href="%s">%s</a>' \
  1327. % (''.join(chars), ''.join(chars[7:]))
  1328. return addr
  1329. def _do_link_patterns(self, text):
  1330. """Caveat emptor: there isn't much guarding against link
  1331. patterns being formed inside other standard Markdown links, e.g.
  1332. inside a [link def][like this].
  1333. Dev Notes: *Could* consider prefixing regexes with a negative
  1334. lookbehind assertion to attempt to guard against this.
  1335. """
  1336. link_from_hash = {}
  1337. for regex, repl in self.link_patterns:
  1338. replacements = []
  1339. for match in regex.finditer(text):
  1340. if hasattr(repl, "__call__"):
  1341. href = repl(match)
  1342. else:
  1343. href = match.expand(repl)
  1344. replacements.append((match.span(), href))
  1345. for (start, end), href in reversed(replacements):
  1346. escaped_href = (
  1347. href.replace('"', '&quot;') # b/c of attr quote
  1348. # To avoid markdown <em> and <strong>:
  1349. .replace('*', g_escape_table['*'])
  1350. .replace('_', g_escape_table['_']))
  1351. link = '<a href="%s">%s</a>' % (escaped_href, text[start:end])
  1352. hash = _hash_text(link)
  1353. link_from_hash[hash] = link
  1354. text = text[:start] + hash + text[end:]
  1355. for hash, link in link_from_hash.items():
  1356. text = text.replace(hash, link)
  1357. return text
  1358. def _unescape_special_chars(self, text):
  1359. # Swap back in all the special characters we've hidden.
  1360. for ch, hash in g_escape_table.items():
  1361. text = text.replace(hash, ch)
  1362. return text
  1363. def _outdent(self, text):
  1364. # Remove one level of line-leading tabs or spaces
  1365. return self._outdent_re.sub('', text)
  1366. class MarkdownWithExtras(Markdown):
  1367. """A markdowner class that enables most extras:
  1368. - footnotes
  1369. - code-color (only has effect if 'pygments' Python module on path)
  1370. These are not included:
  1371. - pyshell (specific to Python-related documenting)
  1372. - code-friendly (because it *disables* part of the syntax)
  1373. - link-patterns (because you need to specify some actual
  1374. link-patterns anyway)
  1375. """
  1376. extras = ["footnotes", "code-color"]
  1377. #---- internal support functions
  1378. # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
  1379. def _curry(*args, **kwargs):
  1380. function, args = args[0], args[1:]
  1381. def result(*rest, **kwrest):
  1382. combined = kwargs.copy()
  1383. combined.update(kwrest)
  1384. return function(*args + rest, **combined)
  1385. return result
  1386. # Recipe: regex_from_encoded_pattern (1.0)
  1387. def _regex_from_encoded_pattern(s):
  1388. """'foo' -> re.compile(re.escape('foo'))
  1389. '/foo/' -> re.compile('foo')
  1390. '/foo/i' -> re.compile('foo', re.I)
  1391. """
  1392. if s.startswith('/') and s.rfind('/') != 0:
  1393. # Parse it: /PATTERN/FLAGS
  1394. idx = s.rfind('/')
  1395. pattern, flags_str = s[1:idx], s[idx+1:]
  1396. flag_from_char = {
  1397. "i": re.IGNORECASE,
  1398. "l": re.LOCALE,
  1399. "s": re.DOTALL,
  1400. "m": re.MULTILINE,
  1401. "u": re.UNICODE,
  1402. }
  1403. flags = 0
  1404. for char in flags_str:
  1405. try:
  1406. flags |= flag_from_char[char]
  1407. except KeyError:
  1408. raise ValueError("unsupported regex flag: '%s' in '%s' "
  1409. "(must be one of '%s')"
  1410. % (char, s, ''.join(flag_from_char.keys())))
  1411. return re.compile(s[1:idx], flags)
  1412. else: # not an encoded regex
  1413. return re.compile(re.escape(s))
  1414. # Recipe: dedent (0.1.2)
  1415. def _dedentlines(lines, tabsize=8, skip_first_line=False):
  1416. """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
  1417. "lines" is a list of lines to dedent.
  1418. "tabsize" is the tab width to use for indent width calculations.
  1419. "skip_first_line" is a boolean indicating if the first line should
  1420. be skipped for calculating the indent width and for dedenting.
  1421. This is sometimes useful for docstrings and similar.
  1422. Same as dedent() except operates on a sequence of lines. Note: the
  1423. lines list is modified **in-place**.
  1424. """
  1425. DEBUG = False
  1426. if DEBUG:
  1427. print "dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\
  1428. % (tabsize, skip_first_line)
  1429. indents = []
  1430. margin = None
  1431. for i, line in enumerate(lines):
  1432. if i == 0 and skip_first_line: continue
  1433. indent = 0
  1434. for ch in line:
  1435. if ch == ' ':
  1436. indent += 1
  1437. elif ch == '\t':
  1438. indent += tabsize - (indent % tabsize)
  1439. elif ch in '\r\n':
  1440. continue # skip all-whitespace lines
  1441. else:
  1442. break
  1443. else:
  1444. continue # skip all-whitespace lines
  1445. if DEBUG: print "dedent: indent=%d: %r" % (indent, line)
  1446. if margin is None:
  1447. margin = indent
  1448. else:
  1449. margin = min(margin, indent)
  1450. if DEBUG: print "dedent: margin=%r" % margin
  1451. if margin is not None and margin > 0:
  1452. for i, line in enumerate(lines):
  1453. if i == 0 and skip_first_line: continue
  1454. removed = 0
  1455. for j, ch in enumerate(line):
  1456. if ch == ' ':
  1457. removed += 1
  1458. elif ch == '\t':
  1459. removed += tabsize - (removed % tabsize)
  1460. elif ch in '\r\n':
  1461. if DEBUG: print "dedent: %r: EOL -> strip up to EOL" % line
  1462. lines[i] = lines[i][j:]
  1463. break
  1464. else:
  1465. raise ValueError("unexpected non-whitespace char %r in "
  1466. "line %r while removing %d-space margin"
  1467. % (ch, line, margin))
  1468. if DEBUG:
  1469. print "dedent: %r: %r -> removed %d/%d"\
  1470. % (line, ch, removed, margin)
  1471. if removed == margin:
  1472. lines[i] = lines[i][j+1:]
  1473. break
  1474. elif removed > margin:
  1475. lines[i] = ' '*(removed-margin) + lines[i][j+1:]
  1476. break
  1477. else:
  1478. if removed:
  1479. lines[i] = lines[i][removed:]
  1480. return lines
  1481. def _dedent(text, tabsize=8, skip_first_line=False):
  1482. """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
  1483. "text" is the text to dedent.
  1484. "tabsize" is the tab width to use for indent width calculations.
  1485. "skip_first_line" is a boolean indicating if the first line should
  1486. be skipped for calculating the indent width and for dedenting.
  1487. This is sometimes useful for docstrings and similar.
  1488. textwrap.dedent(s), but don't expand tabs to spaces
  1489. """
  1490. lines = text.splitlines(1)
  1491. _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)
  1492. return ''.join(lines)
  1493. class _memoized(object):
  1494. """Decorator that caches a function's return value each time it is called.
  1495. If called later with the same arguments, the cached value is returned, and
  1496. not re-evaluated.
  1497. http://wiki.python.org/moin/PythonDecoratorLibrary
  1498. """
  1499. def __init__(self, func):
  1500. self.func = func
  1501. self.cache = {}
  1502. def __call__(self, *args):
  1503. try:
  1504. return self.cache[args]
  1505. except KeyError:
  1506. self.cache[args] = value = self.func(*args)
  1507. return value
  1508. except TypeError:
  1509. # uncachable -- for instance, passing a list as an argument.
  1510. # Better to not cache than to blow up entirely.
  1511. return self.func(*args)
  1512. def __repr__(self):
  1513. """Return the function's docstring."""
  1514. return self.func.__doc__
  1515. def _xml_oneliner_re_from_tab_width(tab_width):
  1516. """Standalone XML processing instruction regex."""
  1517. return re.compile(r"""
  1518. (?:
  1519. (?<=\n\n) # Starting after a blank line
  1520. | # or
  1521. \A\n? # the beginning of the doc
  1522. )
  1523. ( # save in $1
  1524. [ ]{0,%d}
  1525. (?:
  1526. <\?\w+\b\s+.*?\?> # XML processing instruction
  1527. |
  1528. <\w+:\w+\b\s+.*?/> # namespaced single tag
  1529. )
  1530. [ \t]*
  1531. (?=\n{2,}|\Z) # followed by a blank line or end of document
  1532. )
  1533. """ % (tab_width - 1), re.X)
  1534. _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width)
  1535. def _hr_tag_re_from_tab_width(tab_width):
  1536. return re.compile(r"""
  1537. (?:
  1538. (?<=\n\n) # Starting after a blank line
  1539. | # or
  1540. \A\n? # the beginning of the doc
  1541. )
  1542. ( # save in \1
  1543. [ ]{0,%d}
  1544. <(hr) # start tag = \2
  1545. \b # word break
  1546. ([^<>])*? #
  1547. /?> # the matching end tag
  1548. [ \t]*
  1549. (?=\n{2,}|\Z) # followed by a blank line or end of document
  1550. )
  1551. """ % (tab_width - 1), re.X)
  1552. _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width)
  1553. def _xml_encode_email_char_at_random(ch):
  1554. r = random()
  1555. # Roughly 10% raw, 45% hex, 45% dec.
  1556. # '@' *must* be encoded. I [John Gruber] insist.
  1557. # Issue 26: '_' must be encoded.
  1558. if r > 0.9 and ch not in "@_":
  1559. return ch
  1560. elif r < 0.45:
  1561. # The [1:] is to drop leading '0': 0x63 -> x63
  1562. return '&#%s;' % hex(ord(ch))[1:]
  1563. else:
  1564. return '&#%s;' % ord(ch)
  1565. #---- mainline
  1566. class _NoReflowFormatter(optparse.IndentedHelpFormatter):
  1567. """An optparse formatter that does NOT reflow the description."""
  1568. def format_description(self, description):
  1569. return description or ""
  1570. def _test():
  1571. import doctest
  1572. doctest.testmod()
  1573. def main(argv=None):
  1574. if argv is None:
  1575. argv = sys.argv
  1576. if not logging.root.handlers:
  1577. logging.basicConfig()
  1578. usage = "usage: %prog [PATHS...]"
  1579. version = "%prog "+__version__
  1580. parser = optparse.OptionParser(prog="markdown2", usage=usage,
  1581. version=version, description=cmdln_desc,
  1582. formatter=_NoReflowFormatter())
  1583. parser.add_option("-v", "--verbose", dest="log_level",
  1584. action="store_const", const=logging.DEBUG,
  1585. help="more verbose output")
  1586. parser.add_option("--encoding",
  1587. help="specify encoding of text content")
  1588. parser.add_option("--html4tags", action="store_true", default=False,
  1589. help="use HTML 4 style for empty element tags")
  1590. parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode",
  1591. help="sanitize literal HTML: 'escape' escapes "
  1592. "HTML meta chars, 'replace' replaces with an "
  1593. "[HTML_REMOVED] note")
  1594. parser.add_option("-x", "--extras", action="append",
  1595. help="Turn on specific extra features (not part of "
  1596. "the core Markdown spec). See above.")
  1597. parser.add_option("--use-file-vars",
  1598. help="Look for and use Emacs-style 'markdown-extras' "
  1599. "file var to turn on extras. See "
  1600. "<http://code.google.com/p/python-markdown2/wiki/Extras>.")
  1601. parser.add_option("--link-patterns-file",
  1602. help="path to a link pattern file")
  1603. parser.add_option("--self-test", action="store_true",
  1604. help="run internal self-tests (some doctests)")
  1605. parser.add_option("--compare", action="store_true",
  1606. help="run against Markdown.pl as well (for testing)")
  1607. parser.set_defaults(log_level=logging.INFO, compare=False,
  1608. encoding="utf-8", safe_mode=None, use_file_vars=False)
  1609. opts, paths = parser.parse_args()
  1610. log.setLevel(opts.log_level)
  1611. if opts.self_test:
  1612. return _test()
  1613. if opts.extras:
  1614. extras = {}
  1615. for s in opts.extras:
  1616. splitter = re.compile("[,;: ]+")
  1617. for e in splitter.split(s):
  1618. if '=' in e:
  1619. ename, earg = e.split('=', 1)
  1620. try:
  1621. earg = int(earg)
  1622. except ValueError:
  1623. pass
  1624. else:
  1625. ename, earg = e, None
  1626. extras[ename] = earg
  1627. else:
  1628. extras = None
  1629. if opts.link_patterns_file:
  1630. link_patterns = []
  1631. f = open(opts.link_patterns_file)
  1632. try:
  1633. for i, line in enumerate(f.readlines()):
  1634. if not line.strip(): continue
  1635. if line.lstrip().startswith("#"): continue
  1636. try:
  1637. pat, href = line.rstrip().rsplit(None, 1)
  1638. except ValueError:
  1639. raise MarkdownError("%s:%d: invalid link pattern line: %r"
  1640. % (opts.link_patterns_file, i+1, line))
  1641. link_patterns.append(
  1642. (_regex_from_encoded_pattern(pat), href))
  1643. finally:
  1644. f.close()
  1645. else:
  1646. link_patterns = None
  1647. from os.path import join, dirname, abspath, exists
  1648. markdown_pl = join(dirname(dirname(abspath(__file__))), "test",
  1649. "Markdown.pl")
  1650. for path in paths:
  1651. if opts.compare:
  1652. print "==== Markdown.pl ===="
  1653. perl_cmd = 'perl %s "%s"' % (markdown_pl, path)
  1654. o = os.popen(perl_cmd)
  1655. perl_html = o.read()
  1656. o.close()
  1657. sys.stdout.write(perl_html)
  1658. print "==== markdown2.py ===="
  1659. html = markdown_path(path, encoding=opts.encoding,
  1660. html4tags=opts.html4tags,
  1661. safe_mode=opts.safe_mode,
  1662. extras=extras, link_patterns=link_patterns,
  1663. use_file_vars=opts.use_file_vars)
  1664. sys.stdout.write(
  1665. html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace'))
  1666. if opts.compare:
  1667. test_dir = join(dirname(dirname(abspath(__file__))), "test")
  1668. if exists(join(test_dir, "test_markdown2.py")):
  1669. sys.path.insert(0, test_dir)
  1670. from test_markdown2 import norm_html_from_html
  1671. norm_html = norm_html_from_html(html)
  1672. norm_perl_html = norm_html_from_html(perl_html)
  1673. else:
  1674. norm_html = html
  1675. norm_perl_html = perl_html
  1676. print "==== match? %r ====" % (norm_perl_html == norm_html)
  1677. if __name__ == "__main__":
  1678. sys.exit( main(sys.argv) )