treeprocessors.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. """
  2. Python Markdown
  3. A Python implementation of John Gruber's Markdown.
  4. Documentation: https://python-markdown.github.io/
  5. GitHub: https://github.com/Python-Markdown/markdown/
  6. PyPI: https://pypi.org/project/Markdown/
  7. Started by Manfred Stienstra (http://www.dwerg.net/).
  8. Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
  9. Currently maintained by Waylan Limberg (https://github.com/waylan),
  10. Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
  11. Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
  12. Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
  13. Copyright 2004 Manfred Stienstra (the original version)
  14. License: BSD (see LICENSE.md for details).
  15. """
  16. import xml.etree.ElementTree as etree
  17. from . import util
  18. from . import inlinepatterns
  19. def build_treeprocessors(md, **kwargs):
  20. """ Build the default treeprocessors for Markdown. """
  21. treeprocessors = util.Registry()
  22. treeprocessors.register(InlineProcessor(md), 'inline', 20)
  23. treeprocessors.register(PrettifyTreeprocessor(md), 'prettify', 10)
  24. return treeprocessors
  25. def isString(s):
  26. """ Check if it's string """
  27. if not isinstance(s, util.AtomicString):
  28. return isinstance(s, str)
  29. return False
  30. class Treeprocessor(util.Processor):
  31. """
  32. Treeprocessors are run on the ElementTree object before serialization.
  33. Each Treeprocessor implements a "run" method that takes a pointer to an
  34. ElementTree, modifies it as necessary and returns an ElementTree
  35. object.
  36. Treeprocessors must extend markdown.Treeprocessor.
  37. """
  38. def run(self, root):
  39. """
  40. Subclasses of Treeprocessor should implement a `run` method, which
  41. takes a root ElementTree. This method can return another ElementTree
  42. object, and the existing root ElementTree will be replaced, or it can
  43. modify the current tree and return None.
  44. """
  45. pass # pragma: no cover
  46. class InlineProcessor(Treeprocessor):
  47. """
  48. A Treeprocessor that traverses a tree, applying inline patterns.
  49. """
  50. def __init__(self, md):
  51. self.__placeholder_prefix = util.INLINE_PLACEHOLDER_PREFIX
  52. self.__placeholder_suffix = util.ETX
  53. self.__placeholder_length = 4 + len(self.__placeholder_prefix) \
  54. + len(self.__placeholder_suffix)
  55. self.__placeholder_re = util.INLINE_PLACEHOLDER_RE
  56. self.md = md
  57. self.inlinePatterns = md.inlinePatterns
  58. self.ancestors = []
  59. @property
  60. @util.deprecated("Use 'md' instead.")
  61. def markdown(self):
  62. # TODO: remove this later
  63. return self.md
  64. def __makePlaceholder(self, type):
  65. """ Generate a placeholder """
  66. id = "%04d" % len(self.stashed_nodes)
  67. hash = util.INLINE_PLACEHOLDER % id
  68. return hash, id
  69. def __findPlaceholder(self, data, index):
  70. """
  71. Extract id from data string, start from index
  72. Keyword arguments:
  73. * data: string
  74. * index: index, from which we start search
  75. Returns: placeholder id and string index, after the found placeholder.
  76. """
  77. m = self.__placeholder_re.search(data, index)
  78. if m:
  79. return m.group(1), m.end()
  80. else:
  81. return None, index + 1
  82. def __stashNode(self, node, type):
  83. """ Add node to stash """
  84. placeholder, id = self.__makePlaceholder(type)
  85. self.stashed_nodes[id] = node
  86. return placeholder
  87. def __handleInline(self, data, patternIndex=0):
  88. """
  89. Process string with inline patterns and replace it
  90. with placeholders
  91. Keyword arguments:
  92. * data: A line of Markdown text
  93. * patternIndex: The index of the inlinePattern to start with
  94. Returns: String with placeholders.
  95. """
  96. if not isinstance(data, util.AtomicString):
  97. startIndex = 0
  98. while patternIndex < len(self.inlinePatterns):
  99. data, matched, startIndex = self.__applyPattern(
  100. self.inlinePatterns[patternIndex], data, patternIndex, startIndex
  101. )
  102. if not matched:
  103. patternIndex += 1
  104. return data
  105. def __processElementText(self, node, subnode, isText=True):
  106. """
  107. Process placeholders in Element.text or Element.tail
  108. of Elements popped from self.stashed_nodes.
  109. Keywords arguments:
  110. * node: parent node
  111. * subnode: processing node
  112. * isText: bool variable, True - it's text, False - it's tail
  113. Returns: None
  114. """
  115. if isText:
  116. text = subnode.text
  117. subnode.text = None
  118. else:
  119. text = subnode.tail
  120. subnode.tail = None
  121. childResult = self.__processPlaceholders(text, subnode, isText)
  122. if not isText and node is not subnode:
  123. pos = list(node).index(subnode) + 1
  124. else:
  125. pos = 0
  126. childResult.reverse()
  127. for newChild in childResult:
  128. node.insert(pos, newChild[0])
  129. def __processPlaceholders(self, data, parent, isText=True):
  130. """
  131. Process string with placeholders and generate ElementTree tree.
  132. Keyword arguments:
  133. * data: string with placeholders instead of ElementTree elements.
  134. * parent: Element, which contains processing inline data
  135. Returns: list with ElementTree elements with applied inline patterns.
  136. """
  137. def linkText(text):
  138. if text:
  139. if result:
  140. if result[-1][0].tail:
  141. result[-1][0].tail += text
  142. else:
  143. result[-1][0].tail = text
  144. elif not isText:
  145. if parent.tail:
  146. parent.tail += text
  147. else:
  148. parent.tail = text
  149. else:
  150. if parent.text:
  151. parent.text += text
  152. else:
  153. parent.text = text
  154. result = []
  155. strartIndex = 0
  156. while data:
  157. index = data.find(self.__placeholder_prefix, strartIndex)
  158. if index != -1:
  159. id, phEndIndex = self.__findPlaceholder(data, index)
  160. if id in self.stashed_nodes:
  161. node = self.stashed_nodes.get(id)
  162. if index > 0:
  163. text = data[strartIndex:index]
  164. linkText(text)
  165. if not isString(node): # it's Element
  166. for child in [node] + list(node):
  167. if child.tail:
  168. if child.tail.strip():
  169. self.__processElementText(
  170. node, child, False
  171. )
  172. if child.text:
  173. if child.text.strip():
  174. self.__processElementText(child, child)
  175. else: # it's just a string
  176. linkText(node)
  177. strartIndex = phEndIndex
  178. continue
  179. strartIndex = phEndIndex
  180. result.append((node, self.ancestors[:]))
  181. else: # wrong placeholder
  182. end = index + len(self.__placeholder_prefix)
  183. linkText(data[strartIndex:end])
  184. strartIndex = end
  185. else:
  186. text = data[strartIndex:]
  187. if isinstance(data, util.AtomicString):
  188. # We don't want to loose the AtomicString
  189. text = util.AtomicString(text)
  190. linkText(text)
  191. data = ""
  192. return result
  193. def __applyPattern(self, pattern, data, patternIndex, startIndex=0):
  194. """
  195. Check if the line fits the pattern, create the necessary
  196. elements, add it to stashed_nodes.
  197. Keyword arguments:
  198. * data: the text to be processed
  199. * pattern: the pattern to be checked
  200. * patternIndex: index of current pattern
  201. * startIndex: string index, from which we start searching
  202. Returns: String with placeholders instead of ElementTree elements.
  203. """
  204. new_style = isinstance(pattern, inlinepatterns.InlineProcessor)
  205. for exclude in pattern.ANCESTOR_EXCLUDES:
  206. if exclude.lower() in self.ancestors:
  207. return data, False, 0
  208. if new_style:
  209. match = None
  210. # Since handleMatch may reject our first match,
  211. # we iterate over the buffer looking for matches
  212. # until we can't find any more.
  213. for match in pattern.getCompiledRegExp().finditer(data, startIndex):
  214. node, start, end = pattern.handleMatch(match, data)
  215. if start is None or end is None:
  216. startIndex += match.end(0)
  217. match = None
  218. continue
  219. break
  220. else: # pragma: no cover
  221. match = pattern.getCompiledRegExp().match(data[startIndex:])
  222. leftData = data[:startIndex]
  223. if not match:
  224. return data, False, 0
  225. if not new_style: # pragma: no cover
  226. node = pattern.handleMatch(match)
  227. start = match.start(0)
  228. end = match.end(0)
  229. if node is None:
  230. return data, True, end
  231. if not isString(node):
  232. if not isinstance(node.text, util.AtomicString):
  233. # We need to process current node too
  234. for child in [node] + list(node):
  235. if not isString(node):
  236. if child.text:
  237. self.ancestors.append(child.tag.lower())
  238. child.text = self.__handleInline(
  239. child.text, patternIndex + 1
  240. )
  241. self.ancestors.pop()
  242. if child.tail:
  243. child.tail = self.__handleInline(
  244. child.tail, patternIndex
  245. )
  246. placeholder = self.__stashNode(node, pattern.type())
  247. if new_style:
  248. return "{}{}{}".format(data[:start],
  249. placeholder, data[end:]), True, 0
  250. else: # pragma: no cover
  251. return "{}{}{}{}".format(leftData,
  252. match.group(1),
  253. placeholder, match.groups()[-1]), True, 0
  254. def __build_ancestors(self, parent, parents):
  255. """Build the ancestor list."""
  256. ancestors = []
  257. while parent is not None:
  258. if parent is not None:
  259. ancestors.append(parent.tag.lower())
  260. parent = self.parent_map.get(parent)
  261. ancestors.reverse()
  262. parents.extend(ancestors)
  263. def run(self, tree, ancestors=None):
  264. """Apply inline patterns to a parsed Markdown tree.
  265. Iterate over ElementTree, find elements with inline tag, apply inline
  266. patterns and append newly created Elements to tree. If you don't
  267. want to process your data with inline paterns, instead of normal
  268. string, use subclass AtomicString:
  269. node.text = markdown.AtomicString("This will not be processed.")
  270. Arguments:
  271. * tree: ElementTree object, representing Markdown tree.
  272. * ancestors: List of parent tag names that precede the tree node (if needed).
  273. Returns: ElementTree object with applied inline patterns.
  274. """
  275. self.stashed_nodes = {}
  276. # Ensure a valid parent list, but copy passed in lists
  277. # to ensure we don't have the user accidentally change it on us.
  278. tree_parents = [] if ancestors is None else ancestors[:]
  279. self.parent_map = {c: p for p in tree.iter() for c in p}
  280. stack = [(tree, tree_parents)]
  281. while stack:
  282. currElement, parents = stack.pop()
  283. self.ancestors = parents
  284. self.__build_ancestors(currElement, self.ancestors)
  285. insertQueue = []
  286. for child in currElement:
  287. if child.text and not isinstance(
  288. child.text, util.AtomicString
  289. ):
  290. self.ancestors.append(child.tag.lower())
  291. text = child.text
  292. child.text = None
  293. lst = self.__processPlaceholders(
  294. self.__handleInline(text), child
  295. )
  296. for l in lst:
  297. self.parent_map[l[0]] = child
  298. stack += lst
  299. insertQueue.append((child, lst))
  300. self.ancestors.pop()
  301. if child.tail:
  302. tail = self.__handleInline(child.tail)
  303. dumby = etree.Element('d')
  304. child.tail = None
  305. tailResult = self.__processPlaceholders(tail, dumby, False)
  306. if dumby.tail:
  307. child.tail = dumby.tail
  308. pos = list(currElement).index(child) + 1
  309. tailResult.reverse()
  310. for newChild in tailResult:
  311. self.parent_map[newChild[0]] = currElement
  312. currElement.insert(pos, newChild[0])
  313. if len(child):
  314. self.parent_map[child] = currElement
  315. stack.append((child, self.ancestors[:]))
  316. for element, lst in insertQueue:
  317. for i, obj in enumerate(lst):
  318. newChild = obj[0]
  319. element.insert(i, newChild)
  320. return tree
  321. class PrettifyTreeprocessor(Treeprocessor):
  322. """ Add linebreaks to the html document. """
  323. def _prettifyETree(self, elem):
  324. """ Recursively add linebreaks to ElementTree children. """
  325. i = "\n"
  326. if self.md.is_block_level(elem.tag) and elem.tag not in ['code', 'pre']:
  327. if (not elem.text or not elem.text.strip()) \
  328. and len(elem) and self.md.is_block_level(elem[0].tag):
  329. elem.text = i
  330. for e in elem:
  331. if self.md.is_block_level(e.tag):
  332. self._prettifyETree(e)
  333. if not elem.tail or not elem.tail.strip():
  334. elem.tail = i
  335. if not elem.tail or not elem.tail.strip():
  336. elem.tail = i
  337. def run(self, root):
  338. """ Add linebreaks to ElementTree root object. """
  339. self._prettifyETree(root)
  340. # Do <br />'s separately as they are often in the middle of
  341. # inline content and missed by _prettifyETree.
  342. brs = root.iter('br')
  343. for br in brs:
  344. if not br.tail or not br.tail.strip():
  345. br.tail = '\n'
  346. else:
  347. br.tail = '\n%s' % br.tail
  348. # Clean up extra empty lines at end of code blocks.
  349. pres = root.iter('pre')
  350. for pre in pres:
  351. if len(pre) and pre[0].tag == 'code':
  352. pre[0].text = util.AtomicString(pre[0].text.rstrip() + '\n')