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.
 
 
 
 

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