PageRenderTime 71ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/gluon/contrib/markdown/markdown2.py

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