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.
 
 
 
 

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