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.
 
 
 
 

270 lines
9.2 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 . import Node
  24. from .extras import Attribute
  25. from ..compat import str
  26. from ..definitions import is_visible
  27. from ..utils import parse_anything
  28. __all__ = ["Tag"]
  29. class Tag(Node):
  30. """Represents an HTML-style tag in wikicode, like ``<ref>``."""
  31. def __init__(self, tag, contents=None, attrs=None, wiki_markup=None,
  32. self_closing=False, invalid=False, implicit=False, padding="",
  33. closing_tag=None):
  34. super(Tag, self).__init__()
  35. self._tag = tag
  36. if contents is None and not self_closing:
  37. self._contents = parse_anything("")
  38. else:
  39. self._contents = contents
  40. self._attrs = attrs if attrs else []
  41. self._wiki_markup = wiki_markup
  42. self._self_closing = self_closing
  43. self._invalid = invalid
  44. self._implicit = implicit
  45. self._padding = padding
  46. if closing_tag:
  47. self._closing_tag = closing_tag
  48. else:
  49. self._closing_tag = tag
  50. def __unicode__(self):
  51. if self.wiki_markup:
  52. if self.self_closing:
  53. return self.wiki_markup
  54. else:
  55. return self.wiki_markup + str(self.contents) + self.wiki_markup
  56. result = ("</" if self.invalid else "<") + str(self.tag)
  57. if self.attributes:
  58. result += "".join([str(attr) for attr in self.attributes])
  59. if self.self_closing:
  60. result += self.padding + (">" if self.implicit else "/>")
  61. else:
  62. result += self.padding + ">" + str(self.contents)
  63. result += "</" + str(self.closing_tag) + ">"
  64. return result
  65. def __children__(self):
  66. if not self.wiki_markup:
  67. yield self.tag
  68. for attr in self.attributes:
  69. yield attr.name
  70. if attr.value is not None:
  71. yield attr.value
  72. if self.contents:
  73. yield self.contents
  74. if not self.self_closing and not self.wiki_markup and self.closing_tag:
  75. yield self.closing_tag
  76. def __strip__(self, normalize, collapse):
  77. if self.contents and is_visible(self.tag):
  78. return self.contents.strip_code(normalize, collapse)
  79. return None
  80. def __showtree__(self, write, get, mark):
  81. write("</" if self.invalid else "<")
  82. get(self.tag)
  83. for attr in self.attributes:
  84. get(attr.name)
  85. if not attr.value:
  86. continue
  87. write(" = ")
  88. mark()
  89. get(attr.value)
  90. if self.self_closing:
  91. write(">" if self.implicit else "/>")
  92. else:
  93. write(">")
  94. get(self.contents)
  95. write("</")
  96. get(self.closing_tag)
  97. write(">")
  98. @property
  99. def tag(self):
  100. """The tag itself, as a :py:class:`~.Wikicode` object."""
  101. return self._tag
  102. @property
  103. def contents(self):
  104. """The contents of the tag, as a :py:class:`~.Wikicode` object."""
  105. return self._contents
  106. @property
  107. def attributes(self):
  108. """The list of attributes affecting the tag.
  109. Each attribute is an instance of :py:class:`~.Attribute`.
  110. """
  111. return self._attrs
  112. @property
  113. def wiki_markup(self):
  114. """The wikified version of a tag to show instead of HTML.
  115. If set to a value, this will be displayed instead of the brackets.
  116. For example, set to ``''`` to replace ``<i>`` or ``----`` to replace
  117. ``<hr>``.
  118. """
  119. return self._wiki_markup
  120. @property
  121. def self_closing(self):
  122. """Whether the tag is self-closing with no content (like ``<br/>``)."""
  123. return self._self_closing
  124. @property
  125. def invalid(self):
  126. """Whether the tag starts with a backslash after the opening bracket.
  127. This makes the tag look like a lone close tag. It is technically
  128. invalid and is only parsable Wikicode when the tag itself is
  129. single-only, like ``<br>`` and ``<img>``. See
  130. :py:func:`.definitions.is_single_only`.
  131. """
  132. return self._invalid
  133. @property
  134. def implicit(self):
  135. """Whether the tag is implicitly self-closing, with no ending slash.
  136. This is only possible for specific "single" tags like ``<br>`` and
  137. ``<li>``. See :py:func:`.definitions.is_single`. This field only has an
  138. effect if :py:attr:`self_closing` is also ``True``.
  139. """
  140. return self._implicit
  141. @property
  142. def padding(self):
  143. """Spacing to insert before the first closing ``>``."""
  144. return self._padding
  145. @property
  146. def closing_tag(self):
  147. """The closing tag, as a :py:class:`~.Wikicode` object.
  148. This will usually equal :py:attr:`tag`, unless there is additional
  149. spacing, comments, or the like.
  150. """
  151. return self._closing_tag
  152. @tag.setter
  153. def tag(self, value):
  154. self._tag = self._closing_tag = parse_anything(value)
  155. @contents.setter
  156. def contents(self, value):
  157. self._contents = parse_anything(value)
  158. @wiki_markup.setter
  159. def wiki_markup(self, value):
  160. self._wiki_markup = str(value) if value else None
  161. @self_closing.setter
  162. def self_closing(self, value):
  163. self._self_closing = bool(value)
  164. @invalid.setter
  165. def invalid(self, value):
  166. self._invalid = bool(value)
  167. @implicit.setter
  168. def implicit(self, value):
  169. self._implicit = bool(value)
  170. @padding.setter
  171. def padding(self, value):
  172. if not value:
  173. self._padding = ""
  174. else:
  175. value = str(value)
  176. if not value.isspace():
  177. raise ValueError("padding must be entirely whitespace")
  178. self._padding = value
  179. @closing_tag.setter
  180. def closing_tag(self, value):
  181. self._closing_tag = parse_anything(value)
  182. def has(self, name):
  183. """Return whether any attribute in the tag has the given *name*.
  184. Note that a tag may have multiple attributes with the same name, but
  185. only the last one is read by the MediaWiki parser.
  186. """
  187. for attr in self.attributes:
  188. if attr.name == name.strip():
  189. return True
  190. return False
  191. def get(self, name):
  192. """Get the attribute with the given *name*.
  193. The returned object is a :py:class:`~.Attribute` instance. Raises
  194. :py:exc:`ValueError` if no attribute has this name. Since multiple
  195. attributes can have the same name, we'll return the last match, since
  196. all but the last are ignored by the MediaWiki parser.
  197. """
  198. for attr in reversed(self.attributes):
  199. if attr.name == name.strip():
  200. return attr
  201. raise ValueError(name)
  202. def add(self, name, value=None, quotes='"', pad_first=" ",
  203. pad_before_eq="", pad_after_eq=""):
  204. """Add an attribute with the given *name* and *value*.
  205. *name* and *value* can be anything parsable by
  206. :py:func:`.utils.parse_anything`; *value* can be omitted if the
  207. attribute is valueless. If *quotes* is not ``None``, it should be a
  208. string (either ``"`` or ``'``) that *value* will be wrapped in (this is
  209. recommended). ``None`` is only legal if *value* contains no spacing.
  210. *pad_first*, *pad_before_eq*, and *pad_after_eq* are whitespace used as
  211. padding before the name, before the equal sign (or after the name if no
  212. value), and after the equal sign (ignored if no value), respectively.
  213. """
  214. if value is not None:
  215. value = parse_anything(value)
  216. quotes = Attribute.coerce_quotes(quotes)
  217. attr = Attribute(parse_anything(name), value, quotes)
  218. attr.pad_first = pad_first
  219. attr.pad_before_eq = pad_before_eq
  220. attr.pad_after_eq = pad_after_eq
  221. self.attributes.append(attr)
  222. return attr
  223. def remove(self, name):
  224. """Remove all attributes with the given *name*."""
  225. attrs = [attr for attr in self.attributes if attr.name == name.strip()]
  226. if not attrs:
  227. raise ValueError(name)
  228. for attr in attrs:
  229. self.attributes.remove(attr)