You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

536 lines
17 KiB

4 years ago
  1. """
  2. INLINE PATTERNS
  3. =============================================================================
  4. Inline patterns such as *emphasis* are handled by means of auxiliary
  5. objects, one per pattern. Pattern objects must be instances of classes
  6. that extend markdown.Pattern. Each pattern object uses a single regular
  7. expression and needs support the following methods:
  8. pattern.getCompiledRegExp() # returns a regular expression
  9. pattern.handleMatch(m) # takes a match object and returns
  10. # an ElementTree element or just plain text
  11. All of python markdown's built-in patterns subclass from Pattern,
  12. but you can add additional patterns that don't.
  13. Also note that all the regular expressions used by inline must
  14. capture the whole block. For this reason, they all start with
  15. '^(.*)' and end with '(.*)!'. In case with built-in expression
  16. Pattern takes care of adding the "^(.*)" and "(.*)!".
  17. Finally, the order in which regular expressions are applied is very
  18. important - e.g. if we first replace http://.../ links with <a> tags
  19. and _then_ try to replace inline html, we would end up with a mess.
  20. So, we apply the expressions in the following order:
  21. * escape and backticks have to go before everything else, so
  22. that we can preempt any markdown patterns by escaping them.
  23. * then we handle auto-links (must be done before inline html)
  24. * then we handle inline HTML. At this point we will simply
  25. replace all inline HTML strings with a placeholder and add
  26. the actual HTML to a hash.
  27. * then inline images (must be done before links)
  28. * then bracketed links, first regular then reference-style
  29. * finally we apply strong and emphasis
  30. """
  31. from __future__ import absolute_import
  32. from __future__ import unicode_literals
  33. from . import util
  34. from . import odict
  35. import re
  36. try: # pragma: no cover
  37. from urllib.parse import urlparse, urlunparse
  38. except ImportError: # pragma: no cover
  39. from urlparse import urlparse, urlunparse
  40. try: # pragma: no cover
  41. from html import entities
  42. except ImportError: # pragma: no cover
  43. import htmlentitydefs as entities
  44. def build_inlinepatterns(md_instance, **kwargs):
  45. """ Build the default set of inline patterns for Markdown. """
  46. inlinePatterns = odict.OrderedDict()
  47. inlinePatterns["backtick"] = BacktickPattern(BACKTICK_RE)
  48. inlinePatterns["escape"] = EscapePattern(ESCAPE_RE, md_instance)
  49. inlinePatterns["reference"] = ReferencePattern(REFERENCE_RE, md_instance)
  50. inlinePatterns["link"] = LinkPattern(LINK_RE, md_instance)
  51. inlinePatterns["image_link"] = ImagePattern(IMAGE_LINK_RE, md_instance)
  52. inlinePatterns["image_reference"] = ImageReferencePattern(
  53. IMAGE_REFERENCE_RE, md_instance
  54. )
  55. inlinePatterns["short_reference"] = ReferencePattern(
  56. SHORT_REF_RE, md_instance
  57. )
  58. inlinePatterns["autolink"] = AutolinkPattern(AUTOLINK_RE, md_instance)
  59. inlinePatterns["automail"] = AutomailPattern(AUTOMAIL_RE, md_instance)
  60. inlinePatterns["linebreak"] = SubstituteTagPattern(LINE_BREAK_RE, 'br')
  61. if md_instance.safeMode != 'escape':
  62. inlinePatterns["html"] = HtmlPattern(HTML_RE, md_instance)
  63. inlinePatterns["entity"] = HtmlPattern(ENTITY_RE, md_instance)
  64. inlinePatterns["not_strong"] = SimpleTextPattern(NOT_STRONG_RE)
  65. inlinePatterns["em_strong"] = DoubleTagPattern(EM_STRONG_RE, 'strong,em')
  66. inlinePatterns["strong_em"] = DoubleTagPattern(STRONG_EM_RE, 'em,strong')
  67. inlinePatterns["strong"] = SimpleTagPattern(STRONG_RE, 'strong')
  68. inlinePatterns["emphasis"] = SimpleTagPattern(EMPHASIS_RE, 'em')
  69. if md_instance.smart_emphasis:
  70. inlinePatterns["emphasis2"] = SimpleTagPattern(SMART_EMPHASIS_RE, 'em')
  71. else:
  72. inlinePatterns["emphasis2"] = SimpleTagPattern(EMPHASIS_2_RE, 'em')
  73. return inlinePatterns
  74. """
  75. The actual regular expressions for patterns
  76. -----------------------------------------------------------------------------
  77. """
  78. NOBRACKET = r'[^\]\[]*'
  79. BRK = (
  80. r'\[(' +
  81. (NOBRACKET + r'(\[')*6 +
  82. (NOBRACKET + r'\])*')*6 +
  83. NOBRACKET + r')\]'
  84. )
  85. NOIMG = r'(?<!\!)'
  86. # `e=f()` or ``e=f("`")``
  87. BACKTICK_RE = r'(?:(?<!\\)((?:\\{2})+)(?=`+)|(?<!\\)(`+)(.+?)(?<!`)\3(?!`))'
  88. # \<
  89. ESCAPE_RE = r'\\(.)'
  90. # *emphasis*
  91. EMPHASIS_RE = r'(\*)([^\*]+)\2'
  92. # **strong**
  93. STRONG_RE = r'(\*{2}|_{2})(.+?)\2'
  94. # ***strongem*** or ***em*strong**
  95. EM_STRONG_RE = r'(\*|_)\2{2}(.+?)\2(.*?)\2{2}'
  96. # ***strong**em*
  97. STRONG_EM_RE = r'(\*|_)\2{2}(.+?)\2{2}(.*?)\2'
  98. # _smart_emphasis_
  99. SMART_EMPHASIS_RE = r'(?<!\w)(_)(?!_)(.+?)(?<!_)\2(?!\w)'
  100. # _emphasis_
  101. EMPHASIS_2_RE = r'(_)(.+?)\2'
  102. # [text](url) or [text](<url>) or [text](url "title")
  103. LINK_RE = NOIMG + BRK + \
  104. r'''\(\s*(<.*?>|((?:(?:\(.*?\))|[^\(\)]))*?)\s*((['"])(.*?)\12\s*)?\)'''
  105. # ![alttxt](http://x.com/) or ![alttxt](<http://x.com/>)
  106. IMAGE_LINK_RE = r'\!' + BRK + r'\s*\(\s*(<.*?>|([^"\)\s]+\s*"[^"]*"|[^\)\s]*))\s*\)'
  107. # [Google][3]
  108. REFERENCE_RE = NOIMG + BRK + r'\s?\[([^\]]*)\]'
  109. # [Google]
  110. SHORT_REF_RE = NOIMG + r'\[([^\]]+)\]'
  111. # ![alt text][2]
  112. IMAGE_REFERENCE_RE = r'\!' + BRK + r'\s?\[([^\]]*)\]'
  113. # stand-alone * or _
  114. NOT_STRONG_RE = r'((^| )(\*|_)( |$))'
  115. # <http://www.123.com>
  116. AUTOLINK_RE = r'<((?:[Ff]|[Hh][Tt])[Tt][Pp][Ss]?://[^>]*)>'
  117. # <me@example.com>
  118. AUTOMAIL_RE = r'<([^> \!]*@[^> ]*)>'
  119. # <...>
  120. HTML_RE = r'(\<([a-zA-Z/][^\>]*?|\!--.*?--)\>)'
  121. # &amp;
  122. ENTITY_RE = r'(&[\#a-zA-Z0-9]*;)'
  123. # two spaces at end of line
  124. LINE_BREAK_RE = r' \n'
  125. def dequote(string):
  126. """Remove quotes from around a string."""
  127. if ((string.startswith('"') and string.endswith('"')) or
  128. (string.startswith("'") and string.endswith("'"))):
  129. return string[1:-1]
  130. else:
  131. return string
  132. ATTR_RE = re.compile(r"\{@([^\}]*)=([^\}]*)}") # {@id=123}
  133. def handleAttributes(text, parent):
  134. """Set values of an element based on attribute definitions ({@id=123})."""
  135. def attributeCallback(match):
  136. parent.set(match.group(1), match.group(2).replace('\n', ' '))
  137. return ATTR_RE.sub(attributeCallback, text)
  138. """
  139. The pattern classes
  140. -----------------------------------------------------------------------------
  141. """
  142. class Pattern(object):
  143. """Base class that inline patterns subclass. """
  144. ANCESTOR_EXCLUDES = tuple()
  145. def __init__(self, pattern, markdown_instance=None):
  146. """
  147. Create an instant of an inline pattern.
  148. Keyword arguments:
  149. * pattern: A regular expression that matches a pattern
  150. """
  151. self.pattern = pattern
  152. self.compiled_re = re.compile(r"^(.*?)%s(.*)$" % pattern,
  153. re.DOTALL | re.UNICODE)
  154. # Api for Markdown to pass safe_mode into instance
  155. self.safe_mode = False
  156. if markdown_instance:
  157. self.markdown = markdown_instance
  158. def getCompiledRegExp(self):
  159. """ Return a compiled regular expression. """
  160. return self.compiled_re
  161. def handleMatch(self, m):
  162. """Return a ElementTree element from the given match.
  163. Subclasses should override this method.
  164. Keyword arguments:
  165. * m: A re match object containing a match of the pattern.
  166. """
  167. pass # pragma: no cover
  168. def type(self):
  169. """ Return class name, to define pattern type """
  170. return self.__class__.__name__
  171. def unescape(self, text):
  172. """ Return unescaped text given text with an inline placeholder. """
  173. try:
  174. stash = self.markdown.treeprocessors['inline'].stashed_nodes
  175. except KeyError: # pragma: no cover
  176. return text
  177. def itertext(el): # pragma: no cover
  178. ' Reimplement Element.itertext for older python versions '
  179. tag = el.tag
  180. if not isinstance(tag, util.string_type) and tag is not None:
  181. return
  182. if el.text:
  183. yield el.text
  184. for e in el:
  185. for s in itertext(e):
  186. yield s
  187. if e.tail:
  188. yield e.tail
  189. def get_stash(m):
  190. id = m.group(1)
  191. if id in stash:
  192. value = stash.get(id)
  193. if isinstance(value, util.string_type):
  194. return value
  195. else:
  196. # An etree Element - return text content only
  197. return ''.join(itertext(value))
  198. return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
  199. class SimpleTextPattern(Pattern):
  200. """ Return a simple text of group(2) of a Pattern. """
  201. def handleMatch(self, m):
  202. return m.group(2)
  203. class EscapePattern(Pattern):
  204. """ Return an escaped character. """
  205. def handleMatch(self, m):
  206. char = m.group(2)
  207. if char in self.markdown.ESCAPED_CHARS:
  208. return '%s%s%s' % (util.STX, ord(char), util.ETX)
  209. else:
  210. return None
  211. class SimpleTagPattern(Pattern):
  212. """
  213. Return element of type `tag` with a text attribute of group(3)
  214. of a Pattern.
  215. """
  216. def __init__(self, pattern, tag):
  217. Pattern.__init__(self, pattern)
  218. self.tag = tag
  219. def handleMatch(self, m):
  220. el = util.etree.Element(self.tag)
  221. el.text = m.group(3)
  222. return el
  223. class SubstituteTagPattern(SimpleTagPattern):
  224. """ Return an element of type `tag` with no children. """
  225. def handleMatch(self, m):
  226. return util.etree.Element(self.tag)
  227. class BacktickPattern(Pattern):
  228. """ Return a `<code>` element containing the matching text. """
  229. def __init__(self, pattern):
  230. Pattern.__init__(self, pattern)
  231. self.ESCAPED_BSLASH = '%s%s%s' % (util.STX, ord('\\'), util.ETX)
  232. self.tag = 'code'
  233. def handleMatch(self, m):
  234. if m.group(4):
  235. el = util.etree.Element(self.tag)
  236. el.text = util.AtomicString(m.group(4).strip())
  237. return el
  238. else:
  239. return m.group(2).replace('\\\\', self.ESCAPED_BSLASH)
  240. class DoubleTagPattern(SimpleTagPattern):
  241. """Return a ElementTree element nested in tag2 nested in tag1.
  242. Useful for strong emphasis etc.
  243. """
  244. def handleMatch(self, m):
  245. tag1, tag2 = self.tag.split(",")
  246. el1 = util.etree.Element(tag1)
  247. el2 = util.etree.SubElement(el1, tag2)
  248. el2.text = m.group(3)
  249. if len(m.groups()) == 5:
  250. el2.tail = m.group(4)
  251. return el1
  252. class HtmlPattern(Pattern):
  253. """ Store raw inline html and return a placeholder. """
  254. def handleMatch(self, m):
  255. rawhtml = self.unescape(m.group(2))
  256. place_holder = self.markdown.htmlStash.store(rawhtml)
  257. return place_holder
  258. def unescape(self, text):
  259. """ Return unescaped text given text with an inline placeholder. """
  260. try:
  261. stash = self.markdown.treeprocessors['inline'].stashed_nodes
  262. except KeyError: # pragma: no cover
  263. return text
  264. def get_stash(m):
  265. id = m.group(1)
  266. value = stash.get(id)
  267. if value is not None:
  268. try:
  269. return self.markdown.serializer(value)
  270. except Exception:
  271. return r'\%s' % value
  272. return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
  273. class LinkPattern(Pattern):
  274. """ Return a link element from the given match. """
  275. def handleMatch(self, m):
  276. el = util.etree.Element("a")
  277. el.text = m.group(2)
  278. title = m.group(13)
  279. href = m.group(9)
  280. if href:
  281. if href[0] == "<":
  282. href = href[1:-1]
  283. el.set("href", self.sanitize_url(self.unescape(href.strip())))
  284. else:
  285. el.set("href", "")
  286. if title:
  287. title = dequote(self.unescape(title))
  288. el.set("title", title)
  289. return el
  290. def sanitize_url(self, url):
  291. """
  292. Sanitize a url against xss attacks in "safe_mode".
  293. Rather than specifically blacklisting `javascript:alert("XSS")` and all
  294. its aliases (see <http://ha.ckers.org/xss.html>), we whitelist known
  295. safe url formats. Most urls contain a network location, however some
  296. are known not to (i.e.: mailto links). Script urls do not contain a
  297. location. Additionally, for `javascript:...`, the scheme would be
  298. "javascript" but some aliases will appear to `urlparse()` to have no
  299. scheme. On top of that relative links (i.e.: "foo/bar.html") have no
  300. scheme. Therefore we must check "path", "parameters", "query" and
  301. "fragment" for any literal colons. We don't check "scheme" for colons
  302. because it *should* never have any and "netloc" must allow the form:
  303. `username:password@host:port`.
  304. """
  305. if not self.markdown.safeMode:
  306. # Return immediately bipassing parsing.
  307. return url
  308. try:
  309. scheme, netloc, path, params, query, fragment = url = urlparse(url)
  310. except ValueError: # pragma: no cover
  311. # Bad url - so bad it couldn't be parsed.
  312. return ''
  313. locless_schemes = ['', 'mailto', 'news']
  314. allowed_schemes = locless_schemes + ['http', 'https', 'ftp', 'ftps']
  315. if scheme not in allowed_schemes:
  316. # Not a known (allowed) scheme. Not safe.
  317. return ''
  318. if netloc == '' and scheme not in locless_schemes: # pragma: no cover
  319. # This should not happen. Treat as suspect.
  320. return ''
  321. for part in url[2:]:
  322. if ":" in part:
  323. # A colon in "path", "parameters", "query"
  324. # or "fragment" is suspect.
  325. return ''
  326. # Url passes all tests. Return url as-is.
  327. return urlunparse(url)
  328. class ImagePattern(LinkPattern):
  329. """ Return a img element from the given match. """
  330. def handleMatch(self, m):
  331. el = util.etree.Element("img")
  332. src_parts = m.group(9).split()
  333. if src_parts:
  334. src = src_parts[0]
  335. if src[0] == "<" and src[-1] == ">":
  336. src = src[1:-1]
  337. el.set('src', self.sanitize_url(self.unescape(src)))
  338. else:
  339. el.set('src', "")
  340. if len(src_parts) > 1:
  341. el.set('title', dequote(self.unescape(" ".join(src_parts[1:]))))
  342. if self.markdown.enable_attributes:
  343. truealt = handleAttributes(m.group(2), el)
  344. else:
  345. truealt = m.group(2)
  346. el.set('alt', self.unescape(truealt))
  347. return el
  348. class ReferencePattern(LinkPattern):
  349. """ Match to a stored reference and return link element. """
  350. NEWLINE_CLEANUP_RE = re.compile(r'[ ]?\n', re.MULTILINE)
  351. def handleMatch(self, m):
  352. try:
  353. id = m.group(9).lower()
  354. except IndexError:
  355. id = None
  356. if not id:
  357. # if we got something like "[Google][]" or "[Google]"
  358. # we'll use "google" as the id
  359. id = m.group(2).lower()
  360. # Clean up linebreaks in id
  361. id = self.NEWLINE_CLEANUP_RE.sub(' ', id)
  362. if id not in self.markdown.references: # ignore undefined refs
  363. return None
  364. href, title = self.markdown.references[id]
  365. text = m.group(2)
  366. return self.makeTag(href, title, text)
  367. def makeTag(self, href, title, text):
  368. el = util.etree.Element('a')
  369. el.set('href', self.sanitize_url(href))
  370. if title:
  371. el.set('title', title)
  372. el.text = text
  373. return el
  374. class ImageReferencePattern(ReferencePattern):
  375. """ Match to a stored reference and return img element. """
  376. def makeTag(self, href, title, text):
  377. el = util.etree.Element("img")
  378. el.set("src", self.sanitize_url(href))
  379. if title:
  380. el.set("title", title)
  381. if self.markdown.enable_attributes:
  382. text = handleAttributes(text, el)
  383. el.set("alt", self.unescape(text))
  384. return el
  385. class AutolinkPattern(Pattern):
  386. """ Return a link Element given an autolink (`<http://example/com>`). """
  387. def handleMatch(self, m):
  388. el = util.etree.Element("a")
  389. el.set('href', self.unescape(m.group(2)))
  390. el.text = util.AtomicString(m.group(2))
  391. return el
  392. class AutomailPattern(Pattern):
  393. """
  394. Return a mailto link Element given an automail link (`<foo@example.com>`).
  395. """
  396. def handleMatch(self, m):
  397. el = util.etree.Element('a')
  398. email = self.unescape(m.group(2))
  399. if email.startswith("mailto:"):
  400. email = email[len("mailto:"):]
  401. def codepoint2name(code):
  402. """Return entity definition by code, or the code if not defined."""
  403. entity = entities.codepoint2name.get(code)
  404. if entity:
  405. return "%s%s;" % (util.AMP_SUBSTITUTE, entity)
  406. else:
  407. return "%s#%d;" % (util.AMP_SUBSTITUTE, code)
  408. letters = [codepoint2name(ord(letter)) for letter in email]
  409. el.text = util.AtomicString(''.join(letters))
  410. mailto = "mailto:" + email
  411. mailto = "".join([util.AMP_SUBSTITUTE + '#%d;' %
  412. ord(letter) for letter in mailto])
  413. el.set('href', mailto)
  414. return el