PageRenderTime 74ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/couchit/contrib/markdown2.py

https://bitbucket.org/benoitc/couchit/
Python | 2009 lines | 1846 code | 44 blank | 119 comment | 61 complexity | 349a8645787f04f42b27e1c8acb522d1 MD5 | raw file
Possible License(s): 0BSD
  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. """
  32. # Dev Notes:
  33. # - There is already a Python markdown processor
  34. # (http://www.freewisdom.org/projects/python-markdown/).
  35. # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm
  36. # not yet sure if there implications with this. Compare 'pydoc sre'
  37. # and 'perldoc perlre'.
  38. __version_info__ = (1, 0, 1, 11, 'a') # first three nums match Markdown.pl
  39. __version__ = '1.0.1.11a'
  40. __author__ = "Trent Mick"
  41. import os
  42. import sys
  43. from pprint import pprint
  44. import re
  45. import logging
  46. try:
  47. from hashlib import md5
  48. except ImportError:
  49. from md5 import md5
  50. import optparse
  51. from random import random
  52. import codecs
  53. from couchit.utils import smart_str
  54. #---- Python version compat
  55. if sys.version_info[:2] < (2,4):
  56. from sets import Set as set
  57. def reversed(sequence):
  58. for i in sequence[::-1]:
  59. yield i
  60. def _unicode_decode(s, encoding, errors='xmlcharrefreplace'):
  61. return unicode(s, encoding, errors)
  62. else:
  63. def _unicode_decode(s, encoding, errors='strict'):
  64. return s.decode(encoding, errors)
  65. #---- globals
  66. DEBUG = False
  67. log = logging.getLogger("markdown")
  68. DEFAULT_TAB_WIDTH = 4
  69. # Table of hash values for escaped characters:
  70. def _escape_hash(s):
  71. # Lame attempt to avoid possible collision with someone actually
  72. # using the MD5 hexdigest of one of these chars in there text.
  73. # Other ideas: random.random(), uuid.uuid()
  74. #return md5(s).hexdigest() # Markdown.pl effectively does this.
  75. return 'md5:'+md5(s).hexdigest()
  76. g_escape_table = dict([(ch, _escape_hash(ch))
  77. for ch in '\\`*_{}[]()>#+-.!'])
  78. #---- exceptions
  79. class MarkdownError(Exception):
  80. pass
  81. # ------------------ The Main CodeHilite Class ----------------------
  82. class CodeHilite:
  83. """
  84. Determine language of source code, and pass it into the pygments hilighter.
  85. Basic Usage:
  86. >>> code = CodeHilite(src = text)
  87. >>> html = code.hilite()
  88. * src: Source string or any object with a .readline attribute.
  89. * linenos: (Boolen) Turn line numbering 'on' or 'off' (off by default).
  90. * css_class: Set class name of wrapper div ('codehilite' by default).
  91. Low Level Usage:
  92. >>> code = CodeHilite()
  93. >>> code.src = text # String or anything with a .readline attribute
  94. >>> code.linenos = True # True or False; Turns line numbering on or of.
  95. >>> html = code.hilite()
  96. """
  97. def __init__(self, src=None, linenos=False, css_class="codehilite"):
  98. self.src = src
  99. self.lang = None
  100. self.linenos = linenos
  101. self.css_class = css_class
  102. def hilite(self):
  103. """
  104. Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with
  105. optional line numbers. The output should then be styled with css to
  106. your liking. No styles are applied by default - only styling hooks
  107. (i.e.: <span class="k">).
  108. returns : A string of html.
  109. """
  110. self.src = self.src.strip('\n')
  111. self._getLang()
  112. try:
  113. from pygments import highlight
  114. from pygments.lexers import get_lexer_by_name, guess_lexer, \
  115. TextLexer
  116. from pygments.formatters import HtmlFormatter
  117. except ImportError:
  118. # just escape and pass through
  119. txt = self._escape(self.src)
  120. if self.linenos:
  121. txt = self._number(txt)
  122. else :
  123. txt = '<div class="%s"><pre>%s</pre></div>\n'% \
  124. (self.css_class, txt)
  125. return txt
  126. else:
  127. try:
  128. lexer = get_lexer_by_name(self.lang)
  129. except ValueError:
  130. try:
  131. lexer = guess_lexer(self.src)
  132. except ValueError:
  133. lexer = TextLexer()
  134. formatter = HtmlFormatter(linenos=self.linenos,
  135. cssclass=self.css_class)
  136. return highlight(self.src, lexer, formatter)
  137. def _escape(self, txt):
  138. """ basic html escaping """
  139. txt = txt.replace('&', '&amp;')
  140. txt = txt.replace('<', '&lt;')
  141. txt = txt.replace('>', '&gt;')
  142. txt = txt.replace('"', '&quot;')
  143. return txt
  144. def _number(self, txt):
  145. """ Use <ol> for line numbering """
  146. # Fix Whitespace
  147. txt = txt.replace('\t', ' '*TAB_LENGTH)
  148. txt = txt.replace(" "*4, "&nbsp; &nbsp; ")
  149. txt = txt.replace(" "*3, "&nbsp; &nbsp;")
  150. txt = txt.replace(" "*2, "&nbsp; ")
  151. # Add line numbers
  152. lines = txt.splitlines()
  153. txt = '<div class="codehilite"><pre><ol>\n'
  154. for line in lines:
  155. txt += '\t<li>%s</li>\n'% line
  156. txt += '</ol></pre></div>\n'
  157. return txt
  158. def _getLang(self):
  159. """
  160. Determines language of a code block from shebang lines and whether said
  161. line should be removed or left in place. If the sheband line contains a
  162. path (even a single /) then it is assumed to be a real shebang lines and
  163. left alone. However, if no path is given (e.i.: #!python or :::python)
  164. then it is assumed to be a mock shebang for language identifitation of a
  165. code fragment and removed from the code block prior to processing for
  166. code highlighting. When a mock shebang (e.i: #!python) is found, line
  167. numbering is turned on. When colons are found in place of a shebang
  168. (e.i.: :::python), line numbering is left in the current state - off
  169. by default.
  170. """
  171. import re
  172. #split text into lines
  173. lines = self.src.split("\n")
  174. #pull first line to examine
  175. fl = lines.pop(0)
  176. c = re.compile(r'''
  177. (?:(?:::+)|(?P<shebang>[#]!)) # Shebang or 2 or more colons.
  178. (?P<path>(?:/\w+)*[/ ])? # Zero or 1 path
  179. (?P<lang>[\w+-]*) # The language
  180. ''', re.VERBOSE)
  181. # search first line for shebang
  182. m = c.search(fl)
  183. if m:
  184. # we have a match
  185. try:
  186. self.lang = m.group('lang').lower()
  187. except IndexError:
  188. self.lang = None
  189. if m.group('path'):
  190. # path exists - restore first line
  191. lines.insert(0, fl)
  192. if m.group('shebang'):
  193. # shebang exists - use line numbers
  194. self.linenos = True
  195. else:
  196. # No match
  197. lines.insert(0, fl)
  198. self.src = "\n".join(lines).strip("\n")
  199. #---- public api
  200. def markdown_path(path, encoding="utf-8",
  201. html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
  202. safe_mode=None, extras=None, link_patterns=None,
  203. use_file_vars=False):
  204. text = codecs.open(path, 'r', encoding).read()
  205. return Markdown(html4tags=html4tags, tab_width=tab_width,
  206. safe_mode=safe_mode, extras=extras,
  207. link_patterns=link_patterns,
  208. use_file_vars=use_file_vars).convert(text)
  209. def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
  210. safe_mode=None, extras=None, link_patterns=None,
  211. use_file_vars=False):
  212. return Markdown(html4tags=html4tags, tab_width=tab_width,
  213. safe_mode=safe_mode, extras=extras,
  214. link_patterns=link_patterns,
  215. use_file_vars=use_file_vars).convert(text)
  216. class Markdown(object):
  217. # The dict of "extras" to enable in processing -- a mapping of
  218. # extra name to argument for the extra. Most extras do not have an
  219. # argument, in which case the value is None.
  220. #
  221. # This can be set via (a) subclassing and (b) the constructor
  222. # "extras" argument.
  223. extras = None
  224. urls = None
  225. titles = None
  226. html_blocks = None
  227. html_spans = None
  228. html_removed_text = "[HTML_REMOVED]" # for compat with markdown.py
  229. # Used to track when we're inside an ordered or unordered list
  230. # (see _ProcessListItems() for details):
  231. list_level = 0
  232. _ws_only_line_re = re.compile(r"^[ \t]+$", re.M)
  233. def __init__(self, html4tags=False, tab_width=4, safe_mode=None,
  234. extras=None, link_patterns=None, use_file_vars=False, codehilite=None):
  235. if html4tags:
  236. self.empty_element_suffix = ">"
  237. else:
  238. self.empty_element_suffix = " />"
  239. self.tab_width = tab_width
  240. # For compatibility with earlier markdown2.py and with
  241. # markdown.py's safe_mode being a boolean,
  242. # safe_mode == True -> "replace"
  243. if safe_mode is True:
  244. self.safe_mode = "replace"
  245. else:
  246. self.safe_mode = safe_mode
  247. if self.extras is None:
  248. self.extras = {}
  249. elif not isinstance(self.extras, dict):
  250. self.extras = dict([(e, None) for e in self.extras])
  251. if extras:
  252. if not isinstance(extras, dict):
  253. extras = dict([(e, None) for e in extras])
  254. self.extras.update(extras)
  255. assert isinstance(self.extras, dict)
  256. self._instance_extras = self.extras.copy()
  257. self.link_patterns = link_patterns
  258. self.use_file_vars = use_file_vars
  259. self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M)
  260. self.codehilite = codehilite or {}
  261. def reset(self):
  262. self.urls = {}
  263. self.titles = {}
  264. self.html_blocks = {}
  265. self.html_spans = {}
  266. self.list_level = 0
  267. self.extras = self._instance_extras.copy()
  268. if "footnotes" in self.extras:
  269. self.footnotes = {}
  270. self.footnote_ids = []
  271. def convert(self, text):
  272. """Convert the given text."""
  273. # Main function. The order in which other subs are called here is
  274. # essential. Link and image substitutions need to happen before
  275. # _EscapeSpecialChars(), so that any *'s or _'s in the <a>
  276. # and <img> tags get encoded.
  277. # Clear the global hashes. If we don't clear these, you get conflicts
  278. # from other articles when generating a page which contains more than
  279. # one article (e.g. an index page that shows the N most recent
  280. # articles):
  281. self.reset()
  282. if not isinstance(text, unicode):
  283. #TODO: perhaps shouldn't presume UTF-8 for string input?
  284. text = unicode(text, 'utf-8')
  285. if self.use_file_vars:
  286. # Look for emacs-style file variable hints.
  287. emacs_vars = self._get_emacs_vars(text)
  288. if "markdown-extras" in emacs_vars:
  289. splitter = re.compile("[ ,]+")
  290. for e in splitter.split(emacs_vars["markdown-extras"]):
  291. if '=' in e:
  292. ename, earg = e.split('=', 1)
  293. try:
  294. earg = int(earg)
  295. except ValueError:
  296. pass
  297. else:
  298. ename, earg = e, None
  299. self.extras[ename] = earg
  300. # Standardize line endings:
  301. text = re.sub("\r\n|\r", "\n", text)
  302. # Make sure $text ends with a couple of newlines:
  303. text += "\n\n"
  304. # Convert all tabs to spaces.
  305. text = self._detab(text)
  306. # Strip any lines consisting only of spaces and tabs.
  307. # This makes subsequent regexen easier to write, because we can
  308. # match consecutive blank lines with /\n+/ instead of something
  309. # contorted like /[ \t]*\n+/ .
  310. text = self._ws_only_line_re.sub("", text)
  311. if self.safe_mode:
  312. text = self._hash_html_spans(text)
  313. # Turn block-level HTML blocks into hash entries
  314. text = self._hash_html_blocks(text, raw=True)
  315. # Strip link definitions, store in hashes.
  316. if "footnotes" in self.extras:
  317. # Must do footnotes first because an unlucky footnote defn
  318. # looks like a link defn:
  319. # [^4]: this "looks like a link defn"
  320. text = self._strip_footnote_definitions(text)
  321. text = self._strip_link_definitions(text)
  322. text = self._run_block_gamut(text)
  323. text = self._unescape_special_chars(text)
  324. if "footnotes" in self.extras:
  325. text = self._add_footnotes(text)
  326. if self.safe_mode:
  327. text = self._unhash_html_spans(text)
  328. text += "\n"
  329. return text
  330. _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*([^\r\n]*?)\s*-\*-", re.UNICODE)
  331. # This regular expression is intended to match blocks like this:
  332. # PREFIX Local Variables: SUFFIX
  333. # PREFIX mode: Tcl SUFFIX
  334. # PREFIX End: SUFFIX
  335. # Some notes:
  336. # - "[ \t]" is used instead of "\s" to specifically exclude newlines
  337. # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does
  338. # not like anything other than Unix-style line terminators.
  339. _emacs_local_vars_pat = re.compile(r"""^
  340. (?P<prefix>(?:[^\r\n|\n|\r])*?)
  341. [\ \t]*Local\ Variables:[\ \t]*
  342. (?P<suffix>.*?)(?:\r\n|\n|\r)
  343. (?P<content>.*?\1End:)
  344. """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)
  345. def _get_emacs_vars(self, text):
  346. """Return a dictionary of emacs-style local variables.
  347. Parsing is done loosely according to this spec (and according to
  348. some in-practice deviations from this):
  349. http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables
  350. """
  351. emacs_vars = {}
  352. SIZE = pow(2, 13) # 8kB
  353. # Search near the start for a '-*-'-style one-liner of variables.
  354. head = text[:SIZE]
  355. if "-*-" in head:
  356. match = self._emacs_oneliner_vars_pat.search(head)
  357. if match:
  358. emacs_vars_str = match.group(1)
  359. assert '\n' not in emacs_vars_str
  360. emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';')
  361. if s.strip()]
  362. if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]:
  363. # While not in the spec, this form is allowed by emacs:
  364. # -*- Tcl -*-
  365. # where the implied "variable" is "mode". This form
  366. # is only allowed if there are no other variables.
  367. emacs_vars["mode"] = emacs_var_strs[0].strip()
  368. else:
  369. for emacs_var_str in emacs_var_strs:
  370. try:
  371. variable, value = emacs_var_str.strip().split(':', 1)
  372. except ValueError:
  373. log.debug("emacs variables error: malformed -*- "
  374. "line: %r", emacs_var_str)
  375. continue
  376. # Lowercase the variable name because Emacs allows "Mode"
  377. # or "mode" or "MoDe", etc.
  378. emacs_vars[variable.lower()] = value.strip()
  379. tail = text[-SIZE:]
  380. if "Local Variables" in tail:
  381. match = self._emacs_local_vars_pat.search(tail)
  382. if match:
  383. prefix = match.group("prefix")
  384. suffix = match.group("suffix")
  385. lines = match.group("content").splitlines(0)
  386. #print "prefix=%r, suffix=%r, content=%r, lines: %s"\
  387. # % (prefix, suffix, match.group("content"), lines)
  388. # Validate the Local Variables block: proper prefix and suffix
  389. # usage.
  390. for i, line in enumerate(lines):
  391. if not line.startswith(prefix):
  392. log.debug("emacs variables error: line '%s' "
  393. "does not use proper prefix '%s'"
  394. % (line, prefix))
  395. return {}
  396. # Don't validate suffix on last line. Emacs doesn't care,
  397. # neither should we.
  398. if i != len(lines)-1 and not line.endswith(suffix):
  399. log.debug("emacs variables error: line '%s' "
  400. "does not use proper suffix '%s'"
  401. % (line, suffix))
  402. return {}
  403. # Parse out one emacs var per line.
  404. continued_for = None
  405. for line in lines[:-1]: # no var on the last line ("PREFIX End:")
  406. if prefix: line = line[len(prefix):] # strip prefix
  407. if suffix: line = line[:-len(suffix)] # strip suffix
  408. line = line.strip()
  409. if continued_for:
  410. variable = continued_for
  411. if line.endswith('\\'):
  412. line = line[:-1].rstrip()
  413. else:
  414. continued_for = None
  415. emacs_vars[variable] += ' ' + line
  416. else:
  417. try:
  418. variable, value = line.split(':', 1)
  419. except ValueError:
  420. log.debug("local variables error: missing colon "
  421. "in local variables entry: '%s'" % line)
  422. continue
  423. # Do NOT lowercase the variable name, because Emacs only
  424. # allows "mode" (and not "Mode", "MoDe", etc.) in this block.
  425. value = value.strip()
  426. if value.endswith('\\'):
  427. value = value[:-1].rstrip()
  428. continued_for = variable
  429. else:
  430. continued_for = None
  431. emacs_vars[variable] = value
  432. # Unquote values.
  433. for var, val in emacs_vars.items():
  434. if len(val) > 1 and (val.startswith('"') and val.endswith('"')
  435. or val.startswith('"') and val.endswith('"')):
  436. emacs_vars[var] = val[1:-1]
  437. return emacs_vars
  438. # Cribbed from a post by Bart Lateur:
  439. # <http://www.nntp.perl.org/group/perl.macperl.anyperl/154>
  440. _detab_re = re.compile(r'(.*?)\t', re.M)
  441. def _detab_sub(self, match):
  442. g1 = match.group(1)
  443. return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width))
  444. def _detab(self, text):
  445. r"""Remove (leading?) tabs from a file.
  446. >>> m = Markdown()
  447. >>> m._detab("\tfoo")
  448. ' foo'
  449. >>> m._detab(" \tfoo")
  450. ' foo'
  451. >>> m._detab("\t foo")
  452. ' foo'
  453. >>> m._detab(" foo")
  454. ' foo'
  455. >>> m._detab(" foo\n\tbar\tblam")
  456. ' foo\n bar blam'
  457. """
  458. if '\t' not in text:
  459. return text
  460. return self._detab_re.subn(self._detab_sub, text)[0]
  461. _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del'
  462. _strict_tag_block_re = re.compile(r"""
  463. ( # save in \1
  464. ^ # start of line (with re.M)
  465. <(%s) # start tag = \2
  466. \b # word break
  467. (.*\n)*? # any number of lines, minimally matching
  468. </\2> # the matching end tag
  469. [ \t]* # trailing spaces/tabs
  470. (?=\n+|\Z) # followed by a newline or end of document
  471. )
  472. """ % _block_tags_a,
  473. re.X | re.M)
  474. _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math'
  475. _liberal_tag_block_re = re.compile(r"""
  476. ( # save in \1
  477. ^ # start of line (with re.M)
  478. <(%s) # start tag = \2
  479. \b # word break
  480. (.*\n)*? # any number of lines, minimally matching
  481. .*</\2> # the matching end tag
  482. [ \t]* # trailing spaces/tabs
  483. (?=\n+|\Z) # followed by a newline or end of document
  484. )
  485. """ % _block_tags_b,
  486. re.X | re.M)
  487. def _hash_html_block_sub(self, match, raw=False):
  488. html = match.group(1)
  489. if raw and self.safe_mode:
  490. html = self._sanitize_html(html)
  491. key = _hash_text(html)
  492. self.html_blocks[key] = html
  493. return "\n\n" + key + "\n\n"
  494. def _hash_html_blocks(self, text, raw=False):
  495. """Hashify HTML blocks
  496. We only want to do this for block-level HTML tags, such as headers,
  497. lists, and tables. That's because we still want to wrap <p>s around
  498. "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  499. phrase emphasis, and spans. The list of tags we're looking for is
  500. hard-coded.
  501. @param raw {boolean} indicates if these are raw HTML blocks in
  502. the original source. It makes a difference in "safe" mode.
  503. """
  504. if '<' not in text:
  505. return text
  506. # Pass `raw` value into our calls to self._hash_html_block_sub.
  507. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw)
  508. # First, look for nested blocks, e.g.:
  509. # <div>
  510. # <div>
  511. # tags for inner block must be indented.
  512. # </div>
  513. # </div>
  514. #
  515. # The outermost tags must start at the left margin for this to match, and
  516. # the inner nested divs must be indented.
  517. # We need to do this before the next, more liberal match, because the next
  518. # match will start at the first `<div>` and stop at the first `</div>`.
  519. text = self._strict_tag_block_re.sub(hash_html_block_sub, text)
  520. # Now match more liberally, simply from `\n<tag>` to `</tag>\n`
  521. text = self._liberal_tag_block_re.sub(hash_html_block_sub, text)
  522. # Special case just for <hr />. It was easier to make a special
  523. # case than to make the other regex more complicated.
  524. if "<hr" in text:
  525. _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width)
  526. text = _hr_tag_re.sub(hash_html_block_sub, text)
  527. # Special case for standalone HTML comments:
  528. if "<!--" in text:
  529. start = 0
  530. while True:
  531. # Delimiters for next comment block.
  532. try:
  533. start_idx = text.index("<!--", start)
  534. except ValueError, ex:
  535. break
  536. try:
  537. end_idx = text.index("-->", start_idx) + 3
  538. except ValueError, ex:
  539. break
  540. # Start position for next comment block search.
  541. start = end_idx
  542. # Validate whitespace before comment.
  543. if start_idx:
  544. # - Up to `tab_width - 1` spaces before start_idx.
  545. for i in range(self.tab_width - 1):
  546. if text[start_idx - 1] != ' ':
  547. break
  548. start_idx -= 1
  549. if start_idx == 0:
  550. break
  551. # - Must be preceded by 2 newlines or hit the start of
  552. # the document.
  553. if start_idx == 0:
  554. pass
  555. elif start_idx == 1 and text[0] == '\n':
  556. start_idx = 0 # to match minute detail of Markdown.pl regex
  557. elif text[start_idx-2:start_idx] == '\n\n':
  558. pass
  559. else:
  560. break
  561. # Validate whitespace after comment.
  562. # - Any number of spaces and tabs.
  563. while end_idx < len(text):
  564. if text[end_idx] not in ' \t':
  565. break
  566. end_idx += 1
  567. # - Must be following by 2 newlines or hit end of text.
  568. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'):
  569. continue
  570. # Escape and hash (must match `_hash_html_block_sub`).
  571. html = text[start_idx:end_idx]
  572. if raw and self.safe_mode:
  573. html = self._sanitize_html(html)
  574. key = _hash_text(html)
  575. self.html_blocks[key] = html
  576. text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:]
  577. if "xml" in self.extras:
  578. # Treat XML processing instructions and namespaced one-liner
  579. # tags as if they were block HTML tags. E.g., if standalone
  580. # (i.e. are their own paragraph), the following do not get
  581. # wrapped in a <p> tag:
  582. # <?foo bar?>
  583. #
  584. # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/>
  585. _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width)
  586. text = _xml_oneliner_re.sub(hash_html_block_sub, text)
  587. return text
  588. def _strip_link_definitions(self, text):
  589. # Strips link definitions from text, stores the URLs and titles in
  590. # hash references.
  591. less_than_tab = self.tab_width - 1
  592. # Link defs are in the form:
  593. # [id]: url "optional title"
  594. _link_def_re = re.compile(r"""
  595. ^[ ]{0,%d}\[(.+)\]: # id = \1
  596. [ \t]*
  597. \n? # maybe *one* newline
  598. [ \t]*
  599. <?(.+?)>? # url = \2
  600. [ \t]*
  601. (?:
  602. \n? # maybe one newline
  603. [ \t]*
  604. (?<=\s) # lookbehind for whitespace
  605. ['"(]
  606. ([^\n]*) # title = \3
  607. ['")]
  608. [ \t]*
  609. )? # title is optional
  610. (?:\n+|\Z)
  611. """ % less_than_tab, re.X | re.M | re.U)
  612. return _link_def_re.sub(self._extract_link_def_sub, text)
  613. def _extract_link_def_sub(self, match):
  614. id, url, title = match.groups()
  615. key = id.lower() # Link IDs are case-insensitive
  616. self.urls[key] = self._encode_amps_and_angles(url)
  617. if title:
  618. self.titles[key] = title.replace('"', '&quot;')
  619. return ""
  620. def _extract_footnote_def_sub(self, match):
  621. id, text = match.groups()
  622. text = _dedent(text, skip_first_line=not text.startswith('\n')).strip()
  623. normed_id = re.sub(r'\W', '-', id)
  624. # Ensure footnote text ends with a couple newlines (for some
  625. # block gamut matches).
  626. self.footnotes[normed_id] = text + "\n\n"
  627. return ""
  628. def _strip_footnote_definitions(self, text):
  629. """A footnote definition looks like this:
  630. [^note-id]: Text of the note.
  631. May include one or more indented paragraphs.
  632. Where,
  633. - The 'note-id' can be pretty much anything, though typically it
  634. is the number of the footnote.
  635. - The first paragraph may start on the next line, like so:
  636. [^note-id]:
  637. Text of the note.
  638. """
  639. less_than_tab = self.tab_width - 1
  640. footnote_def_re = re.compile(r'''
  641. ^[ ]{0,%d}\[\^(.+)\]: # id = \1
  642. [ \t]*
  643. ( # footnote text = \2
  644. # First line need not start with the spaces.
  645. (?:\s*.*\n+)
  646. (?:
  647. (?:[ ]{%d} | \t) # Subsequent lines must be indented.
  648. .*\n+
  649. )*
  650. )
  651. # Lookahead for non-space at line-start, or end of doc.
  652. (?:(?=^[ ]{0,%d}\S)|\Z)
  653. ''' % (less_than_tab, self.tab_width, self.tab_width),
  654. re.X | re.M)
  655. return footnote_def_re.sub(self._extract_footnote_def_sub, text)
  656. _hr_res = [
  657. re.compile(r"^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$", re.M),
  658. re.compile(r"^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$", re.M),
  659. re.compile(r"^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$", re.M),
  660. ]
  661. def _run_block_gamut(self, text):
  662. # These are all the transformations that form block-level
  663. # tags like paragraphs, headers, and list items.
  664. text = self._do_headers(text)
  665. # Do Horizontal Rules:
  666. hr = "\n<hr"+self.empty_element_suffix+"\n"
  667. for hr_re in self._hr_res:
  668. text = hr_re.sub(hr, text)
  669. text = self._do_lists(text)
  670. if "pyshell" in self.extras:
  671. text = self._prepare_pyshell_blocks(text)
  672. text = self._do_code_blocks(text)
  673. text = self._do_block_quotes(text)
  674. # We already ran _HashHTMLBlocks() before, in Markdown(), but that
  675. # was to escape raw HTML in the original Markdown source. This time,
  676. # we're escaping the markup we've just created, so that we don't wrap
  677. # <p> tags around block-level tags.
  678. text = self._hash_html_blocks(text)
  679. text = self._form_paragraphs(text)
  680. return text
  681. def _pyshell_block_sub(self, match):
  682. lines = match.group(0).splitlines(0)
  683. _dedentlines(lines)
  684. indent = ' ' * self.tab_width
  685. s = ('\n' # separate from possible cuddled paragraph
  686. + indent + ('\n'+indent).join(lines)
  687. + '\n\n')
  688. return s
  689. def _prepare_pyshell_blocks(self, text):
  690. """Ensure that Python interactive shell sessions are put in
  691. code blocks -- even if not properly indented.
  692. """
  693. if ">>>" not in text:
  694. return text
  695. less_than_tab = self.tab_width - 1
  696. _pyshell_block_re = re.compile(r"""
  697. ^([ ]{0,%d})>>>[ ].*\n # first line
  698. ^(\1.*\S+.*\n)* # any number of subsequent lines
  699. ^\n # ends with a blank line
  700. """ % less_than_tab, re.M | re.X)
  701. return _pyshell_block_re.sub(self._pyshell_block_sub, text)
  702. def _run_span_gamut(self, text):
  703. # These are all the transformations that occur *within* block-level
  704. # tags like paragraphs, headers, and list items.
  705. text = self._do_code_spans(text)
  706. text = self._escape_special_chars(text)
  707. # Process anchor and image tags.
  708. text = self._do_links(text)
  709. # Make links out of things like `<http://example.com/>`
  710. # Must come after _do_links(), because you can use < and >
  711. # delimiters in inline links like [this](<url>).
  712. text = self._do_auto_links(text)
  713. if "link-patterns" in self.extras:
  714. text = self._do_link_patterns(text)
  715. text = self._encode_amps_and_angles(text)
  716. text = self._do_italics_and_bold(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('*', g_escape_table['*'])
  755. .replace('_', g_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 = 300
  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('*', g_escape_table['*']) \
  911. .replace('_', g_escape_table['_'])
  912. if title:
  913. title_str = ' title="%s"' \
  914. % title.replace('*', g_escape_table['*']) \
  915. .replace('_', g_escape_table['_']) \
  916. .replace('"', '&quot;')
  917. else:
  918. title_str = ''
  919. if is_img:
  920. result = '<img src="%s" alt="%s"%s%s' \
  921. % (url, link_text.replace('"', '&quot;'),
  922. title_str, self.empty_element_suffix)
  923. curr_pos = start_idx + len(result)
  924. text = text[:start_idx] + result + text[match.end():]
  925. elif start_idx >= anchor_allowed_pos:
  926. if url.startswith('feed://') or url.startswith('feeds://'):
  927. url = url.replace('feed', 'http')
  928. result_head = '<a href="%s"%s rel="feed">' % (url, title_str)
  929. result = '%s%s</a>' % (result_head, link_text)
  930. else:
  931. result_head = '<a href="%s"%s>' % (url, title_str)
  932. result = '%s%s</a>' % (result_head, link_text)
  933. # <img> allowed from curr_pos on, <a> from
  934. # anchor_allowed_pos on.
  935. curr_pos = start_idx + len(result_head)
  936. anchor_allowed_pos = start_idx + len(result)
  937. text = text[:start_idx] + result + text[match.end():]
  938. else:
  939. # Anchor not allowed here.
  940. curr_pos = start_idx + 1
  941. continue
  942. # Reference anchor or img?
  943. else:
  944. match = self._tail_of_reference_link_re.match(text, p)
  945. if match:
  946. # Handle a reference-style anchor or img.
  947. is_img = start_idx > 0 and text[start_idx-1] == "!"
  948. if is_img:
  949. start_idx -= 1
  950. link_id = match.group("id").lower()
  951. if not link_id:
  952. link_id = link_text.lower() # for links like [this][]
  953. if link_id in self.urls:
  954. url = self.urls[link_id]
  955. # We've got to encode these to avoid conflicting
  956. # with italics/bold.
  957. url = url.replace('*', g_escape_table['*']) \
  958. .replace('_', g_escape_table['_'])
  959. title = self.titles.get(link_id)
  960. if title:
  961. title = title.replace('*', g_escape_table['*']) \
  962. .replace('_', g_escape_table['_'])
  963. title_str = ' title="%s"' % title
  964. else:
  965. title_str = ''
  966. if is_img:
  967. result = '<img src="%s" alt="%s"%s%s' \
  968. % (url, link_text.replace('"', '&quot;'),
  969. title_str, self.empty_element_suffix)
  970. curr_pos = start_idx + len(result)
  971. text = text[:start_idx] + result + text[match.end():]
  972. elif start_idx >= anchor_allowed_pos:
  973. result = '<a href="%s"%s>%s</a>' \
  974. % (url, title_str, link_text)
  975. result_head = '<a href="%s"%s>' % (url, title_str)
  976. result = '%s%s</a>' % (result_head, link_text)
  977. # <img> allowed from curr_pos on, <a> from
  978. # anchor_allowed_pos on.
  979. curr_pos = start_idx + len(result_head)
  980. anchor_allowed_pos = start_idx + len(result)
  981. text = text[:start_idx] + result + text[match.end():]
  982. else:
  983. # Anchor not allowed here.
  984. curr_pos = start_idx + 1
  985. else:
  986. # This id isn't defined, leave the markup alone.
  987. curr_pos = match.end()
  988. continue
  989. # Otherwise, it isn't markup.
  990. curr_pos = start_idx + 1
  991. return text
  992. _setext_h_re = re.compile(r'^(.+)[ \t]*\n(=+|-+)[ \t]*\n+', re.M)
  993. def _setext_h_sub(self, match):
  994. n = {"=": 1, "-": 2}[match.group(2)[0]]
  995. demote_headers = self.extras.get("demote-headers")
  996. if demote_headers:
  997. n = min(n + demote_headers, 6)
  998. return "<h%d>%s</h%d>\n\n" \
  999. % (n, self._run_span_gamut(match.group(1)), n)
  1000. _atx_h_re = re.compile(r'''
  1001. ^(\#{1,6}) # \1 = string of #'s
  1002. [ \t]*
  1003. (.+?) # \2 = Header text
  1004. [ \t]*
  1005. (?<!\\) # ensure not an escaped trailing '#'
  1006. \#* # optional closing #'s (not counted)
  1007. \n+
  1008. ''', re.X | re.M)
  1009. def _atx_h_sub(self, match):
  1010. n = len(match.group(1))
  1011. demote_headers = self.extras.get("demote-headers")
  1012. if demote_headers:
  1013. n = min(n + demote_headers, 6)
  1014. return "<h%d>%s</h%d>\n\n" \
  1015. % (n, self._run_span_gamut(match.group(2)), n)
  1016. def _do_headers(self, text):
  1017. # Setext-style headers:
  1018. # Header 1
  1019. # ========
  1020. #
  1021. # Header 2
  1022. # --------
  1023. text = self._setext_h_re.sub(self._setext_h_sub, text)
  1024. # atx-style headers:
  1025. # # Header 1
  1026. # ## Header 2
  1027. # ## Header 2 with closing hashes ##
  1028. # ...
  1029. # ###### Header 6
  1030. text = self._atx_h_re.sub(self._atx_h_sub, text)
  1031. return text
  1032. _marker_ul_chars = '*+-'
  1033. _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars
  1034. _marker_ul = '(?:[%s])' % _marker_ul_chars
  1035. _marker_ol = r'(?:\d+\.)'
  1036. def _list_sub(self, match):
  1037. lst = match.group(1)
  1038. lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol"
  1039. result = self._process_list_items(lst)
  1040. if self.list_level:
  1041. return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type)
  1042. else:
  1043. return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type)
  1044. def _do_lists(self, text):
  1045. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  1046. for marker_pat in (self._marker_ul, self._marker_ol):
  1047. # Re-usable pattern to match any entire ul or ol list:
  1048. less_than_tab = self.tab_width - 1
  1049. whole_list = r'''
  1050. ( # \1 = whole list
  1051. ( # \2
  1052. [ ]{0,%d}
  1053. (%s) # \3 = first list item marker
  1054. [ \t]+
  1055. )
  1056. (?:.+?)
  1057. ( # \4
  1058. \Z
  1059. |
  1060. \n{2,}
  1061. (?=\S)
  1062. (?! # Negative lookahead for another list item marker
  1063. [ \t]*
  1064. %s[ \t]+
  1065. )
  1066. )
  1067. )
  1068. ''' % (less_than_tab, marker_pat, marker_pat)
  1069. # We use a different prefix before nested lists than top-level lists.
  1070. # See extended comment in _process_list_items().
  1071. #
  1072. # Note: There's a bit of duplication here. My original implementation
  1073. # created a scalar regex pattern as the conditional result of the test on
  1074. # $g_list_level, and then only ran the $text =~ s{...}{...}egmx
  1075. # substitution once, using the scalar as the pattern. This worked,
  1076. # everywhere except when running under MT on my hosting account at Pair
  1077. # Networks. There, this caused all rebuilds to be killed by the reaper (or
  1078. # perhaps they crashed, but that seems incredibly unlikely given that the
  1079. # same script on the same server ran fine *except* under MT. I've spent
  1080. # more time trying to figure out why this is happening than I'd like to
  1081. # admit. My only guess, backed up by the fact that this workaround works,
  1082. # is that Perl optimizes the substition when it can figure out that the
  1083. # pattern will never change, and when this optimization isn't on, we run
  1084. # afoul of the reaper. Thus, the slightly redundant code to that uses two
  1085. # static s/// patterns rather than one conditional pattern.
  1086. if self.list_level:
  1087. sub_list_re = re.compile("^"+whole_list, re.X | re.M | re.S)
  1088. text = sub_list_re.sub(self._list_sub, text)
  1089. else:
  1090. list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list,
  1091. re.X | re.M | re.S)
  1092. text = list_re.sub(self._list_sub, text)
  1093. return text
  1094. _list_item_re = re.compile(r'''
  1095. (\n)? # leading line = \1
  1096. (^[ \t]*) # leading whitespace = \2
  1097. (%s) [ \t]+ # list marker = \3
  1098. ((?:.+?) # list item text = \4
  1099. (\n{1,2})) # eols = \5
  1100. (?= \n* (\Z | \2 (%s) [ \t]+))
  1101. ''' % (_marker_any, _marker_any),
  1102. re.M | re.X | re.S)
  1103. _last_li_endswith_two_eols = False
  1104. def _list_item_sub(self, match):
  1105. item = match.group(4)
  1106. leading_line = match.group(1)
  1107. leading_space = match.group(2)
  1108. if leading_line or "\n\n" in item or self._last_li_endswith_two_eols:
  1109. item = self._run_block_gamut(self._outdent(item))
  1110. else:
  1111. # Recursion for sub-lists:
  1112. item = self._do_lists(self._outdent(item))
  1113. if item.endswith('\n'):
  1114. item = item[:-1]
  1115. item = self._run_span_gamut(item)
  1116. self._last_li_endswith_two_eols = (len(match.group(5)) == 2)
  1117. return "<li>%s</li>\n" % item
  1118. def _process_list_items(self, list_str):
  1119. # Process the contents of a single ordered or unordered list,
  1120. # splitting it into individual list items.
  1121. # The $g_list_level global keeps track of when we're inside a list.
  1122. # Each time we enter a list, we increment it; when we leave a list,
  1123. # we decrement. If it's zero, we're not in a list anymore.
  1124. #
  1125. # We do this because when we're not inside a list, we want to treat
  1126. # something like this:
  1127. #
  1128. # I recommend upgrading to version
  1129. # 8. Oops, now this line is treated
  1130. # as a sub-list.
  1131. #
  1132. # As a single paragraph, despite the fact that the second line starts
  1133. # with a digit-period-space sequence.
  1134. #
  1135. # Whereas when we're inside a list (or sub-list), that line will be
  1136. # treated as the start of a sub-list. What a kludge, huh? This is
  1137. # an aspect of Markdown's syntax that's hard to parse perfectly
  1138. # without resorting to mind-reading. Perhaps the solution is to
  1139. # change the syntax rules such that sub-lists must start with a
  1140. # starting cardinal number; e.g. "1." or "a.".
  1141. self.list_level += 1
  1142. self._last_li_endswith_two_eols = False
  1143. list_str = list_str.rstrip('\n') + '\n'
  1144. list_str = self._list_item_re.sub(self._list_item_sub, list_str)
  1145. self.list_level -= 1
  1146. return list_str
  1147. def _get_pygments_lexer(self, lexer_name):
  1148. try:
  1149. from pygments import lexers, util
  1150. except ImportError:
  1151. return None
  1152. try:
  1153. return lexers.get_lexer_by_name(lexer_name)
  1154. except util.ClassNotFound:
  1155. return None
  1156. def _color_with_pygments(self, codeblock, lexer):
  1157. import pygments
  1158. import pygments.formatters
  1159. class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
  1160. def _wrap_code(self, inner):
  1161. """A function for use in a Pygments Formatter which
  1162. wraps in <code> tags.
  1163. """
  1164. yield 0, "<code>"
  1165. for tup in inner:
  1166. yield tup
  1167. yield 0, "</code>"
  1168. def wrap(self, source, outfile):
  1169. """Return the source with a code, pre, and div."""
  1170. return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
  1171. formatter = HtmlCodeFormatter(cssclass="codehilite")
  1172. return pygments.highlight(codeblock, lexer, formatter)
  1173. def _code_block_sub(self, match):
  1174. codeblock = match.group(1)
  1175. codeblock = self._outdent(codeblock)
  1176. codeblock = self._detab(codeblock)
  1177. codeblock = codeblock.lstrip('\n') # trim leading newlines
  1178. codeblock = codeblock.rstrip() # trim trailing whitespace
  1179. if "code-color" in self.extras and codeblock.startswith(":::"):
  1180. lexer_name, rest = codeblock.split('\n', 1)
  1181. lexer_name = lexer_name[3:].strip()
  1182. lexer = self._get_pygments_lexer(lexer_name)
  1183. codeblock = rest.lstrip("\n") # Remove lexer declaration line.
  1184. if lexer:
  1185. colored = self._color_with_pygments(codeblock, lexer)
  1186. return "\n\n%s\n\n" % colored
  1187. if 'codehilite' in self.extras:
  1188. code = CodeHilite(codeblock, linenos=self.codehilite.get('force_linenos'),
  1189. css_class=self.codehilite.get('css_class','codehilite'))
  1190. return "\n\n%s\n\n" % code.hilite()
  1191. codeblock = self._encode_code(codeblock)
  1192. return "\n\n<pre><code>%s\n</code></pre>\n\n" % codeblock
  1193. def _do_code_blocks(self, text):
  1194. """Process Markdown `<pre><code>` blocks."""
  1195. code_block_re = re.compile(r'''
  1196. (?:\n\n|\A)
  1197. ( # $1 = the code block -- one or more lines, starting with a space/tab
  1198. (?:
  1199. (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces
  1200. .*\n+
  1201. )+
  1202. )
  1203. ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  1204. ''' % (self.tab_width, self.tab_width),
  1205. re.M | re.X)
  1206. return code_block_re.sub(self._code_block_sub, text)
  1207. # Rules for a code span:
  1208. # - backslash escapes are not interpreted in a code span
  1209. # - to include one or or a run of more backticks the delimiters must
  1210. # be a longer run of backticks
  1211. # - cannot start or end a code span with a backtick; pad with a
  1212. # space and that space will be removed in the emitted HTML
  1213. # See `test/tm-cases/escapes.text` for a number of edge-case
  1214. # examples.
  1215. _code_span_re = re.compile(r'''
  1216. (?<!\\)
  1217. (`+) # \1 = Opening run of `
  1218. (?!`) # See Note A test/tm-cases/escapes.text
  1219. (.+?) # \2 = The code block
  1220. (?<!`)
  1221. \1 # Matching closer
  1222. (?!`)
  1223. ''', re.X | re.S)
  1224. def _code_span_sub(self, match):
  1225. c = match.group(2).strip(" \t")
  1226. c = self._encode_code(c)
  1227. return "<code>%s</code>" % c
  1228. def _do_code_spans(self, text):
  1229. # * Backtick quotes are used for <code></code> spans.
  1230. #
  1231. # * You can use multiple backticks as the delimiters if you want to
  1232. # include literal backticks in the code span. So, this input:
  1233. #
  1234. # Just type ``foo `bar` baz`` at the prompt.
  1235. #
  1236. # Will translate to:
  1237. #
  1238. # <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  1239. #
  1240. # There's no arbitrary limit to the number of backticks you
  1241. # can use as delimters. If you need three consecutive backticks
  1242. # in your code, use four for delimiters, etc.
  1243. #
  1244. # * You can use spaces to get literal backticks at the edges:
  1245. #
  1246. # ... type `` `bar` `` ...
  1247. #
  1248. # Turns to:
  1249. #
  1250. # ... type <code>`bar`</code> ...
  1251. return self._code_span_re.sub(self._code_span_sub, text)
  1252. def _encode_code(self, text):
  1253. """Encode/escape certain characters inside Markdown code runs.
  1254. The point is that in code, these characters are literals,
  1255. and lose their special Markdown meanings.
  1256. """
  1257. replacements = [
  1258. # Encode all ampersands; HTML entities are not
  1259. # entities within a Markdown code span.
  1260. ('&', '&amp;'),
  1261. # Do the angle bracket song and dance:
  1262. ('<', '&lt;'),
  1263. ('>', '&gt;'),
  1264. # Now, escape characters that are magic in Markdown:
  1265. ('*', g_escape_table['*']),
  1266. ('_', g_escape_table['_']),
  1267. ('{', g_escape_table['{']),
  1268. ('}', g_escape_table['}']),
  1269. ('[', g_escape_table['[']),
  1270. (']', g_escape_table[']']),
  1271. ('\\', g_escape_table['\\']),
  1272. ]
  1273. for before, after in replacements:
  1274. text = text.replace(before, after)
  1275. return text
  1276. _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S)
  1277. _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S)
  1278. _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S)
  1279. _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S)
  1280. def _do_italics_and_bold(self, text):
  1281. # <strong> must go first:
  1282. if "code-friendly" in self.extras:
  1283. text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text)
  1284. text = self._code_friendly_em_re.sub(r"<em>\1</em>", text)
  1285. else:
  1286. text = self._strong_re.sub(r"<strong>\2</strong>", text)
  1287. text = self._em_re.sub(r"<em>\2</em>", text)
  1288. return text
  1289. _block_quote_re = re.compile(r'''
  1290. ( # Wrap whole match in \1
  1291. (
  1292. ^[ \t]*>[ \t]? # '>' at the start of a line
  1293. .+\n # rest of the first line
  1294. (.+\n)* # subsequent consecutive lines
  1295. \n* # blanks
  1296. )+
  1297. )
  1298. ''', re.M | re.X)
  1299. _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M);
  1300. _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S)
  1301. def _dedent_two_spaces_sub(self, match):
  1302. return re.sub(r'(?m)^ ', '', match.group(1))
  1303. def _block_quote_sub(self, match):
  1304. bq = match.group(1)
  1305. bq = self._bq_one_level_re.sub('', bq) # trim one level of quoting
  1306. bq = self._ws_only_line_re.sub('', bq) # trim whitespace-only lines
  1307. bq = self._run_block_gamut(bq) # recurse
  1308. bq = re.sub('(?m)^', ' ', bq)
  1309. # These leading spaces screw with <pre> content, so we need to fix that:
  1310. bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq)
  1311. return "<blockquote>\n%s\n</blockquote>\n\n" % bq
  1312. def _do_block_quotes(self, text):
  1313. if '>' not in text:
  1314. return text
  1315. return self._block_quote_re.sub(self._block_quote_sub, text)
  1316. def _form_paragraphs(self, text):
  1317. # Strip leading and trailing lines:
  1318. text = text.strip('\n')
  1319. # Wrap <p> tags.
  1320. grafs = re.split(r"\n{2,}", text)
  1321. for i, graf in enumerate(grafs):
  1322. if graf in self.html_blocks:
  1323. # Unhashify HTML blocks
  1324. grafs[i] = self.html_blocks[graf]
  1325. else:
  1326. # Wrap <p> tags.
  1327. graf = self._run_span_gamut(graf)
  1328. grafs[i] = "<p>" + graf.lstrip(" \t") + "</p>"
  1329. return "\n\n".join(grafs)
  1330. def _add_footnotes(self, text):
  1331. if self.footnotes:
  1332. footer = [
  1333. '<div class="footnotes">',
  1334. '<hr' + self.empty_element_suffix,
  1335. '<ol>',
  1336. ]
  1337. for i, id in enumerate(self.footnote_ids):
  1338. if i != 0:
  1339. footer.append('')
  1340. footer.append('<li id="fn-%s">' % id)
  1341. footer.append(self._run_block_gamut(self.footnotes[id]))
  1342. backlink = ('<a href="#fnref-%s" '
  1343. 'class="footnoteBackLink" '
  1344. 'title="Jump back to footnote %d in the text.">'
  1345. '&#8617;</a>' % (id, i+1))
  1346. if footer[-1].endswith("</p>"):
  1347. footer[-1] = footer[-1][:-len("</p>")] \
  1348. + '&nbsp;' + backlink + "</p>"
  1349. else:
  1350. footer.append("\n<p>%s</p>" % backlink)
  1351. footer.append('</li>')
  1352. footer.append('</ol>')
  1353. footer.append('</div>')
  1354. return text + '\n\n' + '\n'.join(footer)
  1355. else:
  1356. return text
  1357. # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  1358. # http://bumppo.net/projects/amputator/
  1359. _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)')
  1360. _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I)
  1361. def _encode_amps_and_angles(self, text):
  1362. # Smart processing for ampersands and angle brackets that need
  1363. # to be encoded.
  1364. text = self._ampersand_re.sub('&amp;', text)
  1365. # Encode naked <'s
  1366. text = self._naked_lt_re.sub('&lt;', text)
  1367. return text
  1368. def _encode_backslash_escapes(self, text):
  1369. for ch, escape in g_escape_table.items():
  1370. text = text.replace("\\"+ch, escape)
  1371. return text
  1372. _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I)
  1373. def _auto_link_sub(self, match):
  1374. g1 = match.group(1)
  1375. return '<a href="%s">%s</a>' % (g1, g1)
  1376. _auto_email_link_re = re.compile(r"""
  1377. <
  1378. (?:mailto:)?
  1379. (
  1380. [-.\w]+
  1381. \@
  1382. [-\w]+(\.[-\w]+)*\.[a-zA-Z]+
  1383. )
  1384. >
  1385. """, re.I | re.X | re.U)
  1386. def _auto_email_link_sub(self, match):
  1387. return self._encode_email_address(
  1388. self._unescape_special_chars(match.group(1)))
  1389. def _do_auto_links(self, text):
  1390. text = self._auto_link_re.sub(self._auto_link_sub, text)
  1391. text = self._auto_email_link_re.sub(self._auto_email_link_sub, text)
  1392. return text
  1393. def _encode_email_address(self, addr):
  1394. # Input: an email address, e.g. "foo@example.com"
  1395. #
  1396. # Output: the email address as a mailto link, with each character
  1397. # of the address encoded as either a decimal or hex entity, in
  1398. # the hopes of foiling most address harvesting spam bots. E.g.:
  1399. #
  1400. # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  1401. # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  1402. # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  1403. #
  1404. # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  1405. # mailing list: <http://tinyurl.com/yu7ue>
  1406. chars = [_xml_encode_email_char_at_random(ch)
  1407. for ch in "mailto:" + addr]
  1408. # Strip the mailto: from the visible part.
  1409. addr = '<a href="%s">%s</a>' \
  1410. % (''.join(chars), ''.join(chars[7:]))
  1411. return addr
  1412. def _do_link_patterns(self, text):
  1413. """Caveat emptor: there isn't much guarding against link
  1414. patterns being formed inside other standard Markdown links, e.g.
  1415. inside a [link def][like this].
  1416. Dev Notes: *Could* consider prefixing regexes with a negative
  1417. lookbehind assertion to attempt to guard against this.
  1418. """
  1419. link_from_hash = {}
  1420. for regex, href, group in self.link_patterns:
  1421. replacements = []
  1422. for match in regex.finditer(text):
  1423. replacements.append((match.span(), match.span(group), match.expand(href)))
  1424. for (st, et), (start, end), href in reversed(replacements):
  1425. escaped_href = (
  1426. href.replace('"', '&quot;') # b/c of attr quote
  1427. # To avoid markdown <em> and <strong>:
  1428. .replace('*', g_escape_table['*'])
  1429. .replace('_', g_escape_table['_']))
  1430. link = '<a href="%s">%s</a>' % (escaped_href, text[start:end])
  1431. hash = md5(smart_str(link)).hexdigest()
  1432. link_from_hash[hash] = link
  1433. text = text[:st] + hash + text[et:]
  1434. for hash, link in link_from_hash.items():
  1435. text = text.replace(hash, link)
  1436. return text
  1437. def _unescape_special_chars(self, text):
  1438. # Swap back in all the special characters we've hidden.
  1439. for ch, hash in g_escape_table.items():
  1440. text = text.replace(hash, ch)
  1441. return text
  1442. def _outdent(self, text):
  1443. # Remove one level of line-leading tabs or spaces
  1444. return self._outdent_re.sub('', text)
  1445. class MarkdownWithExtras(Markdown):
  1446. """A markdowner class that enables most extras:
  1447. - footnotes
  1448. - code-color (only has effect if 'pygments' Python module on path)
  1449. These are not included:
  1450. - pyshell (specific to Python-related documenting)
  1451. - code-friendly (because it *disables* part of the syntax)
  1452. - link-patterns (because you need to specify some actual
  1453. link-patterns anyway)
  1454. """
  1455. extras = ["footnotes", "code-color"]
  1456. #---- internal support functions
  1457. # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
  1458. def _curry(*args, **kwargs):
  1459. function, args = args[0], args[1:]
  1460. def result(*rest, **kwrest):
  1461. combined = kwargs.copy()
  1462. combined.update(kwrest)
  1463. return function(*args + rest, **combined)
  1464. return result
  1465. # Recipe: regex_from_encoded_pattern (1.0)
  1466. def _regex_from_encoded_pattern(s):
  1467. """'foo' -> re.compile(re.escape('foo'))
  1468. '/foo/' -> re.compile('foo')
  1469. '/foo/i' -> re.compile('foo', re.I)
  1470. """
  1471. if s.startswith('/') and s.rfind('/') != 0:
  1472. # Parse it: /PATTERN/FLAGS
  1473. idx = s.rfind('/')
  1474. pattern, flags_str = s[1:idx], s[idx+1:]
  1475. flag_from_char = {
  1476. "i": re.IGNORECASE,
  1477. "l": re.LOCALE,
  1478. "s": re.DOTALL,
  1479. "m": re.MULTILINE,
  1480. "u": re.UNICODE,
  1481. }
  1482. flags = 0
  1483. for char in flags_str:
  1484. try:
  1485. flags |= flag_from_char[char]
  1486. except KeyError:
  1487. raise ValueError("unsupported regex flag: '%s' in '%s' "
  1488. "(must be one of '%s')"
  1489. % (char, s, ''.join(flag_from_char.keys())))
  1490. return re.compile(s[1:idx], flags)
  1491. else: # not an encoded regex
  1492. return re.compile(re.escape(s))
  1493. # Recipe: dedent (0.1.2)
  1494. def _dedentlines(lines, tabsize=8, skip_first_line=False):
  1495. """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
  1496. "lines" is a list of lines to dedent.
  1497. "tabsize" is the tab width to use for indent width calculations.
  1498. "skip_first_line" is a boolean indicating if the first line should
  1499. be skipped for calculating the indent width and for dedenting.
  1500. This is sometimes useful for docstrings and similar.
  1501. Same as dedent() except operates on a sequence of lines. Note: the
  1502. lines list is modified **in-place**.
  1503. """
  1504. DEBUG = False
  1505. if DEBUG:
  1506. print "dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\
  1507. % (tabsize, skip_first_line)
  1508. indents = []
  1509. margin = None
  1510. for i, line in enumerate(lines):
  1511. if i == 0 and skip_first_line: continue
  1512. indent = 0
  1513. for ch in line:
  1514. if ch == ' ':
  1515. indent += 1
  1516. elif ch == '\t':
  1517. indent += tabsize - (indent % tabsize)
  1518. elif ch in '\r\n':
  1519. continue # skip all-whitespace lines
  1520. else:
  1521. break
  1522. else:
  1523. continue # skip all-whitespace lines
  1524. if DEBUG: print "dedent: indent=%d: %r" % (indent, line)
  1525. if margin is None:
  1526. margin = indent
  1527. else:
  1528. margin = min(margin, indent)
  1529. if DEBUG: print "dedent: margin=%r" % margin
  1530. if margin is not None and margin > 0:
  1531. for i, line in enumerate(lines):
  1532. if i == 0 and skip_first_line: continue
  1533. removed = 0
  1534. for j, ch in enumerate(line):
  1535. if ch == ' ':
  1536. removed += 1
  1537. elif ch == '\t':
  1538. removed += tabsize - (removed % tabsize)
  1539. elif ch in '\r\n':
  1540. if DEBUG: print "dedent: %r: EOL -> strip up to EOL" % line
  1541. lines[i] = lines[i][j:]
  1542. break
  1543. else:
  1544. raise ValueError("unexpected non-whitespace char %r in "
  1545. "line %r while removing %d-space margin"
  1546. % (ch, line, margin))
  1547. if DEBUG:
  1548. print "dedent: %r: %r -> removed %d/%d"\
  1549. % (line, ch, removed, margin)
  1550. if removed == margin:
  1551. lines[i] = lines[i][j+1:]
  1552. break
  1553. elif removed > margin:
  1554. lines[i] = ' '*(removed-margin) + lines[i][j+1:]
  1555. break
  1556. else:
  1557. if removed:
  1558. lines[i] = lines[i][removed:]
  1559. return lines
  1560. def _dedent(text, tabsize=8, skip_first_line=False):
  1561. """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
  1562. "text" is the text to dedent.
  1563. "tabsize" is the tab width to use for indent width calculations.
  1564. "skip_first_line" is a boolean indicating if the first line should
  1565. be skipped for calculating the indent width and for dedenting.
  1566. This is sometimes useful for docstrings and similar.
  1567. textwrap.dedent(s), but don't expand tabs to spaces
  1568. """
  1569. lines = text.splitlines(1)
  1570. _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)
  1571. return ''.join(lines)
  1572. class _memoized(object):
  1573. """Decorator that caches a function's return value each time it is called.
  1574. If called later with the same arguments, the cached value is returned, and
  1575. not re-evaluated.
  1576. http://wiki.python.org/moin/PythonDecoratorLibrary
  1577. """
  1578. def __init__(self, func):
  1579. self.func = func
  1580. self.cache = {}
  1581. def __call__(self, *args):
  1582. try:
  1583. return self.cache[args]
  1584. except KeyError:
  1585. self.cache[args] = value = self.func(*args)
  1586. return value
  1587. except TypeError:
  1588. # uncachable -- for instance, passing a list as an argument.
  1589. # Better to not cache than to blow up entirely.
  1590. return self.func(*args)
  1591. def __repr__(self):
  1592. """Return the function's docstring."""
  1593. return self.func.__doc__
  1594. def _xml_oneliner_re_from_tab_width(tab_width):
  1595. """Standalone XML processing instruction regex."""
  1596. return re.compile(r"""
  1597. (?:
  1598. (?<=\n\n) # Starting after a blank line
  1599. | # or
  1600. \A\n? # the beginning of the doc
  1601. )
  1602. ( # save in $1
  1603. [ ]{0,%d}
  1604. (?:
  1605. <\?\w+\b\s+.*?\?> # XML processing instruction
  1606. |
  1607. <\w+:\w+\b\s+.*?/> # namespaced single tag
  1608. )
  1609. [ \t]*
  1610. (?=\n{2,}|\Z) # followed by a blank line or end of document
  1611. )
  1612. """ % (tab_width - 1), re.X)
  1613. _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width)
  1614. def _hr_tag_re_from_tab_width(tab_width):
  1615. return re.compile(r"""
  1616. (?:
  1617. (?<=\n\n) # Starting after a blank line
  1618. | # or
  1619. \A\n? # the beginning of the doc
  1620. )
  1621. ( # save in \1
  1622. [ ]{0,%d}
  1623. <(hr) # start tag = \2
  1624. \b # word break
  1625. ([^<>])*? #
  1626. /?> # the matching end tag
  1627. [ \t]*
  1628. (?=\n{2,}|\Z) # followed by a blank line or end of document
  1629. )
  1630. """ % (tab_width - 1), re.X)
  1631. _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width)
  1632. def _xml_encode_email_char_at_random(ch):
  1633. r = random()
  1634. # Roughly 10% raw, 45% hex, 45% dec.
  1635. # '@' *must* be encoded. I [John Gruber] insist.
  1636. if r > 0.9 and ch != "@":
  1637. return ch
  1638. elif r < 0.45:
  1639. # The [1:] is to drop leading '0': 0x63 -> x63
  1640. return '&#%s;' % hex(ord(ch))[1:]
  1641. else:
  1642. return '&#%s;' % ord(ch)
  1643. def _hash_text(text):
  1644. return 'md5:'+md5(text.encode("utf-8")).hexdigest()
  1645. #---- mainline
  1646. class _NoReflowFormatter(optparse.IndentedHelpFormatter):
  1647. """An optparse formatter that does NOT reflow the description."""
  1648. def format_description(self, description):
  1649. return description or ""
  1650. def _test():
  1651. import doctest
  1652. doctest.testmod()
  1653. def main(argv=None):
  1654. if argv is None:
  1655. argv = sys.argv
  1656. if not logging.root.handlers:
  1657. logging.basicConfig()
  1658. usage = "usage: %prog [PATHS...]"
  1659. version = "%prog "+__version__
  1660. parser = optparse.OptionParser(prog="markdown2", usage=usage,
  1661. version=version, description=cmdln_desc,
  1662. formatter=_NoReflowFormatter())
  1663. parser.add_option("-v", "--verbose", dest="log_level",
  1664. action="store_const", const=logging.DEBUG,
  1665. help="more verbose output")
  1666. parser.add_option("--encoding",
  1667. help="specify encoding of text content")
  1668. parser.add_option("--html4tags", action="store_true", default=False,
  1669. help="use HTML 4 style for empty element tags")
  1670. parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode",
  1671. help="sanitize literal HTML: 'escape' escapes "
  1672. "HTML meta chars, 'replace' replaces with an "
  1673. "[HTML_REMOVED] note")
  1674. parser.add_option("-x", "--extras", action="append",
  1675. help="Turn on specific extra features (not part of "
  1676. "the core Markdown spec). Supported values: "
  1677. "'code-friendly' disables _/__ for emphasis; "
  1678. "'code-color' adds code-block syntax coloring; "
  1679. "'link-patterns' adds auto-linking based on patterns; "
  1680. "'footnotes' adds the footnotes syntax;"
  1681. "'xml' passes one-liner processing instructions and namespaced XML tags;"
  1682. "'pyshell' to put unindented Python interactive shell sessions in a <code> block.")
  1683. parser.add_option("--use-file-vars",
  1684. help="Look for and use Emacs-style 'markdown-extras' "
  1685. "file var to turn on extras. See "
  1686. "<http://code.google.com/p/python-markdown2/wiki/Extras>.")
  1687. parser.add_option("--link-patterns-file",
  1688. help="path to a link pattern file")
  1689. parser.add_option("--self-test", action="store_true",
  1690. help="run internal self-tests (some doctests)")
  1691. parser.add_option("--compare", action="store_true",
  1692. help="run against Markdown.pl as well (for testing)")
  1693. parser.set_defaults(log_level=logging.INFO, compare=False,
  1694. encoding="utf-8", safe_mode=None, use_file_vars=False)
  1695. opts, paths = parser.parse_args()
  1696. log.setLevel(opts.log_level)
  1697. if opts.self_test:
  1698. return _test()
  1699. if opts.extras:
  1700. extras = {}
  1701. for s in opts.extras:
  1702. splitter = re.compile("[,;: ]+")
  1703. for e in splitter.split(s):
  1704. if '=' in e:
  1705. ename, earg = e.split('=', 1)
  1706. try:
  1707. earg = int(earg)
  1708. except ValueError:
  1709. pass
  1710. else:
  1711. ename, earg = e, None
  1712. extras[ename] = earg
  1713. else:
  1714. extras = None
  1715. if opts.link_patterns_file:
  1716. link_patterns = []
  1717. f = open(opts.link_patterns_file)
  1718. try:
  1719. for i, line in enumerate(f.readlines()):
  1720. if not line.strip(): continue
  1721. if line.lstrip().startswith("#"): continue
  1722. try:
  1723. pat, href = line.rstrip().rsplit(None, 1)
  1724. except ValueError:
  1725. raise MarkdownError("%s:%d: invalid link pattern line: %r"
  1726. % (opts.link_patterns_file, i+1, line))
  1727. link_patterns.append(
  1728. (_regex_from_encoded_pattern(pat), href))
  1729. finally:
  1730. f.close()
  1731. else:
  1732. link_patterns = None
  1733. from os.path import join, dirname, abspath
  1734. markdown_pl = join(dirname(dirname(abspath(__file__))), "test",
  1735. "Markdown.pl")
  1736. for path in paths:
  1737. if opts.compare:
  1738. print "==== Markdown.pl ===="
  1739. perl_cmd = 'perl %s "%s"' % (markdown_pl, path)
  1740. o = os.popen(perl_cmd)
  1741. perl_html = o.read()
  1742. o.close()
  1743. sys.stdout.write(perl_html)
  1744. print "==== markdown2.py ===="
  1745. html = markdown_path(path, encoding=opts.encoding,
  1746. html4tags=opts.html4tags,
  1747. safe_mode=opts.safe_mode,
  1748. extras=extras, link_patterns=link_patterns,
  1749. use_file_vars=opts.use_file_vars)
  1750. sys.stdout.write(
  1751. html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace'))
  1752. if opts.compare:
  1753. print "==== match? %r ====" % (perl_html == html)
  1754. if __name__ == "__main__":
  1755. sys.exit( main(sys.argv) )