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.
 
 
 
 

268 lines
9.8 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012 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
  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 functions like a string.
  32. """
  33. def __init__(self, nodes):
  34. super(Wikicode, self).__init__()
  35. self._nodes = nodes
  36. def __unicode__(self):
  37. return "".join([str(node) for node in self.nodes])
  38. def _get_children(self, node):
  39. """Iterate over all descendants of a given node, including itself.
  40. This is implemented by the __iternodes__() generator of Node classes,
  41. which by default yields itself and nothing more.
  42. """
  43. for context, child in node.__iternodes__(self._get_all_nodes):
  44. yield child
  45. def _get_context(self, node, obj):
  46. """Return a ``Wikicode`` that contains ``obj`` in its descendants.
  47. The closest (shortest distance from ``node``) suitable ``Wikicode``
  48. will be returned, or ``None`` if the ``obj`` is the ``node`` itself.
  49. Raises ``ValueError`` if ``obj`` is not within ``node``.
  50. """
  51. for context, child in node.__iternodes__(self._get_all_nodes):
  52. if child is obj:
  53. return context
  54. raise ValueError(obj)
  55. def _get_all_nodes(self, code):
  56. """Iterate over all of our descendant nodes.
  57. This is implemented by calling :py:meth:`_get_children` on every node
  58. in our node list (:py:attr:`self.nodes <nodes>`).
  59. """
  60. for node in code.nodes:
  61. for child in self._get_children(node):
  62. yield child
  63. def _is_equivalent(self, obj, node):
  64. """Return ``True`` if obj and node are equivalent, otherwise ``False``.
  65. """
  66. if isinstance(obj, Node):
  67. if node is obj:
  68. return True
  69. else:
  70. if node == obj:
  71. return True
  72. return False
  73. def _contains(self, nodes, obj):
  74. if isinstance(obj, Node):
  75. for node in nodes:
  76. if node is obj:
  77. return True
  78. else:
  79. if obj in nodes:
  80. return True
  81. return False
  82. def _do_search(self, obj, recursive, callback, context, *args, **kwargs):
  83. if recursive:
  84. for i, node in enumerate(context.nodes):
  85. if self._is_equivalent(obj, node):
  86. return callback(context, i, *args, **kwargs)
  87. if self._contains(self._get_children(node), obj):
  88. context = self._get_context(node, obj)
  89. return self._do_search(obj, recursive, callback, context,
  90. *args, **kwargs)
  91. raise ValueError(obj)
  92. callback(context, self.index(obj, recursive=False), *args, **kwargs)
  93. def _get_tree(self, code, lines, marker, indent):
  94. def write(*args):
  95. if lines and lines[-1] is marker: # Continue from the last line
  96. lines.pop() # Remove the marker
  97. last = lines.pop()
  98. lines.append(last + " ".join(args))
  99. else:
  100. lines.append(" " * 6 * indent + " ".join(args))
  101. get = lambda code: self._get_tree(code, lines, marker, indent + 1)
  102. mark = lambda: lines.append(marker)
  103. for node in code.nodes:
  104. node.__showtree__(write, get, mark)
  105. return lines
  106. @property
  107. def nodes(self):
  108. return self._nodes
  109. @nodes.setter
  110. def nodes(self, value):
  111. self._nodes = value
  112. def get(self, index):
  113. return self.nodes[index]
  114. def set(self, index, value):
  115. nodes = parse_anything(value).nodes
  116. if len(nodes) > 1:
  117. raise ValueError("Cannot coerce multiple nodes into one index")
  118. if index >= len(self.nodes) or -1 * index > len(self.nodes):
  119. raise IndexError("List assignment index out of range")
  120. self.nodes.pop(index)
  121. if nodes:
  122. self.nodes[index] = nodes[0]
  123. def index(self, obj, recursive=False):
  124. if recursive:
  125. for i, node in enumerate(self.nodes):
  126. if self._contains(self._get_children(node), obj):
  127. return i
  128. raise ValueError(obj)
  129. for i, node in enumerate(self.nodes):
  130. if self._is_equivalent(obj, node):
  131. return i
  132. raise ValueError(obj)
  133. def insert(self, index, value):
  134. nodes = parse_anything(value).nodes
  135. for node in reversed(nodes):
  136. self.nodes.insert(index, node)
  137. def insert_before(self, obj, value, recursive=True):
  138. callback = lambda self, i, value: self.insert(i, value)
  139. self._do_search(obj, recursive, callback, self, value)
  140. def insert_after(self, obj, value, recursive=True):
  141. callback = lambda self, i, value: self.insert(i + 1, value)
  142. self._do_search(obj, recursive, callback, self, value)
  143. def replace(self, obj, value, recursive=True):
  144. def callback(self, i, value):
  145. self.nodes.pop(i)
  146. self.insert(i, value)
  147. self._do_search(obj, recursive, callback, self, value)
  148. def append(self, value):
  149. nodes = parse_anything(value).nodes
  150. for node in nodes:
  151. self.nodes.append(node)
  152. def remove(self, obj, recursive=True):
  153. callback = lambda self, i: self.nodes.pop(i)
  154. self._do_search(obj, recursive, callback, self)
  155. def ifilter(self, recursive=False, matches=None, flags=FLAGS,
  156. forcetype=None):
  157. if recursive:
  158. nodes = self._get_all_nodes(self)
  159. else:
  160. nodes = self.nodes
  161. for node in nodes:
  162. if not forcetype or isinstance(node, forcetype):
  163. if not matches or re.search(matches, str(node), flags):
  164. yield node
  165. def ifilter_templates(self, recursive=False, matches=None, flags=FLAGS):
  166. return self.filter(recursive, matches, flags, forcetype=Template)
  167. def ifilter_text(self, recursive=False, matches=None, flags=FLAGS):
  168. return self.filter(recursive, matches, flags, forcetype=Text)
  169. def ifilter_tags(self, recursive=False, matches=None, flags=FLAGS):
  170. return self.ifilter(recursive, matches, flags, forcetype=Tag)
  171. def filter(self, recursive=False, matches=None, flags=FLAGS,
  172. forcetype=None):
  173. return list(self.ifilter(recursive, matches, flags, forcetype))
  174. def filter_templates(self, recursive=False, matches=None, flags=FLAGS):
  175. return list(self.ifilter_templates(recursive, matches, flags))
  176. def filter_text(self, recursive=False, matches=None, flags=FLAGS):
  177. return list(self.ifilter_text(recursive, matches, flags))
  178. def filter_tags(self, recursive=False, matches=None, flags=FLAGS):
  179. return list(self.ifilter_tags(recursive, matches, flags))
  180. def get_sections(self, flat=True, matches=None, levels=None, flags=FLAGS,
  181. include_headings=True):
  182. if matches:
  183. matches = r"^(=+?)\s*" + matches + r"\s*\1$"
  184. headings = self.filter(recursive=True, matches=matches, flags=flags,
  185. forcetype=Heading)
  186. if levels:
  187. headings = [head for head in headings if head.level in levels]
  188. sections = []
  189. buffers = [[maxsize, 0]]
  190. i = 0
  191. while i < len(self.nodes):
  192. if self.nodes[i] in headings:
  193. this = self.nodes[i].level
  194. for (level, start) in buffers:
  195. if not flat or this <= level:
  196. buffers.remove([level, start])
  197. sections.append(self.nodes[start:i])
  198. buffers.append([this, i])
  199. if not include_headings:
  200. i += 1
  201. i += 1
  202. for (level, start) in buffers:
  203. if start != i:
  204. sections.append(self.nodes[start:i])
  205. return sections
  206. def strip_code(self, normalize=True, collapse=True):
  207. nodes = []
  208. for node in self.nodes:
  209. stripped = node.__strip__(normalize, collapse)
  210. if stripped:
  211. nodes.append(str(stripped))
  212. if collapse:
  213. stripped = "".join(nodes).strip("\n")
  214. while "\n\n\n" in stripped:
  215. stripped = stripped.replace("\n\n\n", "\n\n")
  216. return stripped
  217. else:
  218. return "".join(nodes)
  219. def get_tree(self):
  220. marker = object() # Random object we can find with certainty in a list
  221. return "\n".join(self._get_tree(self, [], marker, 0))