A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
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.
 
 
 
 

598 lines
27 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2014 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from __future__ import unicode_literals
  23. from itertools import chain
  24. import re
  25. from .compat import py3k, range, str
  26. from .nodes import (Argument, Comment, ExternalLink, Heading, HTMLEntity,
  27. Node, Tag, Template, Text, Wikilink)
  28. from .string_mixin import StringMixIn
  29. from .utils import parse_anything
  30. __all__ = ["Wikicode"]
  31. FLAGS = re.IGNORECASE | re.DOTALL | re.UNICODE
  32. class Wikicode(StringMixIn):
  33. """A ``Wikicode`` is a container for nodes that operates like a string.
  34. Additionally, it contains methods that can be used to extract data from or
  35. modify the nodes, implemented in an interface similar to a list. For
  36. example, :py:meth:`index` can get the index of a node in the list, and
  37. :py:meth:`insert` can add a new node at that index. The :py:meth:`filter()
  38. <ifilter>` series of functions is very useful for extracting and iterating
  39. over, for example, all of the templates in the object.
  40. """
  41. RECURSE_OTHERS = 2
  42. def __init__(self, nodes):
  43. super(Wikicode, self).__init__()
  44. self._nodes = nodes
  45. def __unicode__(self):
  46. return "".join([str(node) for node in self.nodes])
  47. @staticmethod
  48. def _get_children(node, contexts=False, restrict=None, parent=None):
  49. """Iterate over all child :py:class:`.Node`\ s of a given *node*."""
  50. yield (parent, node) if contexts else node
  51. if restrict and isinstance(node, restrict):
  52. return
  53. for code in node.__children__():
  54. for child in code.nodes:
  55. sub = Wikicode._get_children(child, contexts, restrict, code)
  56. for result in sub:
  57. yield result
  58. @staticmethod
  59. def _slice_replace(code, index, old, new):
  60. """Replace the string *old* with *new* across *index* in *code*."""
  61. nodes = [str(node) for node in code.get(index)]
  62. substring = "".join(nodes).replace(old, new)
  63. code.nodes[index] = parse_anything(substring).nodes
  64. @staticmethod
  65. def _build_matcher(matches, flags):
  66. """Helper for :py:meth:`_indexed_ifilter` and others.
  67. If *matches* is a function, return it. If it's a regex, return a
  68. wrapper around it that can be called with a node to do a search. If
  69. it's ``None``, return a function that always returns ``True``.
  70. """
  71. if matches:
  72. if callable(matches):
  73. return matches
  74. return lambda obj: re.search(matches, str(obj), flags)
  75. return lambda obj: True
  76. def _indexed_ifilter(self, recursive=True, matches=None, flags=FLAGS,
  77. forcetype=None):
  78. """Iterate over nodes and their corresponding indices in the node list.
  79. The arguments are interpreted as for :py:meth:`ifilter`. For each tuple
  80. ``(i, node)`` yielded by this method, ``self.index(node) == i``. Note
  81. that if *recursive* is ``True``, ``self.nodes[i]`` might not be the
  82. node itself, but will still contain it.
  83. """
  84. match = self._build_matcher(matches, flags)
  85. if recursive:
  86. restrict = forcetype if recursive == self.RECURSE_OTHERS else None
  87. def getter(i, node):
  88. for ch in self._get_children(node, restrict=restrict):
  89. yield (i, ch)
  90. inodes = chain(*(getter(i, n) for i, n in enumerate(self.nodes)))
  91. else:
  92. inodes = enumerate(self.nodes)
  93. for i, node in inodes:
  94. if (not forcetype or isinstance(node, forcetype)) and match(node):
  95. yield (i, node)
  96. def _do_strong_search(self, obj, recursive=True):
  97. """Search for the specific element *obj* within the node list.
  98. *obj* can be either a :py:class:`.Node` or a :py:class:`.Wikicode`
  99. object. If found, we return a tuple (*context*, *index*) where
  100. *context* is the :py:class:`.Wikicode` that contains *obj* and *index*
  101. is its index there, as a :py:class:`slice`. Note that if *recursive* is
  102. ``False``, *context* will always be ``self`` (since we only look for
  103. *obj* among immediate descendants), but if *recursive* is ``True``,
  104. then it could be any :py:class:`.Wikicode` contained by a node within
  105. ``self``. If *obj* is not found, :py:exc:`ValueError` is raised.
  106. """
  107. mkslice = lambda i: slice(i, i + 1)
  108. if isinstance(obj, Node):
  109. if not recursive:
  110. return self, mkslice(self.index(obj))
  111. for i, node in enumerate(self.nodes):
  112. for context, child in self._get_children(node, contexts=True):
  113. if obj is child:
  114. if not context:
  115. context = self
  116. return context, mkslice(context.index(child))
  117. else:
  118. context, ind = self._do_strong_search(obj.get(0), recursive)
  119. for i in range(1, len(obj.nodes)):
  120. if obj.get(i) is not context.get(ind.start + i):
  121. break
  122. else:
  123. return context, slice(ind.start, ind.start + len(obj.nodes))
  124. raise ValueError(obj)
  125. def _do_weak_search(self, obj, recursive):
  126. """Search for an element that looks like *obj* within the node list.
  127. This follows the same rules as :py:meth:`_do_strong_search` with some
  128. differences. *obj* is treated as a string that might represent any
  129. :py:class:`.Node`, :py:class:`.Wikicode`, or combination of the two
  130. present in the node list. Thus, matching is weak (using string
  131. comparisons) rather than strong (using ``is``). Because multiple nodes
  132. can match *obj*, the result is a list of tuples instead of just one
  133. (however, :py:exc:`ValueError` is still raised if nothing is found).
  134. Individual matches will never overlap.
  135. The tuples contain a new first element, *exact*, which is ``True`` if
  136. we were able to match *obj* exactly to one or more adjacent nodes, or
  137. ``False`` if we found *obj* inside a node or incompletely spanning
  138. multiple nodes.
  139. """
  140. obj = parse_anything(obj)
  141. if not obj or obj not in self:
  142. raise ValueError(obj)
  143. results = []
  144. contexts = [self]
  145. while contexts:
  146. context = contexts.pop()
  147. i = len(context.nodes) - 1
  148. while i >= 0:
  149. node = context.get(i)
  150. if obj.get(-1) == node:
  151. for j in range(-len(obj.nodes), -1):
  152. if obj.get(j) != context.get(i + j + 1):
  153. break
  154. else:
  155. i -= len(obj.nodes) - 1
  156. index = slice(i, i + len(obj.nodes))
  157. results.append((True, context, index))
  158. elif recursive and obj in node:
  159. contexts.extend(node.__children__())
  160. i -= 1
  161. if not results:
  162. if not recursive:
  163. raise ValueError(obj)
  164. results.append((False, self, slice(0, len(self.nodes))))
  165. return results
  166. def _get_tree(self, code, lines, marker, indent):
  167. """Build a tree to illustrate the way the Wikicode object was parsed.
  168. The method that builds the actual tree is ``__showtree__`` of ``Node``
  169. objects. *code* is the ``Wikicode`` object to build a tree for. *lines*
  170. is the list to append the tree to, which is returned at the end of the
  171. method. *marker* is some object to be used to indicate that the builder
  172. should continue on from the last line instead of starting a new one; it
  173. should be any object that can be tested for with ``is``. *indent* is
  174. the starting indentation.
  175. """
  176. def write(*args):
  177. """Write a new line following the proper indentation rules."""
  178. if lines and lines[-1] is marker: # Continue from the last line
  179. lines.pop() # Remove the marker
  180. last = lines.pop()
  181. lines.append(last + " ".join(args))
  182. else:
  183. lines.append(" " * 6 * indent + " ".join(args))
  184. get = lambda code: self._get_tree(code, lines, marker, indent + 1)
  185. mark = lambda: lines.append(marker)
  186. for node in code.nodes:
  187. node.__showtree__(write, get, mark)
  188. return lines
  189. @classmethod
  190. def _build_filter_methods(cls, **meths):
  191. """Given Node types, build the corresponding i?filter shortcuts.
  192. The should be given as keys storing the method's base name paired
  193. with values storing the corresponding :py:class:`~.Node` type. For
  194. example, the dict may contain the pair ``("templates", Template)``,
  195. which will produce the methods :py:meth:`ifilter_templates` and
  196. :py:meth:`filter_templates`, which are shortcuts for
  197. :py:meth:`ifilter(forcetype=Template) <ifilter>` and
  198. :py:meth:`filter(forcetype=Template) <filter>`, respectively. These
  199. shortcuts are added to the class itself, with an appropriate docstring.
  200. """
  201. doc = """Iterate over {0}.
  202. This is equivalent to :py:meth:`{1}` with *forcetype* set to
  203. :py:class:`~{2.__module__}.{2.__name__}`.
  204. """
  205. make_ifilter = lambda ftype: (lambda self, *a, **kw:
  206. self.ifilter(forcetype=ftype, *a, **kw))
  207. make_filter = lambda ftype: (lambda self, *a, **kw:
  208. self.filter(forcetype=ftype, *a, **kw))
  209. for name, ftype in (meths.items() if py3k else meths.iteritems()):
  210. ifilter = make_ifilter(ftype)
  211. filter = make_filter(ftype)
  212. ifilter.__doc__ = doc.format(name, "ifilter", ftype)
  213. filter.__doc__ = doc.format(name, "filter", ftype)
  214. setattr(cls, "ifilter_" + name, ifilter)
  215. setattr(cls, "filter_" + name, filter)
  216. @property
  217. def nodes(self):
  218. """A list of :py:class:`~.Node` objects.
  219. This is the internal data actually stored within a
  220. :py:class:`~.Wikicode` object.
  221. """
  222. return self._nodes
  223. @nodes.setter
  224. def nodes(self, value):
  225. if not isinstance(value, list):
  226. value = parse_anything(value).nodes
  227. self._nodes = value
  228. def get(self, index):
  229. """Return the *index*\ th node within the list of nodes."""
  230. return self.nodes[index]
  231. def set(self, index, value):
  232. """Set the ``Node`` at *index* to *value*.
  233. Raises :py:exc:`IndexError` if *index* is out of range, or
  234. :py:exc:`ValueError` if *value* cannot be coerced into one
  235. :py:class:`~.Node`. To insert multiple nodes at an index, use
  236. :py:meth:`get` with either :py:meth:`remove` and :py:meth:`insert` or
  237. :py:meth:`replace`.
  238. """
  239. nodes = parse_anything(value).nodes
  240. if len(nodes) > 1:
  241. raise ValueError("Cannot coerce multiple nodes into one index")
  242. if index >= len(self.nodes) or -1 * index > len(self.nodes):
  243. raise IndexError("List assignment index out of range")
  244. if nodes:
  245. self.nodes[index] = nodes[0]
  246. else:
  247. self.nodes.pop(index)
  248. def index(self, obj, recursive=False):
  249. """Return the index of *obj* in the list of nodes.
  250. Raises :py:exc:`ValueError` if *obj* is not found. If *recursive* is
  251. ``True``, we will look in all nodes of ours and their descendants, and
  252. return the index of our direct descendant node within *our* list of
  253. nodes. Otherwise, the lookup is done only on direct descendants.
  254. """
  255. strict = isinstance(obj, Node)
  256. equivalent = (lambda o, n: o is n) if strict else (lambda o, n: o == n)
  257. for i, node in enumerate(self.nodes):
  258. if recursive:
  259. for child in self._get_children(node):
  260. if equivalent(obj, child):
  261. return i
  262. elif equivalent(obj, node):
  263. return i
  264. raise ValueError(obj)
  265. def insert(self, index, value):
  266. """Insert *value* at *index* in the list of nodes.
  267. *value* can be anything parsable by :py:func:`.parse_anything`, which
  268. includes strings or other :py:class:`~.Wikicode` or :py:class:`~.Node`
  269. objects.
  270. """
  271. nodes = parse_anything(value).nodes
  272. for node in reversed(nodes):
  273. self.nodes.insert(index, node)
  274. def insert_before(self, obj, value, recursive=True):
  275. """Insert *value* immediately before *obj*.
  276. *obj* can be either a string, a :py:class:`~.Node`, or another
  277. :py:class:`~.Wikicode` object (as created by :py:meth:`get_sections`,
  278. for example). If *obj* is a string, we will operate on all instances
  279. of that string within the code, otherwise only on the specific instance
  280. given. *value* can be anything parsable by :py:func:`.parse_anything`.
  281. If *recursive* is ``True``, we will try to find *obj* within our child
  282. nodes even if it is not a direct descendant of this
  283. :py:class:`~.Wikicode` object. If *obj* is not found,
  284. :py:exc:`ValueError` is raised.
  285. """
  286. if isinstance(obj, (Node, Wikicode)):
  287. context, index = self._do_strong_search(obj, recursive)
  288. context.insert(index.start, value)
  289. else:
  290. for exact, context, index in self._do_weak_search(obj, recursive):
  291. if exact:
  292. context.insert(index.start, value)
  293. else:
  294. obj = str(obj)
  295. self._slice_replace(context, index, obj, str(value) + obj)
  296. def insert_after(self, obj, value, recursive=True):
  297. """Insert *value* immediately after *obj*.
  298. *obj* can be either a string, a :py:class:`~.Node`, or another
  299. :py:class:`~.Wikicode` object (as created by :py:meth:`get_sections`,
  300. for example). If *obj* is a string, we will operate on all instances
  301. of that string within the code, otherwise only on the specific instance
  302. given. *value* can be anything parsable by :py:func:`.parse_anything`.
  303. If *recursive* is ``True``, we will try to find *obj* within our child
  304. nodes even if it is not a direct descendant of this
  305. :py:class:`~.Wikicode` object. If *obj* is not found,
  306. :py:exc:`ValueError` is raised.
  307. """
  308. if isinstance(obj, (Node, Wikicode)):
  309. context, index = self._do_strong_search(obj, recursive)
  310. context.insert(index.stop, value)
  311. else:
  312. for exact, context, index in self._do_weak_search(obj, recursive):
  313. if exact:
  314. context.insert(index.stop, value)
  315. else:
  316. obj = str(obj)
  317. self._slice_replace(context, index, obj, obj + str(value))
  318. def replace(self, obj, value, recursive=True):
  319. """Replace *obj* with *value*.
  320. *obj* can be either a string, a :py:class:`~.Node`, or another
  321. :py:class:`~.Wikicode` object (as created by :py:meth:`get_sections`,
  322. for example). If *obj* is a string, we will operate on all instances
  323. of that string within the code, otherwise only on the specific instance
  324. given. *value* can be anything parsable by :py:func:`.parse_anything`.
  325. If *recursive* is ``True``, we will try to find *obj* within our child
  326. nodes even if it is not a direct descendant of this
  327. :py:class:`~.Wikicode` object. If *obj* is not found,
  328. :py:exc:`ValueError` is raised.
  329. """
  330. if isinstance(obj, (Node, Wikicode)):
  331. context, index = self._do_strong_search(obj, recursive)
  332. for i in range(index.start, index.stop):
  333. context.nodes.pop(index.start)
  334. context.insert(index.start, value)
  335. else:
  336. for exact, context, index in self._do_weak_search(obj, recursive):
  337. if exact:
  338. for i in range(index.start, index.stop):
  339. context.nodes.pop(index.start)
  340. context.insert(index.start, value)
  341. else:
  342. self._slice_replace(context, index, str(obj), str(value))
  343. def append(self, value):
  344. """Insert *value* at the end of the list of nodes.
  345. *value* can be anything parsable by :py:func:`.parse_anything`.
  346. """
  347. nodes = parse_anything(value).nodes
  348. for node in nodes:
  349. self.nodes.append(node)
  350. def remove(self, obj, recursive=True):
  351. """Remove *obj* from the list of nodes.
  352. *obj* can be either a string, a :py:class:`~.Node`, or another
  353. :py:class:`~.Wikicode` object (as created by :py:meth:`get_sections`,
  354. for example). If *obj* is a string, we will operate on all instances
  355. of that string within the code, otherwise only on the specific instance
  356. given. If *recursive* is ``True``, we will try to find *obj* within our
  357. child nodes even if it is not a direct descendant of this
  358. :py:class:`~.Wikicode` object. If *obj* is not found,
  359. :py:exc:`ValueError` is raised.
  360. """
  361. if isinstance(obj, (Node, Wikicode)):
  362. context, index = self._do_strong_search(obj, recursive)
  363. for i in range(index.start, index.stop):
  364. context.nodes.pop(index.start)
  365. else:
  366. for exact, context, index in self._do_weak_search(obj, recursive):
  367. if exact:
  368. for i in range(index.start, index.stop):
  369. context.nodes.pop(index.start)
  370. else:
  371. self._slice_replace(context, index, str(obj), "")
  372. def matches(self, other):
  373. """Do a loose equivalency test suitable for comparing page names.
  374. *other* can be any string-like object, including
  375. :py:class:`~.Wikicode`, or a tuple of these. This operation is
  376. symmetric; both sides are adjusted. Specifically, whitespace and markup
  377. is stripped and the first letter's case is normalized. Typical usage is
  378. ``if template.name.matches("stub"): ...``.
  379. """
  380. cmp = lambda a, b: (a[0].upper() + a[1:] == b[0].upper() + b[1:]
  381. if a and b else a == b)
  382. this = self.strip_code().strip()
  383. if isinstance(other, (tuple, list)):
  384. for obj in other:
  385. that = parse_anything(obj).strip_code().strip()
  386. if cmp(this, that):
  387. return True
  388. return False
  389. that = parse_anything(other).strip_code().strip()
  390. return cmp(this, that)
  391. def ifilter(self, recursive=True, matches=None, flags=FLAGS,
  392. forcetype=None):
  393. """Iterate over nodes in our list matching certain conditions.
  394. If *forcetype* is given, only nodes that are instances of this type (or
  395. tuple of types) are yielded. Setting *recursive* to ``True`` will
  396. iterate over all children and their descendants. ``RECURSE_OTHERS``
  397. will only iterate over children that are not the instances of
  398. *forcetype*. ``False`` will only iterate over immediate children.
  399. ``RECURSE_OTHERS`` can be used to iterate over all un-nested templates,
  400. even if they are inside of HTML tags, like so:
  401. >>> code = mwparserfromhell.parse("{{foo}}<b>{{foo|{{bar}}}}</b>")
  402. >>> code.filter_templates(code.RECURSE_OTHERS)
  403. ["{{foo}}", "{{foo|{{bar}}}}"]
  404. *matches* can be used to further restrict the nodes, either as a
  405. function (taking a single :py:class:`.Node` and returning a boolean) or
  406. a regular expression (matched against the node's string representation
  407. with :py:func:`re.search`). If *matches* is a regex, the flags passed
  408. to :py:func:`re.search` are :py:const:`re.IGNORECASE`,
  409. :py:const:`re.DOTALL`, and :py:const:`re.UNICODE`, but custom flags can
  410. be specified by passing *flags*.
  411. """
  412. gen = self._indexed_ifilter(recursive, matches, flags, forcetype)
  413. return (node for i, node in gen)
  414. def filter(self, *args, **kwargs):
  415. """Return a list of nodes within our list matching certain conditions.
  416. This is equivalent to calling :py:func:`list` on :py:meth:`ifilter`.
  417. """
  418. return list(self.ifilter(*args, **kwargs))
  419. def get_sections(self, levels=None, matches=None, flags=FLAGS, flat=False,
  420. include_lead=None, include_headings=True):
  421. """Return a list of sections within the page.
  422. Sections are returned as :py:class:`~.Wikicode` objects with a shared
  423. node list (implemented using :py:class:`~.SmartList`) so that changes
  424. to sections are reflected in the parent Wikicode object.
  425. Each section contains all of its subsections, unless *flat* is
  426. ``True``. If *levels* is given, it should be a iterable of integers;
  427. only sections whose heading levels are within it will be returned. If
  428. *matches* is given, it should be either a function or a regex; only
  429. sections whose headings match it (without the surrounding equal signs)
  430. will be included. *flags* can be used to override the default regex
  431. flags (see :py:meth:`ifilter`) if a regex *matches* is used.
  432. If *include_lead* is ``True``, the first, lead section (without a
  433. heading) will be included in the list; ``False`` will not include it;
  434. the default will include it only if no specific *levels* were given. If
  435. *include_headings* is ``True``, the section's beginning
  436. :py:class:`~.Heading` object will be included; otherwise, this is
  437. skipped.
  438. """
  439. title_matcher = self._build_matcher(matches, flags)
  440. matcher = lambda heading: (title_matcher(heading.title) and
  441. (not levels or heading.level in levels))
  442. iheadings = self._indexed_ifilter(recursive=False, forcetype=Heading)
  443. sections = [] # Tuples of (index_of_first_node, section)
  444. open_headings = [] # Tuples of (index, heading), where index and
  445. # heading.level are both monotonically increasing
  446. # Add the lead section if appropriate:
  447. if include_lead or not (include_lead is not None or matches or levels):
  448. itr = self._indexed_ifilter(recursive=False, forcetype=Heading)
  449. try:
  450. first = next(itr)[0]
  451. sections.append((0, Wikicode(self.nodes[:first])))
  452. except StopIteration: # No headings in page
  453. sections.append((0, Wikicode(self.nodes[:])))
  454. # Iterate over headings, adding sections to the list as they end:
  455. for i, heading in iheadings:
  456. if flat: # With flat, all sections close at the next heading
  457. newly_closed, open_headings = open_headings, []
  458. else: # Otherwise, figure out which sections have closed, if any
  459. closed_start_index = len(open_headings)
  460. for j, (start, last_heading) in enumerate(open_headings):
  461. if heading.level <= last_heading.level:
  462. closed_start_index = j
  463. break
  464. newly_closed = open_headings[closed_start_index:]
  465. del open_headings[closed_start_index:]
  466. for start, closed_heading in newly_closed:
  467. if matcher(closed_heading):
  468. sections.append((start, Wikicode(self.nodes[start:i])))
  469. start = i if include_headings else (i + 1)
  470. open_headings.append((start, heading))
  471. # Add any remaining open headings to the list of sections:
  472. for start, heading in open_headings:
  473. if matcher(heading):
  474. sections.append((start, Wikicode(self.nodes[start:])))
  475. # Ensure that earlier sections are earlier in the returned list:
  476. return [section for i, section in sorted(sections)]
  477. def strip_code(self, normalize=True, collapse=True):
  478. """Return a rendered string without unprintable code such as templates.
  479. The way a node is stripped is handled by the
  480. :py:meth:`~.Node.__strip__` method of :py:class:`~.Node` objects, which
  481. generally return a subset of their nodes or ``None``. For example,
  482. templates and tags are removed completely, links are stripped to just
  483. their display part, headings are stripped to just their title. If
  484. *normalize* is ``True``, various things may be done to strip code
  485. further, such as converting HTML entities like ``&Sigma;``, ``&#931;``,
  486. and ``&#x3a3;`` to ``Σ``. If *collapse* is ``True``, we will try to
  487. remove excess whitespace as well (three or more newlines are converted
  488. to two, for example).
  489. """
  490. nodes = []
  491. for node in self.nodes:
  492. stripped = node.__strip__(normalize, collapse)
  493. if stripped:
  494. nodes.append(str(stripped))
  495. if collapse:
  496. stripped = "".join(nodes).strip("\n")
  497. while "\n\n\n" in stripped:
  498. stripped = stripped.replace("\n\n\n", "\n\n")
  499. return stripped
  500. else:
  501. return "".join(nodes)
  502. def get_tree(self):
  503. """Return a hierarchical tree representation of the object.
  504. The representation is a string makes the most sense printed. It is
  505. built by calling :py:meth:`_get_tree` on the
  506. :py:class:`~.Wikicode` object and its children recursively. The end
  507. result may look something like the following::
  508. >>> text = "Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}"
  509. >>> print mwparserfromhell.parse(text).get_tree()
  510. Lorem ipsum
  511. {{
  512. foo
  513. | 1
  514. = bar
  515. | 2
  516. = {{
  517. baz
  518. }}
  519. | spam
  520. = eggs
  521. }}
  522. """
  523. marker = object() # Random object we can find with certainty in a list
  524. return "\n".join(self._get_tree(self, [], marker, 0))
  525. Wikicode._build_filter_methods(
  526. arguments=Argument, comments=Comment, external_links=ExternalLink,
  527. headings=Heading, html_entities=HTMLEntity, tags=Tag, templates=Template,
  528. text=Text, wikilinks=Wikilink)