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.
 
 
 
 

312 lines
11 KiB

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