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.
 
 
 
 

307 lines
11 KiB

  1. # Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. from ._base import Node
  21. from .extras import Attribute
  22. from ..definitions import is_visible
  23. from ..utils import parse_anything
  24. __all__ = ["Tag"]
  25. class Tag(Node):
  26. """Represents an HTML-style tag in wikicode, like ``<ref>``."""
  27. def __init__(self, tag, contents=None, attrs=None, wiki_markup=None,
  28. self_closing=False, invalid=False, implicit=False, padding="",
  29. closing_tag=None, wiki_style_separator=None,
  30. closing_wiki_markup=None):
  31. super().__init__()
  32. self.tag = tag
  33. self.contents = contents
  34. self._attrs = attrs if attrs else []
  35. self._closing_wiki_markup = None
  36. self.wiki_markup = wiki_markup
  37. self.self_closing = self_closing
  38. self.invalid = invalid
  39. self.implicit = implicit
  40. self.padding = padding
  41. if closing_tag is not None:
  42. self.closing_tag = closing_tag
  43. self.wiki_style_separator = wiki_style_separator
  44. if closing_wiki_markup is not None:
  45. self.closing_wiki_markup = closing_wiki_markup
  46. def __str__(self):
  47. if self.wiki_markup:
  48. if self.attributes:
  49. attrs = "".join([str(attr) for attr in self.attributes])
  50. else:
  51. attrs = ""
  52. padding = self.padding or ""
  53. separator = self.wiki_style_separator or ""
  54. if self.self_closing:
  55. return self.wiki_markup + attrs + padding + separator
  56. close = self.closing_wiki_markup or ""
  57. return self.wiki_markup + attrs + padding + separator + \
  58. str(self.contents) + close
  59. result = ("</" if self.invalid else "<") + str(self.tag)
  60. if self.attributes:
  61. result += "".join([str(attr) for attr in self.attributes])
  62. if self.self_closing:
  63. result += self.padding + (">" if self.implicit else "/>")
  64. else:
  65. result += self.padding + ">" + str(self.contents)
  66. result += "</" + str(self.closing_tag) + ">"
  67. return result
  68. def __children__(self):
  69. if not self.wiki_markup:
  70. yield self.tag
  71. for attr in self.attributes:
  72. yield attr.name
  73. if attr.value is not None:
  74. yield attr.value
  75. if not self.self_closing:
  76. yield self.contents
  77. if not self.wiki_markup and self.closing_tag:
  78. yield self.closing_tag
  79. def __strip__(self, **kwargs):
  80. if self.contents and is_visible(self.tag):
  81. return self.contents.strip_code(**kwargs)
  82. return None
  83. def __showtree__(self, write, get, mark):
  84. write("</" if self.invalid else "<")
  85. get(self.tag)
  86. for attr in self.attributes:
  87. get(attr.name)
  88. if not attr.value:
  89. continue
  90. write(" = ")
  91. mark()
  92. get(attr.value)
  93. if self.self_closing:
  94. write(">" if self.implicit else "/>")
  95. else:
  96. write(">")
  97. get(self.contents)
  98. write("</")
  99. get(self.closing_tag)
  100. write(">")
  101. @property
  102. def tag(self):
  103. """The tag itself, as a :class:`.Wikicode` object."""
  104. return self._tag
  105. @property
  106. def contents(self):
  107. """The contents of the tag, as a :class:`.Wikicode` object."""
  108. return self._contents
  109. @property
  110. def attributes(self):
  111. """The list of attributes affecting the tag.
  112. Each attribute is an instance of :class:`.Attribute`.
  113. """
  114. return self._attrs
  115. @property
  116. def wiki_markup(self):
  117. """The wikified version of a tag to show instead of HTML.
  118. If set to a value, this will be displayed instead of the brackets.
  119. For example, set to ``''`` to replace ``<i>`` or ``----`` to replace
  120. ``<hr>``.
  121. """
  122. return self._wiki_markup
  123. @property
  124. def self_closing(self):
  125. """Whether the tag is self-closing with no content (like ``<br/>``)."""
  126. return self._self_closing
  127. @property
  128. def invalid(self):
  129. """Whether the tag starts with a backslash after the opening bracket.
  130. This makes the tag look like a lone close tag. It is technically
  131. invalid and is only parsable Wikicode when the tag itself is
  132. single-only, like ``<br>`` and ``<img>``. See
  133. :func:`.definitions.is_single_only`.
  134. """
  135. return self._invalid
  136. @property
  137. def implicit(self):
  138. """Whether the tag is implicitly self-closing, with no ending slash.
  139. This is only possible for specific "single" tags like ``<br>`` and
  140. ``<li>``. See :func:`.definitions.is_single`. This field only has an
  141. effect if :attr:`self_closing` is also ``True``.
  142. """
  143. return self._implicit
  144. @property
  145. def padding(self):
  146. """Spacing to insert before the first closing ``>``."""
  147. return self._padding
  148. @property
  149. def closing_tag(self):
  150. """The closing tag, as a :class:`.Wikicode` object.
  151. This will usually equal :attr:`tag`, unless there is additional
  152. spacing, comments, or the like.
  153. """
  154. return self._closing_tag
  155. @property
  156. def wiki_style_separator(self):
  157. """The separator between the padding and content in a wiki markup tag.
  158. Essentially the wiki equivalent of the TagCloseOpen.
  159. """
  160. return self._wiki_style_separator
  161. @property
  162. def closing_wiki_markup(self):
  163. """The wikified version of the closing tag to show instead of HTML.
  164. If set to a value, this will be displayed instead of the close tag
  165. brackets. If tag is :attr:`self_closing` is ``True`` then this is not
  166. displayed. If :attr:`wiki_markup` is set and this has not been set, this
  167. is set to the value of :attr:`wiki_markup`. If this has been set and
  168. :attr:`wiki_markup` is set to a ``False`` value, this is set to
  169. ``None``.
  170. """
  171. return self._closing_wiki_markup
  172. @tag.setter
  173. def tag(self, value):
  174. self._tag = self._closing_tag = parse_anything(value)
  175. @contents.setter
  176. def contents(self, value):
  177. self._contents = parse_anything(value)
  178. @wiki_markup.setter
  179. def wiki_markup(self, value):
  180. self._wiki_markup = str(value) if value else None
  181. if not value or not self.closing_wiki_markup:
  182. self._closing_wiki_markup = self._wiki_markup
  183. @self_closing.setter
  184. def self_closing(self, value):
  185. self._self_closing = bool(value)
  186. @invalid.setter
  187. def invalid(self, value):
  188. self._invalid = bool(value)
  189. @implicit.setter
  190. def implicit(self, value):
  191. self._implicit = bool(value)
  192. @padding.setter
  193. def padding(self, value):
  194. if not value:
  195. self._padding = ""
  196. else:
  197. value = str(value)
  198. if not value.isspace():
  199. raise ValueError("padding must be entirely whitespace")
  200. self._padding = value
  201. @closing_tag.setter
  202. def closing_tag(self, value):
  203. self._closing_tag = parse_anything(value)
  204. @wiki_style_separator.setter
  205. def wiki_style_separator(self, value):
  206. self._wiki_style_separator = str(value) if value else None
  207. @closing_wiki_markup.setter
  208. def closing_wiki_markup(self, value):
  209. self._closing_wiki_markup = str(value) if value else None
  210. def has(self, name):
  211. """Return whether any attribute in the tag has the given *name*.
  212. Note that a tag may have multiple attributes with the same name, but
  213. only the last one is read by the MediaWiki parser.
  214. """
  215. for attr in self.attributes:
  216. if attr.name == name.strip():
  217. return True
  218. return False
  219. def get(self, name):
  220. """Get the attribute with the given *name*.
  221. The returned object is a :class:`.Attribute` instance. Raises
  222. :exc:`ValueError` if no attribute has this name. Since multiple
  223. attributes can have the same name, we'll return the last match, since
  224. all but the last are ignored by the MediaWiki parser.
  225. """
  226. for attr in reversed(self.attributes):
  227. if attr.name == name.strip():
  228. return attr
  229. raise ValueError(name)
  230. def add(self, name, value=None, quotes='"', pad_first=" ",
  231. pad_before_eq="", pad_after_eq=""):
  232. """Add an attribute with the given *name* and *value*.
  233. *name* and *value* can be anything parsable by
  234. :func:`.utils.parse_anything`; *value* can be omitted if the attribute
  235. is valueless. If *quotes* is not ``None``, it should be a string
  236. (either ``"`` or ``'``) that *value* will be wrapped in (this is
  237. recommended). ``None`` is only legal if *value* contains no spacing.
  238. *pad_first*, *pad_before_eq*, and *pad_after_eq* are whitespace used as
  239. padding before the name, before the equal sign (or after the name if no
  240. value), and after the equal sign (ignored if no value), respectively.
  241. """
  242. if value is not None:
  243. value = parse_anything(value)
  244. quotes = Attribute.coerce_quotes(quotes)
  245. attr = Attribute(parse_anything(name), value, quotes)
  246. attr.pad_first = pad_first
  247. attr.pad_before_eq = pad_before_eq
  248. attr.pad_after_eq = pad_after_eq
  249. self.attributes.append(attr)
  250. return attr
  251. def remove(self, name):
  252. """Remove all attributes with the given *name*.
  253. Raises :exc:`ValueError` if none were found.
  254. """
  255. attrs = [attr for attr in self.attributes if attr.name == name.strip()]
  256. if not attrs:
  257. raise ValueError(name)
  258. for attr in attrs:
  259. self.attributes.remove(attr)