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.
 
 
 
 

715 lines
30 KiB

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