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.
 
 
 
 

472 lines
20 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2013 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from __future__ import unicode_literals
  23. import re
  24. from .compat import maxsize, str
  25. from .nodes import Heading, Node, Tag, Template, Text, Wikilink
  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, :py:meth:`index` can get the index of a node in the list, and
  35. :py:meth:`insert` can add a new node at that index. The :py: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. def __init__(self, nodes):
  40. super(Wikicode, self).__init__()
  41. self._nodes = nodes
  42. def __unicode__(self):
  43. return "".join([str(node) for node in self.nodes])
  44. def _get_children(self, node):
  45. """Iterate over all descendants of a given *node*, including itself.
  46. This is implemented by the ``__iternodes__()`` generator of ``Node``
  47. classes, which by default yields itself and nothing more.
  48. """
  49. for context, child in node.__iternodes__(self._get_all_nodes):
  50. yield child
  51. def _get_context(self, node, obj):
  52. """Return a ``Wikicode`` that contains *obj* in its descendants.
  53. The closest (shortest distance from *node*) suitable ``Wikicode`` will
  54. be returned, or ``None`` if the *obj* is the *node* itself.
  55. Raises ``ValueError`` if *obj* is not within *node*.
  56. """
  57. for context, child in node.__iternodes__(self._get_all_nodes):
  58. if child is obj:
  59. return context
  60. raise ValueError(obj)
  61. def _get_all_nodes(self, code):
  62. """Iterate over all of our descendant nodes.
  63. This is implemented by calling :py:meth:`_get_children` on every node
  64. in our node list (:py:attr:`self.nodes <nodes>`).
  65. """
  66. for node in code.nodes:
  67. for child in self._get_children(node):
  68. yield child
  69. def _is_equivalent(self, obj, node):
  70. """Return ``True`` if *obj* and *node* are equivalent, else ``False``.
  71. If *obj* is a ``Node``, the function will test whether they are the
  72. same object, otherwise it will compare them with ``==``.
  73. """
  74. return (node is obj) if isinstance(obj, Node) else (node == obj)
  75. def _contains(self, nodes, obj):
  76. """Return ``True`` if *obj* is inside of *nodes*, else ``False``.
  77. If *obj* is a ``Node``, we will only return ``True`` if *obj* is
  78. actually in the list (and not just a node that equals it). Otherwise,
  79. the test is simply ``obj in nodes``.
  80. """
  81. if isinstance(obj, Node):
  82. for node in nodes:
  83. if node is obj:
  84. return True
  85. return False
  86. return obj in nodes
  87. def _do_search(self, obj, recursive, callback, context, *args, **kwargs):
  88. """Look within *context* for *obj*, executing *callback* if found.
  89. If *recursive* is ``True``, we'll look within context and its
  90. descendants, otherwise we'll just execute callback. We raise
  91. :py:exc:`ValueError` if *obj* isn't in our node list or context. If
  92. found, *callback* is passed the context, the index of the node within
  93. the context, and whatever were passed as ``*args`` and ``**kwargs``.
  94. """
  95. if recursive:
  96. for i, node in enumerate(context.nodes):
  97. if self._is_equivalent(obj, node):
  98. return callback(context, i, *args, **kwargs)
  99. if self._contains(self._get_children(node), obj):
  100. context = self._get_context(node, obj)
  101. return self._do_search(obj, recursive, callback, context,
  102. *args, **kwargs)
  103. raise ValueError(obj)
  104. callback(context, self.index(obj, recursive=False), *args, **kwargs)
  105. def _get_tree(self, code, lines, marker, indent):
  106. """Build a tree to illustrate the way the Wikicode object was parsed.
  107. The method that builds the actual tree is ``__showtree__`` of ``Node``
  108. objects. *code* is the ``Wikicode`` object to build a tree for. *lines*
  109. is the list to append the tree to, which is returned at the end of the
  110. method. *marker* is some object to be used to indicate that the builder
  111. should continue on from the last line instead of starting a new one; it
  112. should be any object that can be tested for with ``is``. *indent* is
  113. the starting indentation.
  114. """
  115. def write(*args):
  116. """Write a new line following the proper indentation rules."""
  117. if lines and lines[-1] is marker: # Continue from the last line
  118. lines.pop() # Remove the marker
  119. last = lines.pop()
  120. lines.append(last + " ".join(args))
  121. else:
  122. lines.append(" " * 6 * indent + " ".join(args))
  123. get = lambda code: self._get_tree(code, lines, marker, indent + 1)
  124. mark = lambda: lines.append(marker)
  125. for node in code.nodes:
  126. node.__showtree__(write, get, mark)
  127. return lines
  128. @property
  129. def nodes(self):
  130. """A list of :py:class:`~.Node` objects.
  131. This is the internal data actually stored within a
  132. :py:class:`~.Wikicode` object.
  133. """
  134. return self._nodes
  135. @nodes.setter
  136. def nodes(self, value):
  137. if not isinstance(value, list):
  138. value = parse_anything(value).nodes
  139. self._nodes = value
  140. def get(self, index):
  141. """Return the *index*\ th node within the list of nodes."""
  142. return self.nodes[index]
  143. def set(self, index, value):
  144. """Set the ``Node`` at *index* to *value*.
  145. Raises :py:exc:`IndexError` if *index* is out of range, or
  146. :py:exc:`ValueError` if *value* cannot be coerced into one
  147. :py:class:`~.Node`. To insert multiple nodes at an index, use
  148. :py:meth:`get` with either :py:meth:`remove` and :py:meth:`insert` or
  149. :py:meth:`replace`.
  150. """
  151. nodes = parse_anything(value).nodes
  152. if len(nodes) > 1:
  153. raise ValueError("Cannot coerce multiple nodes into one index")
  154. if index >= len(self.nodes) or -1 * index > len(self.nodes):
  155. raise IndexError("List assignment index out of range")
  156. self.nodes.pop(index)
  157. if nodes:
  158. self.nodes[index] = nodes[0]
  159. def index(self, obj, recursive=False):
  160. """Return the index of *obj* in the list of nodes.
  161. Raises :py:exc:`ValueError` if *obj* is not found. If *recursive* is
  162. ``True``, we will look in all nodes of ours and their descendants, and
  163. return the index of our direct descendant node within *our* list of
  164. nodes. Otherwise, the lookup is done only on direct descendants.
  165. """
  166. if recursive:
  167. for i, node in enumerate(self.nodes):
  168. if self._contains(self._get_children(node), obj):
  169. return i
  170. raise ValueError(obj)
  171. for i, node in enumerate(self.nodes):
  172. if self._is_equivalent(obj, node):
  173. return i
  174. raise ValueError(obj)
  175. def insert(self, index, value):
  176. """Insert *value* at *index* in the list of nodes.
  177. *value* can be anything parasable by :py:func:`.parse_anything`, which
  178. includes strings or other :py:class:`~.Wikicode` or :py:class:`~.Node`
  179. objects.
  180. """
  181. nodes = parse_anything(value).nodes
  182. for node in reversed(nodes):
  183. self.nodes.insert(index, node)
  184. def insert_before(self, obj, value, recursive=True):
  185. """Insert *value* immediately before *obj* in the list of nodes.
  186. *obj* can be either a string or a :py:class:`~.Node`. *value* can be
  187. anything parasable by :py:func:`.parse_anything`. If *recursive* is
  188. ``True``, we will try to find *obj* within our child nodes even if it
  189. is not a direct descendant of this :py:class:`~.Wikicode` object. If
  190. *obj* is not in the node list, :py:exc:`ValueError` is raised.
  191. """
  192. callback = lambda self, i, value: self.insert(i, value)
  193. self._do_search(obj, recursive, callback, self, value)
  194. def insert_after(self, obj, value, recursive=True):
  195. """Insert *value* immediately after *obj* in the list of nodes.
  196. *obj* can be either a string or a :py:class:`~.Node`. *value* can be
  197. anything parasable by :py:func:`.parse_anything`. If *recursive* is
  198. ``True``, we will try to find *obj* within our child nodes even if it
  199. is not a direct descendant of this :py:class:`~.Wikicode` object. If
  200. *obj* is not in the node list, :py:exc:`ValueError` is raised.
  201. """
  202. callback = lambda self, i, value: self.insert(i + 1, value)
  203. self._do_search(obj, recursive, callback, self, value)
  204. def replace(self, obj, value, recursive=True):
  205. """Replace *obj* with *value* in the list of nodes.
  206. *obj* can be either a string or a :py:class:`~.Node`. *value* can be
  207. anything parasable by :py:func:`.parse_anything`. If *recursive* is
  208. ``True``, we will try to find *obj* within our child nodes even if it
  209. is not a direct descendant of this :py:class:`~.Wikicode` object. If
  210. *obj* is not in the node list, :py:exc:`ValueError` is raised.
  211. """
  212. def callback(self, i, value):
  213. self.nodes.pop(i)
  214. self.insert(i, value)
  215. self._do_search(obj, recursive, callback, self, value)
  216. def append(self, value):
  217. """Insert *value* at the end of the list of nodes.
  218. *value* can be anything parasable by :py:func:`.parse_anything`.
  219. """
  220. nodes = parse_anything(value).nodes
  221. for node in nodes:
  222. self.nodes.append(node)
  223. def remove(self, obj, recursive=True):
  224. """Remove *obj* from the list of nodes.
  225. *obj* can be either a string or a :py:class:`~.Node`. If *recursive* is
  226. ``True``, we will try to find *obj* within our child nodes even if it
  227. is not a direct descendant of this :py:class:`~.Wikicode` object. If
  228. *obj* is not in the node list, :py:exc:`ValueError` is raised.
  229. """
  230. callback = lambda self, i: self.nodes.pop(i)
  231. self._do_search(obj, recursive, callback, self)
  232. def ifilter(self, recursive=False, matches=None, flags=FLAGS,
  233. forcetype=None):
  234. """Iterate over nodes in our list matching certain conditions.
  235. If *recursive* is ``True``, we will iterate over our children and all
  236. descendants of our children, otherwise just our immediate children. If
  237. *matches* is given, we will only yield the nodes that match the given
  238. regular expression (with :py:func:`re.search`). The default flags used
  239. are :py:const:`re.IGNORECASE`, :py:const:`re.DOTALL`, and
  240. :py:const:`re.UNICODE`, but custom flags can be specified by passing
  241. *flags*. If *forcetype* is given, only nodes that are instances of this
  242. type are yielded.
  243. """
  244. if recursive:
  245. nodes = self._get_all_nodes(self)
  246. else:
  247. nodes = self.nodes
  248. for node in nodes:
  249. if not forcetype or isinstance(node, forcetype):
  250. if not matches or re.search(matches, str(node), flags):
  251. yield node
  252. def ifilter_links(self, recursive=False, matches=None, flags=FLAGS):
  253. """Iterate over wikilink nodes.
  254. This is equivalent to :py:meth:`ifilter` with *forcetype* set to
  255. :py:class:`~.Wikilink`.
  256. """
  257. return self.ifilter(recursive, matches, flags, forcetype=Wikilink)
  258. def ifilter_templates(self, recursive=False, matches=None, flags=FLAGS):
  259. """Iterate over template nodes.
  260. This is equivalent to :py:meth:`ifilter` with *forcetype* set to
  261. :py:class:`~.Template`.
  262. """
  263. return self.filter(recursive, matches, flags, forcetype=Template)
  264. def ifilter_text(self, recursive=False, matches=None, flags=FLAGS):
  265. """Iterate over text nodes.
  266. This is equivalent to :py:meth:`ifilter` with *forcetype* set to
  267. :py:class:`~.nodes.Text`.
  268. """
  269. return self.filter(recursive, matches, flags, forcetype=Text)
  270. def ifilter_tags(self, recursive=False, matches=None, flags=FLAGS):
  271. """Iterate over tag nodes.
  272. This is equivalent to :py:meth:`ifilter` with *forcetype* set to
  273. :py:class:`~.Tag`.
  274. """
  275. return self.ifilter(recursive, matches, flags, forcetype=Tag)
  276. def filter(self, recursive=False, matches=None, flags=FLAGS,
  277. forcetype=None):
  278. """Return a list of nodes within our list matching certain conditions.
  279. This is equivalent to calling :py:func:`list` on :py:meth:`ifilter`.
  280. """
  281. return list(self.ifilter(recursive, matches, flags, forcetype))
  282. def filter_links(self, recursive=False, matches=None, flags=FLAGS):
  283. """Return a list of wikilink nodes.
  284. This is equivalent to calling :py:func:`list` on
  285. :py:meth:`ifilter_links`.
  286. """
  287. return list(self.ifilter_links(recursive, matches, flags))
  288. def filter_templates(self, recursive=False, matches=None, flags=FLAGS):
  289. """Return a list of template nodes.
  290. This is equivalent to calling :py:func:`list` on
  291. :py:meth:`ifilter_templates`.
  292. """
  293. return list(self.ifilter_templates(recursive, matches, flags))
  294. def filter_text(self, recursive=False, matches=None, flags=FLAGS):
  295. """Return a list of text nodes.
  296. This is equivalent to calling :py:func:`list` on
  297. :py:meth:`ifilter_text`.
  298. """
  299. return list(self.ifilter_text(recursive, matches, flags))
  300. def filter_tags(self, recursive=False, matches=None, flags=FLAGS):
  301. """Return a list of tag nodes.
  302. This is equivalent to calling :py:func:`list` on
  303. :py:meth:`ifilter_tags`.
  304. """
  305. return list(self.ifilter_tags(recursive, matches, flags))
  306. def get_sections(self, flat=True, matches=None, levels=None, flags=FLAGS,
  307. include_headings=True):
  308. """Return a list of sections within the page.
  309. Sections are returned as :py:class:`~.Wikicode` objects with a shared
  310. node list (implemented using :py:class:`~.SmartList`) so that changes
  311. to sections are reflected in the parent Wikicode object.
  312. With *flat* as ``True``, each returned section contains all of its
  313. subsections within the :py:class:`~.Wikicode`; otherwise, the returned
  314. sections contain only the section up to the next heading, regardless of
  315. its size. If *matches* is given, it should be a regex to be matched
  316. against the titles of section headings; only sections whose headings
  317. match the regex will be included. If *levels* is given, it should be a
  318. iterable of integers; only sections whose heading levels are within it
  319. will be returned. If *include_headings* is ``True``, the section's
  320. beginning :py:class:`~.Heading` object will be included in returned
  321. :py:class:`~.Wikicode` objects; otherwise, this is skipped.
  322. """
  323. if matches:
  324. matches = r"^(=+?)\s*" + matches + r"\s*\1$"
  325. headings = self.filter(recursive=True, matches=matches, flags=flags,
  326. forcetype=Heading)
  327. if levels:
  328. headings = [head for head in headings if head.level in levels]
  329. sections = []
  330. buffers = [(maxsize, 0)]
  331. i = 0
  332. while i < len(self.nodes):
  333. if self.nodes[i] in headings:
  334. this = self.nodes[i].level
  335. for (level, start) in buffers:
  336. if not flat or this <= level:
  337. buffers.remove((level, start))
  338. sections.append(Wikicode(self.nodes[start:i]))
  339. buffers.append((this, i))
  340. if not include_headings:
  341. i += 1
  342. i += 1
  343. for (level, start) in buffers:
  344. if start != i:
  345. sections.append(Wikicode(self.nodes[start:i]))
  346. return sections
  347. def strip_code(self, normalize=True, collapse=True):
  348. """Return a rendered string without unprintable code such as templates.
  349. The way a node is stripped is handled by the
  350. :py:meth:`~.Node.__showtree__` method of :py:class:`~.Node` objects,
  351. which generally return a subset of their nodes or ``None``. For
  352. example, templates and tags are removed completely, links are stripped
  353. to just their display part, headings are stripped to just their title.
  354. If *normalize* is ``True``, various things may be done to strip code
  355. further, such as converting HTML entities like ``&Sigma;``, ``&#931;``,
  356. and ``&#x3a3;`` to ``Σ``. If *collapse* is ``True``, we will try to
  357. remove excess whitespace as well (three or more newlines are converted
  358. to two, for example).
  359. """
  360. nodes = []
  361. for node in self.nodes:
  362. stripped = node.__strip__(normalize, collapse)
  363. if stripped:
  364. nodes.append(str(stripped))
  365. if collapse:
  366. stripped = "".join(nodes).strip("\n")
  367. while "\n\n\n" in stripped:
  368. stripped = stripped.replace("\n\n\n", "\n\n")
  369. return stripped
  370. else:
  371. return "".join(nodes)
  372. def get_tree(self):
  373. """Return a hierarchical tree representation of the object.
  374. The representation is a string makes the most sense printed. It is
  375. built by calling :py:meth:`_get_tree` on the
  376. :py:class:`~.Wikicode` object and its children recursively. The end
  377. result may look something like the following::
  378. >>> text = "Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}"
  379. >>> print mwparserfromhell.parse(text).get_tree()
  380. Lorem ipsum
  381. {{
  382. foo
  383. | 1
  384. = bar
  385. | 2
  386. = {{
  387. baz
  388. }}
  389. | spam
  390. = eggs
  391. }}
  392. """
  393. marker = object() # Random object we can find with certainty in a list
  394. return "\n".join(self._get_tree(self, [], marker, 0))