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.
 
 
 
 

684 lines
30 KiB

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