PageRenderTime 52ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/markdown/inlinepatterns.py

https://github.com/broady/cuter
Python | 371 lines | 336 code | 14 blank | 21 comment | 11 complexity | 0f6e93b03128ac2a38288e72f28ebff1 MD5 | raw file
  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. import markdown
  32. import re
  33. from urlparse import urlparse, urlunparse
  34. import sys
  35. if sys.version >= "3.0":
  36. from html import entities as htmlentitydefs
  37. else:
  38. import htmlentitydefs
  39. """
  40. The actual regular expressions for patterns
  41. -----------------------------------------------------------------------------
  42. """
  43. NOBRACKET = r'[^\]\[]*'
  44. BRK = ( r'\[('
  45. + (NOBRACKET + r'(\[')*6
  46. + (NOBRACKET+ r'\])*')*6
  47. + NOBRACKET + r')\]' )
  48. NOIMG = r'(?<!\!)'
  49. BACKTICK_RE = r'(?<!\\)(`+)(.+?)(?<!`)\2(?!`)' # `e=f()` or ``e=f("`")``
  50. ESCAPE_RE = r'\\(.)' # \<
  51. EMPHASIS_RE = r'(\*)([^\*]+)\2' # *emphasis*
  52. STRONG_RE = r'(\*{2}|_{2})(.+?)\2' # **strong**
  53. STRONG_EM_RE = r'(\*{3}|_{3})(.+?)\2' # ***strong***
  54. if markdown.SMART_EMPHASIS:
  55. EMPHASIS_2_RE = r'(?<!\w)(_)(\S.+?)\2(?!\w)' # _emphasis_
  56. else:
  57. EMPHASIS_2_RE = r'(_)(.+?)\2' # _emphasis_
  58. LINK_RE = NOIMG + BRK + \
  59. r'''\(\s*(<.*?>|((?:(?:\(.*?\))|[^\(\)]))*?)\s*((['"])(.*?)\12)?\)'''
  60. # [text](url) or [text](<url>)
  61. IMAGE_LINK_RE = r'\!' + BRK + r'\s*\((<.*?>|([^\)]*))\)'
  62. # ![alttxt](http://x.com/) or ![alttxt](<http://x.com/>)
  63. REFERENCE_RE = NOIMG + BRK+ r'\s*\[([^\]]*)\]' # [Google][3]
  64. IMAGE_REFERENCE_RE = r'\!' + BRK + '\s*\[([^\]]*)\]' # ![alt text][2]
  65. NOT_STRONG_RE = r'((^| )(\*|_)( |$))' # stand-alone * or _
  66. AUTOLINK_RE = r'<((?:f|ht)tps?://[^>]*)>' # <http://www.123.com>
  67. AUTOMAIL_RE = r'<([^> \!]*@[^> ]*)>' # <me@example.com>
  68. HTML_RE = r'(\<([a-zA-Z/][^\>]*?|\!--.*?--)\>)' # <...>
  69. ENTITY_RE = r'(&[\#a-zA-Z0-9]*;)' # &amp;
  70. LINE_BREAK_RE = r' \n' # two spaces at end of line
  71. LINE_BREAK_2_RE = r' $' # two spaces at end of text
  72. def dequote(string):
  73. """Remove quotes from around a string."""
  74. if ( ( string.startswith('"') and string.endswith('"'))
  75. or (string.startswith("'") and string.endswith("'")) ):
  76. return string[1:-1]
  77. else:
  78. return string
  79. ATTR_RE = re.compile("\{@([^\}]*)=([^\}]*)}") # {@id=123}
  80. def handleAttributes(text, parent):
  81. """Set values of an element based on attribute definitions ({@id=123})."""
  82. def attributeCallback(match):
  83. parent.set(match.group(1), match.group(2).replace('\n', ' '))
  84. return ATTR_RE.sub(attributeCallback, text)
  85. """
  86. The pattern classes
  87. -----------------------------------------------------------------------------
  88. """
  89. class Pattern:
  90. """Base class that inline patterns subclass. """
  91. def __init__ (self, pattern, markdown_instance=None):
  92. """
  93. Create an instant of an inline pattern.
  94. Keyword arguments:
  95. * pattern: A regular expression that matches a pattern
  96. """
  97. self.pattern = pattern
  98. self.compiled_re = re.compile("^(.*?)%s(.*?)$" % pattern, re.DOTALL)
  99. # Api for Markdown to pass safe_mode into instance
  100. self.safe_mode = False
  101. if markdown_instance:
  102. self.markdown = markdown_instance
  103. def getCompiledRegExp (self):
  104. """ Return a compiled regular expression. """
  105. return self.compiled_re
  106. def handleMatch(self, m):
  107. """Return a ElementTree element from the given match.
  108. Subclasses should override this method.
  109. Keyword arguments:
  110. * m: A re match object containing a match of the pattern.
  111. """
  112. pass
  113. def type(self):
  114. """ Return class name, to define pattern type """
  115. return self.__class__.__name__
  116. BasePattern = Pattern # for backward compatibility
  117. class SimpleTextPattern (Pattern):
  118. """ Return a simple text of group(2) of a Pattern. """
  119. def handleMatch(self, m):
  120. text = m.group(2)
  121. if text == markdown.INLINE_PLACEHOLDER_PREFIX:
  122. return None
  123. return text
  124. class SimpleTagPattern (Pattern):
  125. """
  126. Return element of type `tag` with a text attribute of group(3)
  127. of a Pattern.
  128. """
  129. def __init__ (self, pattern, tag):
  130. Pattern.__init__(self, pattern)
  131. self.tag = tag
  132. def handleMatch(self, m):
  133. el = markdown.etree.Element(self.tag)
  134. el.text = m.group(3)
  135. return el
  136. class SubstituteTagPattern (SimpleTagPattern):
  137. """ Return a eLement of type `tag` with no children. """
  138. def handleMatch (self, m):
  139. return markdown.etree.Element(self.tag)
  140. class BacktickPattern (Pattern):
  141. """ Return a `<code>` element containing the matching text. """
  142. def __init__ (self, pattern):
  143. Pattern.__init__(self, pattern)
  144. self.tag = "code"
  145. def handleMatch(self, m):
  146. el = markdown.etree.Element(self.tag)
  147. el.text = markdown.AtomicString(m.group(3).strip())
  148. return el
  149. class DoubleTagPattern (SimpleTagPattern):
  150. """Return a ElementTree element nested in tag2 nested in tag1.
  151. Useful for strong emphasis etc.
  152. """
  153. def handleMatch(self, m):
  154. tag1, tag2 = self.tag.split(",")
  155. el1 = markdown.etree.Element(tag1)
  156. el2 = markdown.etree.SubElement(el1, tag2)
  157. el2.text = m.group(3)
  158. return el1
  159. class HtmlPattern (Pattern):
  160. """ Store raw inline html and return a placeholder. """
  161. def handleMatch (self, m):
  162. rawhtml = m.group(2)
  163. inline = True
  164. place_holder = self.markdown.htmlStash.store(rawhtml)
  165. return place_holder
  166. class LinkPattern (Pattern):
  167. """ Return a link element from the given match. """
  168. def handleMatch(self, m):
  169. el = markdown.etree.Element("a")
  170. el.text = m.group(2)
  171. title = m.group(11)
  172. href = m.group(9)
  173. if href:
  174. if href[0] == "<":
  175. href = href[1:-1]
  176. el.set("href", self.sanitize_url(href.strip()))
  177. else:
  178. el.set("href", "")
  179. if title:
  180. title = dequote(title) #.replace('"', "&quot;")
  181. el.set("title", title)
  182. return el
  183. def sanitize_url(self, url):
  184. """
  185. Sanitize a url against xss attacks in "safe_mode".
  186. Rather than specifically blacklisting `javascript:alert("XSS")` and all
  187. its aliases (see <http://ha.ckers.org/xss.html>), we whitelist known
  188. safe url formats. Most urls contain a network location, however some
  189. are known not to (i.e.: mailto links). Script urls do not contain a
  190. location. Additionally, for `javascript:...`, the scheme would be
  191. "javascript" but some aliases will appear to `urlparse()` to have no
  192. scheme. On top of that relative links (i.e.: "foo/bar.html") have no
  193. scheme. Therefore we must check "path", "parameters", "query" and
  194. "fragment" for any literal colons. We don't check "scheme" for colons
  195. because it *should* never have any and "netloc" must allow the form:
  196. `username:password@host:port`.
  197. """
  198. locless_schemes = ['', 'mailto', 'news']
  199. scheme, netloc, path, params, query, fragment = url = urlparse(url)
  200. safe_url = False
  201. if netloc != '' or scheme in locless_schemes:
  202. safe_url = True
  203. for part in url[2:]:
  204. if ":" in part:
  205. safe_url = False
  206. if self.markdown.safeMode and not safe_url:
  207. return ''
  208. else:
  209. return urlunparse(url)
  210. class ImagePattern(LinkPattern):
  211. """ Return a img element from the given match. """
  212. def handleMatch(self, m):
  213. el = markdown.etree.Element("img")
  214. src_parts = m.group(9).split()
  215. if src_parts:
  216. src = src_parts[0]
  217. if src[0] == "<" and src[-1] == ">":
  218. src = src[1:-1]
  219. el.set('src', self.sanitize_url(src))
  220. else:
  221. el.set('src', "")
  222. if len(src_parts) > 1:
  223. el.set('title', dequote(" ".join(src_parts[1:])))
  224. if markdown.ENABLE_ATTRIBUTES:
  225. truealt = handleAttributes(m.group(2), el)
  226. else:
  227. truealt = m.group(2)
  228. el.set('alt', truealt)
  229. return el
  230. class ReferencePattern(LinkPattern):
  231. """ Match to a stored reference and return link element. """
  232. def handleMatch(self, m):
  233. if m.group(9):
  234. id = m.group(9).lower()
  235. else:
  236. # if we got something like "[Google][]"
  237. # we'll use "google" as the id
  238. id = m.group(2).lower()
  239. if not id in self.markdown.references: # ignore undefined refs
  240. return None
  241. href, title = self.markdown.references[id]
  242. text = m.group(2)
  243. return self.makeTag(href, title, text)
  244. def makeTag(self, href, title, text):
  245. el = markdown.etree.Element('a')
  246. el.set('href', self.sanitize_url(href))
  247. if title:
  248. el.set('title', title)
  249. el.text = text
  250. return el
  251. class ImageReferencePattern (ReferencePattern):
  252. """ Match to a stored reference and return img element. """
  253. def makeTag(self, href, title, text):
  254. el = markdown.etree.Element("img")
  255. el.set("src", self.sanitize_url(href))
  256. if title:
  257. el.set("title", title)
  258. el.set("alt", text)
  259. return el
  260. class AutolinkPattern (Pattern):
  261. """ Return a link Element given an autolink (`<http://example/com>`). """
  262. def handleMatch(self, m):
  263. el = markdown.etree.Element("a")
  264. el.set('href', m.group(2))
  265. el.text = markdown.AtomicString(m.group(2))
  266. return el
  267. class AutomailPattern (Pattern):
  268. """
  269. Return a mailto link Element given an automail link (`<foo@example.com>`).
  270. """
  271. def handleMatch(self, m):
  272. el = markdown.etree.Element('a')
  273. email = m.group(2)
  274. if email.startswith("mailto:"):
  275. email = email[len("mailto:"):]
  276. def codepoint2name(code):
  277. """Return entity definition by code, or the code if not defined."""
  278. entity = htmlentitydefs.codepoint2name.get(code)
  279. if entity:
  280. return "%s%s;" % (markdown.AMP_SUBSTITUTE, entity)
  281. else:
  282. return "%s#%d;" % (markdown.AMP_SUBSTITUTE, code)
  283. letters = [codepoint2name(ord(letter)) for letter in email]
  284. el.text = markdown.AtomicString(''.join(letters))
  285. mailto = "mailto:" + email
  286. mailto = "".join([markdown.AMP_SUBSTITUTE + '#%d;' %
  287. ord(letter) for letter in mailto])
  288. el.set('href', mailto)
  289. return el