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.
 
 
 
 

685 lines
30 KiB

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