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.
 
 
 
 

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