PageRenderTime 61ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/markdown2.py

http://github.com/trentm/python-markdown2
Python | 2808 lines | 2641 code | 62 blank | 105 comment | 101 complexity | 9a2c8bd1585068cc77e2d33553269ae2 MD5 | raw file

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

  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 Trent Mick.
  3. # Copyright (c) 2007-2008 ActiveState Corp.
  4. # License: MIT (http://www.opensource.org/licenses/mit-license.php)
  5. r"""A fast and complete Python implementation of Markdown.
  6. [from http://daringfireball.net/projects/markdown/]
  7. > Markdown is a text-to-HTML filter; it translates an easy-to-read /
  8. > easy-to-write structured text format into HTML. Markdown's text
  9. > format is most similar to that of plain text email, and supports
  10. > features such as headers, *emphasis*, code blocks, blockquotes, and
  11. > links.
  12. >
  13. > Markdown's syntax is designed not as a generic markup language, but
  14. > specifically to serve as a front-end to (X)HTML. You can use span-level
  15. > HTML tags anywhere in a Markdown document, and you can use block level
  16. > HTML tags (like <div> and <table> as well).
  17. Module usage:
  18. >>> import markdown2
  19. >>> markdown2.markdown("*boo!*") # or use `html = markdown_path(PATH)`
  20. u'<p><em>boo!</em></p>\n'
  21. >>> markdowner = Markdown()
  22. >>> markdowner.convert("*boo!*")
  23. u'<p><em>boo!</em></p>\n'
  24. >>> markdowner.convert("**boom!**")
  25. u'<p><strong>boom!</strong></p>\n'
  26. This implementation of Markdown implements the full "core" syntax plus a
  27. number of extras (e.g., code syntax coloring, footnotes) as described on
  28. <https://github.com/trentm/python-markdown2/wiki/Extras>.
  29. """
  30. cmdln_desc = """A fast and complete Python implementation of Markdown, a
  31. text-to-HTML conversion tool for web writers.
  32. Supported extra syntax options (see -x|--extras option below and
  33. see <https://github.com/trentm/python-markdown2/wiki/Extras> for details):
  34. * break-on-newline: Replace single new line characters with <br> when True
  35. * code-friendly: Disable _ and __ for em and strong.
  36. * cuddled-lists: Allow lists to be cuddled to the preceding paragraph.
  37. * fenced-code-blocks: Allows a code block to not have to be indented
  38. by fencing it with '```' on a line before and after. Based on
  39. <http://github.github.com/github-flavored-markdown/> with support for
  40. syntax highlighting.
  41. * footnotes: Support footnotes as in use on daringfireball.net and
  42. implemented in other Markdown processors (tho not in Markdown.pl v1.0.1).
  43. * header-ids: Adds "id" attributes to headers. The id value is a slug of
  44. the header text.
  45. * highlightjs-lang: Allows specifying the language which used for syntax
  46. highlighting when using fenced-code-blocks and highlightjs.
  47. * html-classes: Takes a dict mapping html tag names (lowercase) to a
  48. string to use for a "class" tag attribute. Currently only supports "img",
  49. "table", "pre" and "code" tags. Add an issue if you require this for other
  50. tags.
  51. * link-patterns: Auto-link given regex patterns in text (e.g. bug number
  52. references, revision number references).
  53. * markdown-in-html: Allow the use of `markdown="1"` in a block HTML tag to
  54. have markdown processing be done on its contents. Similar to
  55. <http://michelf.com/projects/php-markdown/extra/#markdown-attr> but with
  56. some limitations.
  57. * metadata: Extract metadata from a leading '---'-fenced block.
  58. See <https://github.com/trentm/python-markdown2/issues/77> for details.
  59. * nofollow: Add `rel="nofollow"` to add `<a>` tags with an href. See
  60. <http://en.wikipedia.org/wiki/Nofollow>.
  61. * numbering: Support of generic counters. Non standard extension to
  62. allow sequential numbering of figures, tables, equations, exhibits etc.
  63. * pyshell: Treats unindented Python interactive shell sessions as <code>
  64. blocks.
  65. * smarty-pants: Replaces ' and " with curly quotation marks or curly
  66. apostrophes. Replaces --, ---, ..., and . . . with en dashes, em dashes,
  67. and ellipses.
  68. * spoiler: A special kind of blockquote commonly hidden behind a
  69. click on SO. Syntax per <http://meta.stackexchange.com/a/72878>.
  70. * strike: text inside of double tilde is ~~strikethrough~~
  71. * tag-friendly: Requires atx style headers to have a space between the # and
  72. the header text. Useful for applications that require twitter style tags to
  73. pass through the parser.
  74. * tables: Tables using the same format as GFM
  75. <https://help.github.com/articles/github-flavored-markdown#tables> and
  76. PHP-Markdown Extra <https://michelf.ca/projects/php-markdown/extra/#table>.
  77. * toc: The returned HTML string gets a new "toc_html" attribute which is
  78. a Table of Contents for the document. (experimental)
  79. * use-file-vars: Look for an Emacs-style markdown-extras file variable to turn
  80. on Extras.
  81. * wiki-tables: Google Code Wiki-style tables. See
  82. <http://code.google.com/p/support/wiki/WikiSyntax#Tables>.
  83. * xml: Passes one-liner processing instructions and namespaced XML tags.
  84. """
  85. # Dev Notes:
  86. # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm
  87. # not yet sure if there implications with this. Compare 'pydoc sre'
  88. # and 'perldoc perlre'.
  89. __version_info__ = (2, 4, 2)
  90. __version__ = '.'.join(map(str, __version_info__))
  91. __author__ = "Trent Mick"
  92. import sys
  93. import re
  94. import logging
  95. from hashlib import sha256
  96. import optparse
  97. from random import random, randint
  98. import codecs
  99. from collections import defaultdict
  100. # ---- Python version compat
  101. # Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3).
  102. if sys.version_info[0] <= 2:
  103. py3 = False
  104. try:
  105. bytes
  106. except NameError:
  107. bytes = str
  108. base_string_type = basestring
  109. elif sys.version_info[0] >= 3:
  110. py3 = True
  111. unicode = str
  112. base_string_type = str
  113. # ---- globals
  114. DEBUG = False
  115. log = logging.getLogger("markdown")
  116. DEFAULT_TAB_WIDTH = 4
  117. SECRET_SALT = bytes(randint(0, 1000000))
  118. # MD5 function was previously used for this; the "md5" prefix was kept for
  119. # backwards compatibility.
  120. def _hash_text(s):
  121. return 'md5-' + sha256(SECRET_SALT + s.encode("utf-8")).hexdigest()[32:]
  122. # Table of hash values for escaped characters:
  123. g_escape_table = dict([(ch, _hash_text(ch))
  124. for ch in '\\`*_{}[]()>#+-.!'])
  125. # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  126. # http://bumppo.net/projects/amputator/
  127. _AMPERSAND_RE = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)')
  128. # ---- exceptions
  129. class MarkdownError(Exception):
  130. pass
  131. # ---- public api
  132. def markdown_path(path, encoding="utf-8",
  133. html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
  134. safe_mode=None, extras=None, link_patterns=None,
  135. footnote_title=None, footnote_return_symbol=None,
  136. use_file_vars=False):
  137. fp = codecs.open(path, 'r', encoding)
  138. text = fp.read()
  139. fp.close()
  140. return Markdown(html4tags=html4tags, tab_width=tab_width,
  141. safe_mode=safe_mode, extras=extras,
  142. link_patterns=link_patterns,
  143. footnote_title=footnote_title,
  144. footnote_return_symbol=footnote_return_symbol,
  145. use_file_vars=use_file_vars).convert(text)
  146. def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
  147. safe_mode=None, extras=None, link_patterns=None,
  148. footnote_title=None, footnote_return_symbol=None,
  149. use_file_vars=False, cli=False):
  150. return Markdown(html4tags=html4tags, tab_width=tab_width,
  151. safe_mode=safe_mode, extras=extras,
  152. link_patterns=link_patterns,
  153. footnote_title=footnote_title,
  154. footnote_return_symbol=footnote_return_symbol,
  155. use_file_vars=use_file_vars, cli=cli).convert(text)
  156. class Markdown(object):
  157. # The dict of "extras" to enable in processing -- a mapping of
  158. # extra name to argument for the extra. Most extras do not have an
  159. # argument, in which case the value is None.
  160. #
  161. # This can be set via (a) subclassing and (b) the constructor
  162. # "extras" argument.
  163. extras = None
  164. urls = None
  165. titles = None
  166. html_blocks = None
  167. html_spans = None
  168. html_removed_text = "{(#HTML#)}" # placeholder removed text that does not trigger bold
  169. html_removed_text_compat = "[HTML_REMOVED]" # for compat with markdown.py
  170. _toc = None
  171. # Used to track when we're inside an ordered or unordered list
  172. # (see _ProcessListItems() for details):
  173. list_level = 0
  174. _ws_only_line_re = re.compile(r"^[ \t]+$", re.M)
  175. def __init__(self, html4tags=False, tab_width=4, safe_mode=None,
  176. extras=None, link_patterns=None,
  177. footnote_title=None, footnote_return_symbol=None,
  178. use_file_vars=False, cli=False):
  179. if html4tags:
  180. self.empty_element_suffix = ">"
  181. else:
  182. self.empty_element_suffix = " />"
  183. self.tab_width = tab_width
  184. self.tab = tab_width * " "
  185. # For compatibility with earlier markdown2.py and with
  186. # markdown.py's safe_mode being a boolean,
  187. # safe_mode == True -> "replace"
  188. if safe_mode is True:
  189. self.safe_mode = "replace"
  190. else:
  191. self.safe_mode = safe_mode
  192. # Massaging and building the "extras" info.
  193. if self.extras is None:
  194. self.extras = {}
  195. elif not isinstance(self.extras, dict):
  196. self.extras = dict([(e, None) for e in self.extras])
  197. if extras:
  198. if not isinstance(extras, dict):
  199. extras = dict([(e, None) for e in extras])
  200. self.extras.update(extras)
  201. assert isinstance(self.extras, dict)
  202. if "toc" in self.extras:
  203. if "header-ids" not in self.extras:
  204. self.extras["header-ids"] = None # "toc" implies "header-ids"
  205. if self.extras["toc"] is None:
  206. self._toc_depth = 6
  207. else:
  208. self._toc_depth = self.extras["toc"].get("depth", 6)
  209. self._instance_extras = self.extras.copy()
  210. self.link_patterns = link_patterns
  211. self.footnote_title = footnote_title
  212. self.footnote_return_symbol = footnote_return_symbol
  213. self.use_file_vars = use_file_vars
  214. self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M)
  215. self.cli = cli
  216. self._escape_table = g_escape_table.copy()
  217. if "smarty-pants" in self.extras:
  218. self._escape_table['"'] = _hash_text('"')
  219. self._escape_table["'"] = _hash_text("'")
  220. def reset(self):
  221. self.urls = {}
  222. self.titles = {}
  223. self.html_blocks = {}
  224. self.html_spans = {}
  225. self.list_level = 0
  226. self.extras = self._instance_extras.copy()
  227. if "footnotes" in self.extras:
  228. self.footnotes = {}
  229. self.footnote_ids = []
  230. if "header-ids" in self.extras:
  231. self._count_from_header_id = defaultdict(int)
  232. if "metadata" in self.extras:
  233. self.metadata = {}
  234. self._toc = None
  235. # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel"
  236. # should only be used in <a> tags with an "href" attribute.
  237. # Opens the linked document in a new window or tab
  238. # should only used in <a> tags with an "href" attribute.
  239. # same with _a_nofollow
  240. _a_nofollow_or_blank_links = re.compile(r"""
  241. <(a)
  242. (
  243. [^>]*
  244. href= # href is required
  245. ['"]? # HTML5 attribute values do not have to be quoted
  246. [^#'"] # We don't want to match href values that start with # (like footnotes)
  247. )
  248. """,
  249. re.IGNORECASE | re.VERBOSE
  250. )
  251. def convert(self, text):
  252. """Convert the given text."""
  253. # Main function. The order in which other subs are called here is
  254. # essential. Link and image substitutions need to happen before
  255. # _EscapeSpecialChars(), so that any *'s or _'s in the <a>
  256. # and <img> tags get encoded.
  257. # Clear the global hashes. If we don't clear these, you get conflicts
  258. # from other articles when generating a page which contains more than
  259. # one article (e.g. an index page that shows the N most recent
  260. # articles):
  261. self.reset()
  262. if not isinstance(text, unicode):
  263. # TODO: perhaps shouldn't presume UTF-8 for string input?
  264. text = unicode(text, 'utf-8')
  265. if self.use_file_vars:
  266. # Look for emacs-style file variable hints.
  267. emacs_vars = self._get_emacs_vars(text)
  268. if "markdown-extras" in emacs_vars:
  269. splitter = re.compile("[ ,]+")
  270. for e in splitter.split(emacs_vars["markdown-extras"]):
  271. if '=' in e:
  272. ename, earg = e.split('=', 1)
  273. try:
  274. earg = int(earg)
  275. except ValueError:
  276. pass
  277. else:
  278. ename, earg = e, None
  279. self.extras[ename] = earg
  280. # Standardize line endings:
  281. text = text.replace("\r\n", "\n")
  282. text = text.replace("\r", "\n")
  283. # Make sure $text ends with a couple of newlines:
  284. text += "\n\n"
  285. # Convert all tabs to spaces.
  286. text = self._detab(text)
  287. # Strip any lines consisting only of spaces and tabs.
  288. # This makes subsequent regexen easier to write, because we can
  289. # match consecutive blank lines with /\n+/ instead of something
  290. # contorted like /[ \t]*\n+/ .
  291. text = self._ws_only_line_re.sub("", text)
  292. # strip metadata from head and extract
  293. if "metadata" in self.extras:
  294. text = self._extract_metadata(text)
  295. text = self.preprocess(text)
  296. if "fenced-code-blocks" in self.extras and not self.safe_mode:
  297. text = self._do_fenced_code_blocks(text)
  298. if self.safe_mode:
  299. text = self._hash_html_spans(text)
  300. # Turn block-level HTML blocks into hash entries
  301. text = self._hash_html_blocks(text, raw=True)
  302. if "fenced-code-blocks" in self.extras and self.safe_mode:
  303. text = self._do_fenced_code_blocks(text)
  304. # Because numbering references aren't links (yet?) then we can do everything associated with counters
  305. # before we get started
  306. if "numbering" in self.extras:
  307. text = self._do_numbering(text)
  308. # Strip link definitions, store in hashes.
  309. if "footnotes" in self.extras:
  310. # Must do footnotes first because an unlucky footnote defn
  311. # looks like a link defn:
  312. # [^4]: this "looks like a link defn"
  313. text = self._strip_footnote_definitions(text)
  314. text = self._strip_link_definitions(text)
  315. text = self._run_block_gamut(text)
  316. if "footnotes" in self.extras:
  317. text = self._add_footnotes(text)
  318. text = self.postprocess(text)
  319. text = self._unescape_special_chars(text)
  320. if self.safe_mode:
  321. text = self._unhash_html_spans(text)
  322. # return the removed text warning to its markdown.py compatible form
  323. text = text.replace(self.html_removed_text, self.html_removed_text_compat)
  324. do_target_blank_links = "target-blank-links" in self.extras
  325. do_nofollow_links = "nofollow" in self.extras
  326. if do_target_blank_links and do_nofollow_links:
  327. text = self._a_nofollow_or_blank_links.sub(r'<\1 rel="nofollow noopener" target="_blank"\2', text)
  328. elif do_target_blank_links:
  329. text = self._a_nofollow_or_blank_links.sub(r'<\1 rel="noopener" target="_blank"\2', text)
  330. elif do_nofollow_links:
  331. text = self._a_nofollow_or_blank_links.sub(r'<\1 rel="nofollow"\2', text)
  332. if "toc" in self.extras and self._toc:
  333. self._toc_html = calculate_toc_html(self._toc)
  334. # Prepend toc html to output
  335. if self.cli:
  336. text = '{}\n{}'.format(self._toc_html, text)
  337. text += "\n"
  338. # Attach attrs to output
  339. rv = UnicodeWithAttrs(text)
  340. if "toc" in self.extras and self._toc:
  341. rv.toc_html = self._toc_html
  342. if "metadata" in self.extras:
  343. rv.metadata = self.metadata
  344. return rv
  345. def postprocess(self, text):
  346. """A hook for subclasses to do some postprocessing of the html, if
  347. desired. This is called before unescaping of special chars and
  348. unhashing of raw HTML spans.
  349. """
  350. return text
  351. def preprocess(self, text):
  352. """A hook for subclasses to do some preprocessing of the Markdown, if
  353. desired. This is called after basic formatting of the text, but prior
  354. to any extras, safe mode, etc. processing.
  355. """
  356. return text
  357. # Is metadata if the content starts with optional '---'-fenced `key: value`
  358. # pairs. E.g. (indented for presentation):
  359. # ---
  360. # foo: bar
  361. # another-var: blah blah
  362. # ---
  363. # # header
  364. # or:
  365. # foo: bar
  366. # another-var: blah blah
  367. #
  368. # # header
  369. _meta_data_pattern = re.compile(r'^(?:---[\ \t]*\n)?((?:[\S\w]+\s*:(?:\n+[ \t]+.*)+)|(?:.*:\s+>\n\s+[\S\s]+?)(?=\n\w+\s*:\s*\w+\n|\Z)|(?:\s*[\S\w]+\s*:(?! >)[ \t]*.*\n?))(?:---[\ \t]*\n)?', re.MULTILINE)
  370. _key_val_pat = re.compile(r"[\S\w]+\s*:(?! >)[ \t]*.*\n?", re.MULTILINE)
  371. # this allows key: >
  372. # value
  373. # conutiues over multiple lines
  374. _key_val_block_pat = re.compile(
  375. r"(.*:\s+>\n\s+[\S\s]+?)(?=\n\w+\s*:\s*\w+\n|\Z)", re.MULTILINE
  376. )
  377. _key_val_list_pat = re.compile(
  378. r"^-(?:[ \t]*([^\n]*)(?:[ \t]*[:-][ \t]*(\S+))?)(?:\n((?:[ \t]+[^\n]+\n?)+))?",
  379. re.MULTILINE,
  380. )
  381. _key_val_dict_pat = re.compile(
  382. r"^([^:\n]+)[ \t]*:[ \t]*([^\n]*)(?:((?:\n[ \t]+[^\n]+)+))?", re.MULTILINE
  383. ) # grp0: key, grp1: value, grp2: multiline value
  384. _meta_data_fence_pattern = re.compile(r'^---[\ \t]*\n', re.MULTILINE)
  385. _meta_data_newline = re.compile("^\n", re.MULTILINE)
  386. def _extract_metadata(self, text):
  387. if text.startswith("---"):
  388. fence_splits = re.split(self._meta_data_fence_pattern, text, maxsplit=2)
  389. metadata_content = fence_splits[1]
  390. match = re.findall(self._meta_data_pattern, metadata_content)
  391. if not match:
  392. return text
  393. tail = fence_splits[2]
  394. else:
  395. metadata_split = re.split(self._meta_data_newline, text, maxsplit=1)
  396. metadata_content = metadata_split[0]
  397. match = re.findall(self._meta_data_pattern, metadata_content)
  398. if not match:
  399. return text
  400. tail = metadata_split[1]
  401. def parse_structured_value(value):
  402. vs = value.lstrip()
  403. vs = value.replace(v[: len(value) - len(vs)], "\n")[1:]
  404. # List
  405. if vs.startswith("-"):
  406. r = []
  407. for match in re.findall(self._key_val_list_pat, vs):
  408. if match[0] and not match[1] and not match[2]:
  409. r.append(match[0].strip())
  410. elif match[0] == ">" and not match[1] and match[2]:
  411. r.append(match[2].strip())
  412. elif match[0] and match[1]:
  413. r.append({match[0].strip(): match[1].strip()})
  414. elif not match[0] and not match[1] and match[2]:
  415. r.append(parse_structured_value(match[2]))
  416. else:
  417. # Broken case
  418. pass
  419. return r
  420. # Dict
  421. else:
  422. return {
  423. match[0].strip(): (
  424. match[1].strip()
  425. if match[1]
  426. else parse_structured_value(match[2])
  427. )
  428. for match in re.findall(self._key_val_dict_pat, vs)
  429. }
  430. for item in match:
  431. k, v = item.split(":", 1)
  432. # Multiline value
  433. if v[:3] == " >\n":
  434. self.metadata[k.strip()] = v[3:].strip()
  435. # Empty value
  436. elif v == "\n":
  437. self.metadata[k.strip()] = ""
  438. # Structured value
  439. elif v[0] == "\n":
  440. self.metadata[k.strip()] = parse_structured_value(v)
  441. # Simple value
  442. else:
  443. self.metadata[k.strip()] = v.strip()
  444. return tail
  445. _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*(?:(\S[^\r\n]*?)([\r\n]\s*)?)?-\*-", re.UNICODE)
  446. # This regular expression is intended to match blocks like this:
  447. # PREFIX Local Variables: SUFFIX
  448. # PREFIX mode: Tcl SUFFIX
  449. # PREFIX End: SUFFIX
  450. # Some notes:
  451. # - "[ \t]" is used instead of "\s" to specifically exclude newlines
  452. # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does
  453. # not like anything other than Unix-style line terminators.
  454. _emacs_local_vars_pat = re.compile(r"""^
  455. (?P<prefix>(?:[^\r\n|\n|\r])*?)
  456. [\ \t]*Local\ Variables:[\ \t]*
  457. (?P<suffix>.*?)(?:\r\n|\n|\r)
  458. (?P<content>.*?\1End:)
  459. """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)
  460. def _get_emacs_vars(self, text):
  461. """Return a dictionary of emacs-style local variables.
  462. Parsing is done loosely according to this spec (and according to
  463. some in-practice deviations from this):
  464. http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables
  465. """
  466. emacs_vars = {}
  467. SIZE = pow(2, 13) # 8kB
  468. # Search near the start for a '-*-'-style one-liner of variables.
  469. head = text[:SIZE]
  470. if "-*-" in head:
  471. match = self._emacs_oneliner_vars_pat.search(head)
  472. if match:
  473. emacs_vars_str = match.group(1)
  474. assert '\n' not in emacs_vars_str
  475. emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';')
  476. if s.strip()]
  477. if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]:
  478. # While not in the spec, this form is allowed by emacs:
  479. # -*- Tcl -*-
  480. # where the implied "variable" is "mode". This form
  481. # is only allowed if there are no other variables.
  482. emacs_vars["mode"] = emacs_var_strs[0].strip()
  483. else:
  484. for emacs_var_str in emacs_var_strs:
  485. try:
  486. variable, value = emacs_var_str.strip().split(':', 1)
  487. except ValueError:
  488. log.debug("emacs variables error: malformed -*- "
  489. "line: %r", emacs_var_str)
  490. continue
  491. # Lowercase the variable name because Emacs allows "Mode"
  492. # or "mode" or "MoDe", etc.
  493. emacs_vars[variable.lower()] = value.strip()
  494. tail = text[-SIZE:]
  495. if "Local Variables" in tail:
  496. match = self._emacs_local_vars_pat.search(tail)
  497. if match:
  498. prefix = match.group("prefix")
  499. suffix = match.group("suffix")
  500. lines = match.group("content").splitlines(0)
  501. # print "prefix=%r, suffix=%r, content=%r, lines: %s"\
  502. # % (prefix, suffix, match.group("content"), lines)
  503. # Validate the Local Variables block: proper prefix and suffix
  504. # usage.
  505. for i, line in enumerate(lines):
  506. if not line.startswith(prefix):
  507. log.debug("emacs variables error: line '%s' "
  508. "does not use proper prefix '%s'"
  509. % (line, prefix))
  510. return {}
  511. # Don't validate suffix on last line. Emacs doesn't care,
  512. # neither should we.
  513. if i != len(lines)-1 and not line.endswith(suffix):
  514. log.debug("emacs variables error: line '%s' "
  515. "does not use proper suffix '%s'"
  516. % (line, suffix))
  517. return {}
  518. # Parse out one emacs var per line.
  519. continued_for = None
  520. for line in lines[:-1]: # no var on the last line ("PREFIX End:")
  521. if prefix: line = line[len(prefix):] # strip prefix
  522. if suffix: line = line[:-len(suffix)] # strip suffix
  523. line = line.strip()
  524. if continued_for:
  525. variable = continued_for
  526. if line.endswith('\\'):
  527. line = line[:-1].rstrip()
  528. else:
  529. continued_for = None
  530. emacs_vars[variable] += ' ' + line
  531. else:
  532. try:
  533. variable, value = line.split(':', 1)
  534. except ValueError:
  535. log.debug("local variables error: missing colon "
  536. "in local variables entry: '%s'" % line)
  537. continue
  538. # Do NOT lowercase the variable name, because Emacs only
  539. # allows "mode" (and not "Mode", "MoDe", etc.) in this block.
  540. value = value.strip()
  541. if value.endswith('\\'):
  542. value = value[:-1].rstrip()
  543. continued_for = variable
  544. else:
  545. continued_for = None
  546. emacs_vars[variable] = value
  547. # Unquote values.
  548. for var, val in list(emacs_vars.items()):
  549. if len(val) > 1 and (val.startswith('"') and val.endswith('"')
  550. or val.startswith('"') and val.endswith('"')):
  551. emacs_vars[var] = val[1:-1]
  552. return emacs_vars
  553. def _detab_line(self, line):
  554. r"""Recusively convert tabs to spaces in a single line.
  555. Called from _detab()."""
  556. if '\t' not in line:
  557. return line
  558. chunk1, chunk2 = line.split('\t', 1)
  559. chunk1 += (' ' * (self.tab_width - len(chunk1) % self.tab_width))
  560. output = chunk1 + chunk2
  561. return self._detab_line(output)
  562. def _detab(self, text):
  563. r"""Iterate text line by line and convert tabs to spaces.
  564. >>> m = Markdown()
  565. >>> m._detab("\tfoo")
  566. ' foo'
  567. >>> m._detab(" \tfoo")
  568. ' foo'
  569. >>> m._detab("\t foo")
  570. ' foo'
  571. >>> m._detab(" foo")
  572. ' foo'
  573. >>> m._detab(" foo\n\tbar\tblam")
  574. ' foo\n bar blam'
  575. """
  576. if '\t' not in text:
  577. return text
  578. output = []
  579. for line in text.splitlines():
  580. output.append(self._detab_line(line))
  581. return '\n'.join(output)
  582. # I broke out the html5 tags here and add them to _block_tags_a and
  583. # _block_tags_b. This way html5 tags are easy to keep track of.
  584. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption'
  585. _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del'
  586. _block_tags_a += _html5tags
  587. _strict_tag_block_re = re.compile(r"""
  588. ( # save in \1
  589. ^ # start of line (with re.M)
  590. <(%s) # start tag = \2
  591. \b # word break
  592. (.*\n)*? # any number of lines, minimally matching
  593. </\2> # the matching end tag
  594. [ \t]* # trailing spaces/tabs
  595. (?=\n+|\Z) # followed by a newline or end of document
  596. )
  597. """ % _block_tags_a,
  598. re.X | re.M)
  599. _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math'
  600. _block_tags_b += _html5tags
  601. _liberal_tag_block_re = re.compile(r"""
  602. ( # save in \1
  603. ^ # start of line (with re.M)
  604. <(%s) # start tag = \2
  605. \b # word break
  606. (.*\n)*? # any number of lines, minimally matching
  607. .*</\2> # the matching end tag
  608. [ \t]* # trailing spaces/tabs
  609. (?=\n+|\Z) # followed by a newline or end of document
  610. )
  611. """ % _block_tags_b,
  612. re.X | re.M)
  613. _html_markdown_attr_re = re.compile(
  614. r'''\s+markdown=("1"|'1')''')
  615. def _hash_html_block_sub(self, match, raw=False):
  616. html = match.group(1)
  617. if raw and self.safe_mode:
  618. html = self._sanitize_html(html)
  619. elif 'markdown-in-html' in self.extras and 'markdown=' in html:
  620. first_line = html.split('\n', 1)[0]
  621. m = self._html_markdown_attr_re.search(first_line)
  622. if m:
  623. lines = html.split('\n')
  624. middle = '\n'.join(lines[1:-1])
  625. last_line = lines[-1]
  626. first_line = first_line[:m.start()] + first_line[m.end():]
  627. f_key = _hash_text(first_line)
  628. self.html_blocks[f_key] = first_line
  629. l_key = _hash_text(last_line)
  630. self.html_blocks[l_key] = last_line
  631. return ''.join(["\n\n", f_key,
  632. "\n\n", middle, "\n\n",
  633. l_key, "\n\n"])
  634. key = _hash_text(html)
  635. self.html_blocks[key] = html
  636. return "\n\n" + key + "\n\n"
  637. def _hash_html_blocks(self, text, raw=False):
  638. """Hashify HTML blocks
  639. We only want to do this for block-level HTML tags, such as headers,
  640. lists, and tables. That's because we still want to wrap <p>s around
  641. "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  642. phrase emphasis, and spans. The list of tags we're looking for is
  643. hard-coded.
  644. @param raw {boolean} indicates if these are raw HTML blocks in
  645. the original source. It makes a difference in "safe" mode.
  646. """
  647. if '<' not in text:
  648. return text
  649. # Pass `raw` value into our calls to self._hash_html_block_sub.
  650. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw)
  651. # First, look for nested blocks, e.g.:
  652. # <div>
  653. # <div>
  654. # tags for inner block must be indented.
  655. # </div>
  656. # </div>
  657. #
  658. # The outermost tags must start at the left margin for this to match, and
  659. # the inner nested divs must be indented.
  660. # We need to do this before the next, more liberal match, because the next
  661. # match will start at the first `<div>` and stop at the first `</div>`.
  662. text = self._strict_tag_block_re.sub(hash_html_block_sub, text)
  663. # Now match more liberally, simply from `\n<tag>` to `</tag>\n`
  664. text = self._liberal_tag_block_re.sub(hash_html_block_sub, text)
  665. # Special case just for <hr />. It was easier to make a special
  666. # case than to make the other regex more complicated.
  667. if "<hr" in text:
  668. _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width)
  669. text = _hr_tag_re.sub(hash_html_block_sub, text)
  670. # Special case for standalone HTML comments:
  671. if "<!--" in text:
  672. start = 0
  673. while True:
  674. # Delimiters for next comment block.
  675. try:
  676. start_idx = text.index("<!--", start)
  677. except ValueError:
  678. break
  679. try:
  680. end_idx = text.index("-->", start_idx) + 3
  681. except ValueError:
  682. break
  683. # Start position for next comment block search.
  684. start = end_idx
  685. # Validate whitespace before comment.
  686. if start_idx:
  687. # - Up to `tab_width - 1` spaces before start_idx.
  688. for i in range(self.tab_width - 1):
  689. if text[start_idx - 1] != ' ':
  690. break
  691. start_idx -= 1
  692. if start_idx == 0:
  693. break
  694. # - Must be preceded by 2 newlines or hit the start of
  695. # the document.
  696. if start_idx == 0:
  697. pass
  698. elif start_idx == 1 and text[0] == '\n':
  699. start_idx = 0 # to match minute detail of Markdown.pl regex
  700. elif text[start_idx-2:start_idx] == '\n\n':
  701. pass
  702. else:
  703. break
  704. # Validate whitespace after comment.
  705. # - Any number of spaces and tabs.
  706. while end_idx < len(text):
  707. if text[end_idx] not in ' \t':
  708. break
  709. end_idx += 1
  710. # - Must be following by 2 newlines or hit end of text.
  711. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'):
  712. continue
  713. # Escape and hash (must match `_hash_html_block_sub`).
  714. html = text[start_idx:end_idx]
  715. if raw and self.safe_mode:
  716. html = self._sanitize_html(html)
  717. key = _hash_text(html)
  718. self.html_blocks[key] = html
  719. text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:]
  720. if "xml" in self.extras:
  721. # Treat XML processing instructions and namespaced one-liner
  722. # tags as if they were block HTML tags. E.g., if standalone
  723. # (i.e. are their own paragraph), the following do not get
  724. # wrapped in a <p> tag:
  725. # <?foo bar?>
  726. #
  727. # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/>
  728. _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width)
  729. text = _xml_oneliner_re.sub(hash_html_block_sub, text)
  730. return text
  731. def _strip_link_definitions(self, text):
  732. # Strips link definitions from text, stores the URLs and titles in
  733. # hash references.
  734. less_than_tab = self.tab_width - 1
  735. # Link defs are in the form:
  736. # [id]: url "optional title"
  737. _link_def_re = re.compile(r"""
  738. ^[ ]{0,%d}\[(.+)\]: # id = \1
  739. [ \t]*
  740. \n? # maybe *one* newline
  741. [ \t]*
  742. <?(.+?)>? # url = \2
  743. [ \t]*
  744. (?:
  745. \n? # maybe one newline
  746. [ \t]*
  747. (?<=\s) # lookbehind for whitespace
  748. ['"(]
  749. ([^\n]*) # title = \3
  750. ['")]
  751. [ \t]*
  752. )? # title is optional
  753. (?:\n+|\Z)
  754. """ % less_than_tab, re.X | re.M | re.U)
  755. return _link_def_re.sub(self._extract_link_def_sub, text)
  756. def _extract_link_def_sub(self, match):
  757. id, url, title = match.groups()
  758. key = id.lower() # Link IDs are case-insensitive
  759. self.urls[key] = self._encode_amps_and_angles(url)
  760. if title:
  761. self.titles[key] = title
  762. return ""
  763. def _do_numbering(self, text):
  764. ''' We handle the special extension for generic numbering for
  765. tables, figures etc.
  766. '''
  767. # First pass to define all the references
  768. self.regex_defns = re.compile(r'''
  769. \[\#(\w+) # the counter. Open square plus hash plus a word \1
  770. ([^@]*) # Some optional characters, that aren't an @. \2
  771. @(\w+) # the id. Should this be normed? \3
  772. ([^\]]*)\] # The rest of the text up to the terminating ] \4
  773. ''', re.VERBOSE)
  774. self.regex_subs = re.compile(r"\[@(\w+)\s*\]") # [@ref_id]
  775. counters = {}
  776. references = {}
  777. replacements = []
  778. definition_html = '<figcaption class="{}" id="counter-ref-{}">{}{}{}</figcaption>'
  779. reference_html = '<a class="{}" href="#counter-ref-{}">{}</a>'
  780. for match in self.regex_defns.finditer(text):
  781. # We must have four match groups otherwise this isn't a numbering reference
  782. if len(match.groups()) != 4:
  783. continue
  784. counter = match.group(1)
  785. text_before = match.group(2).strip()
  786. ref_id = match.group(3)
  787. text_after = match.group(4)
  788. number = counters.get(counter, 1)
  789. references[ref_id] = (number, counter)
  790. replacements.append((match.start(0),
  791. definition_html.format(counter,
  792. ref_id,
  793. text_before,
  794. number,
  795. text_after),
  796. match.end(0)))
  797. counters[counter] = number + 1
  798. for repl in reversed(replacements):
  799. text = text[:repl[0]] + repl[1] + text[repl[2]:]
  800. # Second pass to replace the references with the right
  801. # value of the counter
  802. # Fwiw, it's vaguely annoying to have to turn the iterator into
  803. # a list and then reverse it but I can't think of a better thing to do.
  804. for match in reversed(list(self.regex_subs.finditer(text))):
  805. number, counter = references.get(match.group(1), (None, None))
  806. if number is not None:
  807. repl = reference_html.format(counter,
  808. match.group(1),
  809. number)
  810. else:
  811. repl = reference_html.format(match.group(1),
  812. 'countererror',
  813. '?' + match.group(1) + '?')
  814. if "smarty-pants" in self.extras:
  815. repl = repl.replace('"', self._escape_table['"'])
  816. text = text[:match.start()] + repl + text[match.end():]
  817. return text
  818. def _extract_footnote_def_sub(self, match):
  819. id, text = match.groups()
  820. text = _dedent(text, skip_first_line=not text.startswith('\n')).strip()
  821. normed_id = re.sub(r'\W', '-', id)
  822. # Ensure footnote text ends with a couple newlines (for some
  823. # block gamut matches).
  824. self.footnotes[normed_id] = text + "\n\n"
  825. return ""
  826. def _strip_footnote_definitions(self, text):
  827. """A footnote definition looks like this:
  828. [^note-id]: Text of the note.
  829. May include one or more indented paragraphs.
  830. Where,
  831. - The 'note-id' can be pretty much anything, though typically it
  832. is the number of the footnote.
  833. - The first paragraph may start on the next line, like so:
  834. [^note-id]:
  835. Text of the note.
  836. """
  837. less_than_tab = self.tab_width - 1
  838. footnote_def_re = re.compile(r'''
  839. ^[ ]{0,%d}\[\^(.+)\]: # id = \1
  840. [ \t]*
  841. ( # footnote text = \2
  842. # First line need not start with the spaces.
  843. (?:\s*.*\n+)
  844. (?:
  845. (?:[ ]{%d} | \t) # Subsequent lines must be indented.
  846. .*\n+
  847. )*
  848. )
  849. # Lookahead for non-space at line-start, or end of doc.
  850. (?:(?=^[ ]{0,%d}\S)|\Z)
  851. ''' % (less_than_tab, self.tab_width, self.tab_width),
  852. re.X | re.M)
  853. return footnote_def_re.sub(self._extract_footnote_def_sub, text)
  854. _hr_re = re.compile(r'^[ ]{0,3}([-_*][ ]{0,2}){3,}$', re.M)
  855. def _run_block_gamut(self, text):
  856. # These are all the transformations that form block-level
  857. # tags like paragraphs, headers, and list items.
  858. if "fenced-code-blocks" in self.extras:
  859. text = self._do_fenced_code_blocks(text)
  860. text = self._do_headers(text)
  861. # Do Horizontal Rules:
  862. # On the number of spaces in horizontal rules: The spec is fuzzy: "If
  863. # you wish, you may use spaces between the hyphens or asterisks."
  864. # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the
  865. # hr chars to one or two. We'll reproduce that limit here.
  866. hr = "\n<hr"+self.empty_element_suffix+"\n"
  867. text = re.sub(self._hr_re, hr, text)
  868. text = self._do_lists(text)
  869. if "pyshell" in self.extras:
  870. text = self._prepare_pyshell_blocks(text)
  871. if "wiki-tables" in self.extras:
  872. text = self._do_wiki_tables(text)
  873. if "tables" in self.extras:
  874. text = self._do_tables(text)
  875. text = self._do_code_blocks(text)
  876. text = self._do_block_quotes(text)
  877. # We already ran _HashHTMLBlocks() before, in Markdown(), but that
  878. # was to escape raw HTML in the original Markdown source. This time,
  879. # we're escaping the markup we've just created, so that we don't wrap
  880. # <p> tags around block-level tags.
  881. text = self._hash_html_blocks(text)
  882. text = self._form_paragraphs(text)
  883. return text
  884. def _pyshell_block_sub(self, match):
  885. if "fenced-code-blocks" in self.extras:
  886. dedented = _dedent(match.group(0))
  887. return self._do_fenced_code_blocks("```pycon\n" + dedented + "```\n")
  888. lines = match.group(0).splitlines(0)
  889. _dedentlines(lines)
  890. indent = ' ' * self.tab_width
  891. s = ('\n' # separate from possible cuddled paragraph
  892. + indent + ('\n'+indent).join(lines)
  893. + '\n\n')
  894. return s
  895. def _prepare_pyshell_blocks(self, text):
  896. """Ensure that Python interactive shell sessions are put in
  897. code blocks -- even if not properly indented.
  898. """
  899. if ">>>" not in text:
  900. return text
  901. less_than_tab = self.tab_width - 1
  902. _pyshell_block_re = re.compile(r"""
  903. ^([ ]{0,%d})>>>[ ].*\n # first line
  904. ^(\1.*\S+.*\n)* # any number of subsequent lines
  905. ^\n # ends with a blank line
  906. """ % less_than_tab, re.M | re.X)
  907. return _pyshell_block_re.sub(self._pyshell_block_sub, text)
  908. def _table_sub(self, match):
  909. trim_space_re = '^[ \t\n]+|[ \t\n]+$'
  910. trim_bar_re = r'^\||\|$'
  911. split_bar_re = r'^\||(?<!\\)\|'
  912. escape_bar_re = r'\\\|'
  913. head, underline, body = match.groups()
  914. # Determine aligns for columns.
  915. cols = [re.sub(escape_bar_re, '|', cell.strip()) for cell in re.split(split_bar_re, re.sub(trim_bar_re, "", re.sub(trim_space_re, "", underline)))]
  916. align_from_col_idx = {}
  917. for col_idx, col in enumerate(cols):
  918. if col[0] == ':' and col[-1] == ':':
  919. align_from_col_idx[col_idx] = ' style="text-align:center;"'
  920. elif col[0] == ':':
  921. align_from_col_idx[col_idx] = ' style="text-align:left;"'
  922. elif col[-1] == ':':
  923. align_from_col_idx[col_idx] = ' style="text-align:right;"'
  924. # thead
  925. hlines = ['<table%s>' % self._html_class_str_from_tag('table'), '<thead>', '<tr>']
  926. cols = [re.sub(escape_bar_re, '|', cell.strip()) for cell in re.split(split_bar_re, re.sub(trim_bar_re, "", re.sub(trim_space_re, "", head)))]
  927. for col_idx, col in enumerate(cols):
  928. hlines.append(' <th%s>%s</th>' % (
  929. align_from_col_idx.get(col_idx, ''),
  930. self._run_span_gamut(col)
  931. ))
  932. hlines.append('</tr>')
  933. hlines.append('</thead>')
  934. # tbody
  935. hlines.append('<tbody>')
  936. for line in body.strip('\n').split('\n'):
  937. hlines.append('<tr>')
  938. cols = [re.sub(escape_bar_re, '|', cell.strip()) for cell in re.split(split_bar_re, re.sub(trim_bar_re, "", re.sub(trim_space_re, "", line)))]
  939. for col_idx, col in enumerate(cols):
  940. hlines.append(' <td%s>%s</td>' % (
  941. align_from_col_idx.get(col_idx, ''),
  942. self._run_span_gamut(col)
  943. ))
  944. hlines.append('</tr>')
  945. hlines.append('</tbody>')
  946. hlines.append('</table>')
  947. return '\n'.join(hlines) + '\n'
  948. def _do_tables(self, text):
  949. """Copying PHP-Markdown and GFM table syntax. Some regex borrowed from
  950. https://github.com/michelf/php-markdown/blob/lib/Michelf/Markdown.php#L2538
  951. """
  952. less_than_tab = self.tab_width - 1
  953. table_re = re.compile(r'''
  954. (?:(?<=\n\n)|\A\n?) # leading blank line
  955. ^[ ]{0,%d} # allowed whitespace
  956. (.*[|].*) \n # $1: header row (at least one pipe)
  957. ^[ ]{0,%d} # allowed whitespace
  958. ( # $2: underline row
  959. # underline row with leading bar
  960. (?: \|\ *:?-+:?\ * )+ \|? \s? \n
  961. |
  962. # or, underline row without leading bar
  963. (?: \ *:?-+:?\ *\| )+ (?: \ *:?-+:?\ * )? \s? \n
  964. )
  965. ( # $3: data rows
  966. (?:
  967. ^[ ]{0,%d}(?!\ ) # ensure line begins with 0 to less_than_tab spaces
  968. .*\|.* \n
  969. )+
  970. )
  971. ''' % (less_than_tab, less_than_tab, less_than_tab), re.M | re.X)
  972. return table_re.sub(self._table_sub, text)
  973. def _wiki_table_sub(self, match):
  974. ttext = match.group(0).strip()
  975. # print('wiki table: %r' % match.group(0))
  976. rows = []
  977. for line in ttext.splitlines(0):
  978. line = line.strip()[2:-2].strip()
  979. row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)]
  980. rows.append(row)
  981. # from pprint import pprint
  982. # pprint(rows)
  983. hlines = []
  984. def add_hline(line, indents=0):
  985. hlines.append((self.tab * indents) + line)
  986. def format_cell(text):
  987. return self._run_span_gamut(re.sub(r"^\s*~", "", cell).strip(" "))
  988. add_hline('<table%s>' % self._html_class_str_from_tag('table'))
  989. # Check if first cell of first row is a header cell. If so, assume the whole row is a header row.
  990. if rows and rows[0] and re.match(r"^\s*~", rows[0][0]):
  991. add_hline('<thead>', 1)
  992. add_hline('<tr>', 2)
  993. for cell in rows[0]:
  994. add_hline("<th>{}</th>".format(format_cell(cell)), 3)
  995. add_hline('</tr>', 2)
  996. add_hline('</thead>', 1)
  997. # Only one header row allowed.
  998. rows = rows[1:]
  999. # If no more rows, don't create a tbody.
  1000. if rows:
  1001. add_hline('<tbody>', 1)
  1002. for row in rows:
  1003. add_hline('<tr>', 2)
  1004. for cell in row:
  1005. add_hline('<td>{}</td>'.format(format_cell(cell)), 3)
  1006. add_hline('</tr>', 2)
  1007. add_hline('</tbody>', 1)
  1008. add_hline('</table>')
  1009. return '\n'.join(hlines) + '\n'
  1010. def _do_wiki_tables(self, text):
  1011. # Optimization.
  1012. if "||" not in text:
  1013. return text
  1014. less_than_tab = self.tab_width - 1
  1015. wiki_table_re = re.compile(r'''
  1016. (?:(?<=\n\n)|\A\n?) # leading blank line
  1017. ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line
  1018. (^\1\|\|.+?\|\|\n)* # any number of subsequent lines
  1019. ''' % less_than_tab, re.M | re.X)
  1020. return wiki_table_re.sub(self._wiki_table_sub, text)
  1021. def _run_span_gamut(self, text):
  1022. # These are all the transformations that occur *within* block-level
  1023. # tags like paragraphs, headers, and list items.
  1024. text = self._do_code_spans(text)
  1025. text = self._escape_special_chars(text)
  1026. # Process anchor and image tags.
  1027. if "link-patterns" in self.extras:
  1028. text = self._do_link_patterns(text)
  1029. text = self._do_links(text)
  1030. # Make links out of things like `<http://example.com/>`
  1031. # Must come after _do_links(), because you can use < and >
  1032. # delimiters in inline links like [this](<url>).
  1033. text = self._do_auto_links(text)
  1034. text = self._encode_amps_and_angles(text)
  1035. if "strike" in self.extras:
  1036. text = self._do_strike(text)
  1037. if "underline" in self.extras:
  1038. text = self._do_underline(text)
  1039. text = self._do_italics_and_bold(text)
  1040. if "smarty-pants" in self.extras:
  1041. text = self._do_smart_punctuation(text)
  1042. # Do hard breaks:
  1043. if "break-on-newline" in self.extras:
  1044. text = re.sub(r" *\n", "<br%s\n" % self.empty_element_suffix, text)
  1045. else:
  1046. text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text)
  1047. return text
  1048. # "Sorta" because auto-links are identified as "tag" tokens.
  1049. _sorta_html_tokenize_re = re.compile(r"""
  1050. (
  1051. # tag
  1052. </?
  1053. (?:\w+) # tag name
  1054. (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes
  1055. \s*/?>
  1056. |
  1057. # auto-link (e.g., <http://www.activestate.com/>)
  1058. <[\w~:/?#\[\]@!$&'\(\)*+,;%=\.\\-]+>
  1059. |
  1060. <!

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