treeprocessors.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. # markdown is released under the BSD license
  2. # Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later)
  3. # Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
  4. # Copyright 2004 Manfred Stienstra (the original version)
  5. #
  6. # All rights reserved.
  7. #
  8. # Redistribution and use in source and binary forms, with or without
  9. # modification, are permitted provided that the following conditions are met:
  10. #
  11. # * Redistributions of source code must retain the above copyright
  12. # notice, this list of conditions and the following disclaimer.
  13. # * Redistributions in binary form must reproduce the above copyright
  14. # notice, this list of conditions and the following disclaimer in the
  15. # documentation and/or other materials provided with the distribution.
  16. # * Neither the name of the <organization> nor the
  17. # names of its contributors may be used to endorse or promote products
  18. # derived from this software without specific prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE PYTHON MARKDOWN PROJECT ''AS IS'' AND ANY
  21. # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  22. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  23. # DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTORS TO THE PYTHON MARKDOWN PROJECT
  24. # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30. # POSSIBILITY OF SUCH DAMAGE.
  31. from __future__ import unicode_literals
  32. from __future__ import absolute_import
  33. from . import util
  34. from . import odict
  35. from . import inlinepatterns
  36. def build_treeprocessors(md_instance, **kwargs):
  37. """ Build the default treeprocessors for Markdown. """
  38. treeprocessors = odict.OrderedDict()
  39. treeprocessors["inline"] = InlineProcessor(md_instance)
  40. treeprocessors["prettify"] = PrettifyTreeprocessor(md_instance)
  41. return treeprocessors
  42. def isString(s):
  43. """ Check if it's string """
  44. if not isinstance(s, util.AtomicString):
  45. return isinstance(s, util.string_type)
  46. return False
  47. class Treeprocessor(util.Processor):
  48. """
  49. Treeprocessors are run on the ElementTree object before serialization.
  50. Each Treeprocessor implements a "run" method that takes a pointer to an
  51. ElementTree, modifies it as necessary and returns an ElementTree
  52. object.
  53. Treeprocessors must extend markdown.Treeprocessor.
  54. """
  55. def run(self, root):
  56. """
  57. Subclasses of Treeprocessor should implement a `run` method, which
  58. takes a root ElementTree. This method can return another ElementTree
  59. object, and the existing root ElementTree will be replaced, or it can
  60. modify the current tree and return None.
  61. """
  62. pass
  63. class InlineProcessor(Treeprocessor):
  64. """
  65. A Treeprocessor that traverses a tree, applying inline patterns.
  66. """
  67. def __init__(self, md):
  68. self.__placeholder_prefix = util.INLINE_PLACEHOLDER_PREFIX
  69. self.__placeholder_suffix = util.ETX
  70. self.__placeholder_length = 4 + len(self.__placeholder_prefix) \
  71. + len(self.__placeholder_suffix)
  72. self.__placeholder_re = util.INLINE_PLACEHOLDER_RE
  73. self.markdown = md
  74. def __makePlaceholder(self, type):
  75. """ Generate a placeholder """
  76. id = "%04d" % len(self.stashed_nodes)
  77. hash = util.INLINE_PLACEHOLDER % id
  78. return hash, id
  79. def __findPlaceholder(self, data, index):
  80. """
  81. Extract id from data string, start from index
  82. Keyword arguments:
  83. * data: string
  84. * index: index, from which we start search
  85. Returns: placeholder id and string index, after the found placeholder.
  86. """
  87. m = self.__placeholder_re.search(data, index)
  88. if m:
  89. return m.group(1), m.end()
  90. else:
  91. return None, index + 1
  92. def __stashNode(self, node, type):
  93. """ Add node to stash """
  94. placeholder, id = self.__makePlaceholder(type)
  95. self.stashed_nodes[id] = node
  96. return placeholder
  97. def __handleInline(self, data, patternIndex=0):
  98. """
  99. Process string with inline patterns and replace it
  100. with placeholders
  101. Keyword arguments:
  102. * data: A line of Markdown text
  103. * patternIndex: The index of the inlinePattern to start with
  104. Returns: String with placeholders.
  105. """
  106. if not isinstance(data, util.AtomicString):
  107. startIndex = 0
  108. while patternIndex < len(self.markdown.inlinePatterns):
  109. data, matched, startIndex = self.__applyPattern(
  110. self.markdown.inlinePatterns.value_for_index(patternIndex),
  111. data, patternIndex, startIndex)
  112. if not matched:
  113. patternIndex += 1
  114. return data
  115. def __processElementText(self, node, subnode, isText=True):
  116. """
  117. Process placeholders in Element.text or Element.tail
  118. of Elements popped from self.stashed_nodes.
  119. Keywords arguments:
  120. * node: parent node
  121. * subnode: processing node
  122. * isText: bool variable, True - it's text, False - it's tail
  123. Returns: None
  124. """
  125. if isText:
  126. text = subnode.text
  127. subnode.text = None
  128. else:
  129. text = subnode.tail
  130. subnode.tail = None
  131. childResult = self.__processPlaceholders(text, subnode)
  132. if not isText and node is not subnode:
  133. pos = list(node).index(subnode)
  134. node.remove(subnode)
  135. else:
  136. pos = 0
  137. childResult.reverse()
  138. for newChild in childResult:
  139. node.insert(pos, newChild)
  140. def __processPlaceholders(self, data, parent):
  141. """
  142. Process string with placeholders and generate ElementTree tree.
  143. Keyword arguments:
  144. * data: string with placeholders instead of ElementTree elements.
  145. * parent: Element, which contains processing inline data
  146. Returns: list with ElementTree elements with applied inline patterns.
  147. """
  148. def linkText(text):
  149. if text:
  150. if result:
  151. if result[-1].tail:
  152. result[-1].tail += text
  153. else:
  154. result[-1].tail = text
  155. else:
  156. if parent.text:
  157. parent.text += text
  158. else:
  159. parent.text = text
  160. result = []
  161. strartIndex = 0
  162. while data:
  163. index = data.find(self.__placeholder_prefix, strartIndex)
  164. if index != -1:
  165. id, phEndIndex = self.__findPlaceholder(data, index)
  166. if id in self.stashed_nodes:
  167. node = self.stashed_nodes.get(id)
  168. if index > 0:
  169. text = data[strartIndex:index]
  170. linkText(text)
  171. if not isString(node): # it's Element
  172. for child in [node] + list(node):
  173. if child.tail:
  174. if child.tail.strip():
  175. self.__processElementText(node, child,False)
  176. if child.text:
  177. if child.text.strip():
  178. self.__processElementText(child, child)
  179. else: # it's just a string
  180. linkText(node)
  181. strartIndex = phEndIndex
  182. continue
  183. strartIndex = phEndIndex
  184. result.append(node)
  185. else: # wrong placeholder
  186. end = index + len(self.__placeholder_prefix)
  187. linkText(data[strartIndex:end])
  188. strartIndex = end
  189. else:
  190. text = data[strartIndex:]
  191. if isinstance(data, util.AtomicString):
  192. # We don't want to loose the AtomicString
  193. text = util.AtomicString(text)
  194. linkText(text)
  195. data = ""
  196. return result
  197. def __applyPattern(self, pattern, data, patternIndex, startIndex=0):
  198. """
  199. Check if the line fits the pattern, create the necessary
  200. elements, add it to stashed_nodes.
  201. Keyword arguments:
  202. * data: the text to be processed
  203. * pattern: the pattern to be checked
  204. * patternIndex: index of current pattern
  205. * startIndex: string index, from which we start searching
  206. Returns: String with placeholders instead of ElementTree elements.
  207. """
  208. match = pattern.getCompiledRegExp().match(data[startIndex:])
  209. leftData = data[:startIndex]
  210. if not match:
  211. return data, False, 0
  212. node = pattern.handleMatch(match)
  213. if node is None:
  214. return data, True, len(leftData)+match.span(len(match.groups()))[0]
  215. if not isString(node):
  216. if not isinstance(node.text, util.AtomicString):
  217. # We need to process current node too
  218. for child in [node] + list(node):
  219. if not isString(node):
  220. if child.text:
  221. child.text = self.__handleInline(child.text,
  222. patternIndex + 1)
  223. if child.tail:
  224. child.tail = self.__handleInline(child.tail,
  225. patternIndex)
  226. placeholder = self.__stashNode(node, pattern.type())
  227. return "%s%s%s%s" % (leftData,
  228. match.group(1),
  229. placeholder, match.groups()[-1]), True, 0
  230. def run(self, tree):
  231. """Apply inline patterns to a parsed Markdown tree.
  232. Iterate over ElementTree, find elements with inline tag, apply inline
  233. patterns and append newly created Elements to tree. If you don't
  234. want to process your data with inline paterns, instead of normal string,
  235. use subclass AtomicString:
  236. node.text = markdown.AtomicString("This will not be processed.")
  237. Arguments:
  238. * tree: ElementTree object, representing Markdown tree.
  239. Returns: ElementTree object with applied inline patterns.
  240. """
  241. self.stashed_nodes = {}
  242. stack = [tree]
  243. while stack:
  244. currElement = stack.pop()
  245. insertQueue = []
  246. for child in currElement:
  247. if child.text and not isinstance(child.text, util.AtomicString):
  248. text = child.text
  249. child.text = None
  250. lst = self.__processPlaceholders(self.__handleInline(
  251. text), child)
  252. stack += lst
  253. insertQueue.append((child, lst))
  254. if child.tail:
  255. tail = self.__handleInline(child.tail)
  256. dumby = util.etree.Element('d')
  257. tailResult = self.__processPlaceholders(tail, dumby)
  258. if dumby.text:
  259. child.tail = dumby.text
  260. else:
  261. child.tail = None
  262. pos = list(currElement).index(child) + 1
  263. tailResult.reverse()
  264. for newChild in tailResult:
  265. currElement.insert(pos, newChild)
  266. if list(child):
  267. stack.append(child)
  268. for element, lst in insertQueue:
  269. if self.markdown.enable_attributes:
  270. if element.text and isString(element.text):
  271. element.text = \
  272. inlinepatterns.handleAttributes(element.text,
  273. element)
  274. i = 0
  275. for newChild in lst:
  276. if self.markdown.enable_attributes:
  277. # Processing attributes
  278. if newChild.tail and isString(newChild.tail):
  279. newChild.tail = \
  280. inlinepatterns.handleAttributes(newChild.tail,
  281. element)
  282. if newChild.text and isString(newChild.text):
  283. newChild.text = \
  284. inlinepatterns.handleAttributes(newChild.text,
  285. newChild)
  286. element.insert(i, newChild)
  287. i += 1
  288. return tree
  289. class PrettifyTreeprocessor(Treeprocessor):
  290. """ Add linebreaks to the html document. """
  291. def _prettifyETree(self, elem):
  292. """ Recursively add linebreaks to ElementTree children. """
  293. i = "\n"
  294. if util.isBlockLevel(elem.tag) and elem.tag not in ['code', 'pre']:
  295. if (not elem.text or not elem.text.strip()) \
  296. and len(elem) and util.isBlockLevel(elem[0].tag):
  297. elem.text = i
  298. for e in elem:
  299. if util.isBlockLevel(e.tag):
  300. self._prettifyETree(e)
  301. if not elem.tail or not elem.tail.strip():
  302. elem.tail = i
  303. if not elem.tail or not elem.tail.strip():
  304. elem.tail = i
  305. def run(self, root):
  306. """ Add linebreaks to ElementTree root object. """
  307. self._prettifyETree(root)
  308. # Do <br />'s seperately as they are often in the middle of
  309. # inline content and missed by _prettifyETree.
  310. brs = root.iter('br')
  311. for br in brs:
  312. if not br.tail or not br.tail.strip():
  313. br.tail = '\n'
  314. else:
  315. br.tail = '\n%s' % br.tail
  316. # Clean up extra empty lines at end of code blocks.
  317. pres = root.iter('pre')
  318. for pre in pres:
  319. if len(pre) and pre[0].tag == 'code':
  320. pre[0].text = pre[0].text.rstrip() + '\n'