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.
 
 
 
 

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