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.
 
 
 
 

535 lines
24 KiB

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