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.
 
 
 
 

300 lines
10 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, closing_wiki_markup=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. if wiki_markup and not self_closing:
  43. if closing_wiki_markup:
  44. self._closing_wiki_markup = closing_wiki_markup
  45. else:
  46. self._closing_wiki_markup = wiki_markup
  47. else:
  48. self._closing_wiki_markup = None
  49. self._self_closing = self_closing
  50. self._invalid = invalid
  51. self._implicit = implicit
  52. self._padding = padding
  53. if closing_tag:
  54. self._closing_tag = closing_tag
  55. else:
  56. self._closing_tag = tag
  57. def __unicode__(self):
  58. if self.wiki_markup:
  59. attrs = "".join([str(attr) for attr in self.attributes]) if self.attributes else ""
  60. if self.self_closing:
  61. return self.wiki_markup
  62. else:
  63. return self.wiki_markup + attrs + str(self.contents) + self.closing_wiki_markup
  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 self.contents:
  81. yield self.contents
  82. if not self.self_closing and not self.wiki_markup and self.closing_tag:
  83. yield self.closing_tag
  84. def __strip__(self, normalize, collapse):
  85. if self.contents and is_visible(self.tag):
  86. return self.contents.strip_code(normalize, collapse)
  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 closing_wiki_markup(self):
  130. """The wikified version of the closing tag to show instead of HTML.
  131. If set to a value, this will be displayed instead of the close tag
  132. brackets. If tag is :attr:`self_closing` is ``True``, this is set to
  133. ``None`` and not displayed. If :attr:`wiki_markup` is set and this has
  134. not been set, this is set to the value of :attr:`wiki_markup`. If this
  135. has been set and :attr:`wiki_markup` is set to a ``False`` value, this
  136. is set to ``None``.
  137. """
  138. return self._closing_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. @tag.setter
  172. def tag(self, value):
  173. self._tag = self._closing_tag = parse_anything(value)
  174. @contents.setter
  175. def contents(self, value):
  176. self._contents = parse_anything(value)
  177. @wiki_markup.setter
  178. def wiki_markup(self, value):
  179. self._wiki_markup = str(value) if value else None
  180. if not value or not self.closing_wiki_markup:
  181. self.closing_wiki_markup = str(value) if value else None
  182. @closing_wiki_markup.setter
  183. def closing_wiki_markup(self, value):
  184. self._closing_wiki_markup = str(value) if value and not self.self_closing else None
  185. @self_closing.setter
  186. def self_closing(self, value):
  187. self._self_closing = bool(value)
  188. if not bool(value):
  189. self.closing_wiki_markup = None
  190. @invalid.setter
  191. def invalid(self, value):
  192. self._invalid = bool(value)
  193. @implicit.setter
  194. def implicit(self, value):
  195. self._implicit = bool(value)
  196. @padding.setter
  197. def padding(self, value):
  198. if not value:
  199. self._padding = ""
  200. else:
  201. value = str(value)
  202. if not value.isspace():
  203. raise ValueError("padding must be entirely whitespace")
  204. self._padding = value
  205. @closing_tag.setter
  206. def closing_tag(self, value):
  207. self._closing_tag = parse_anything(value)
  208. def has(self, name):
  209. """Return whether any attribute in the tag has the given *name*.
  210. Note that a tag may have multiple attributes with the same name, but
  211. only the last one is read by the MediaWiki parser.
  212. """
  213. for attr in self.attributes:
  214. if attr.name == name.strip():
  215. return True
  216. return False
  217. def get(self, name):
  218. """Get the attribute with the given *name*.
  219. The returned object is a :class:`.Attribute` instance. Raises
  220. :exc:`ValueError` if no attribute has this name. Since multiple
  221. attributes can have the same name, we'll return the last match, since
  222. all but the last are ignored by the MediaWiki parser.
  223. """
  224. for attr in reversed(self.attributes):
  225. if attr.name == name.strip():
  226. return attr
  227. raise ValueError(name)
  228. def add(self, name, value=None, quotes='"', pad_first=" ",
  229. pad_before_eq="", pad_after_eq=""):
  230. """Add an attribute with the given *name* and *value*.
  231. *name* and *value* can be anything parsable by
  232. :func:`.utils.parse_anything`; *value* can be omitted if the attribute
  233. is valueless. If *quotes* is not ``None``, it should be a string
  234. (either ``"`` or ``'``) that *value* will be wrapped in (this is
  235. recommended). ``None`` is only legal if *value* contains no spacing.
  236. *pad_first*, *pad_before_eq*, and *pad_after_eq* are whitespace used as
  237. padding before the name, before the equal sign (or after the name if no
  238. value), and after the equal sign (ignored if no value), respectively.
  239. """
  240. if value is not None:
  241. value = parse_anything(value)
  242. quotes = Attribute.coerce_quotes(quotes)
  243. attr = Attribute(parse_anything(name), value, quotes)
  244. attr.pad_first = pad_first
  245. attr.pad_before_eq = pad_before_eq
  246. attr.pad_after_eq = pad_after_eq
  247. self.attributes.append(attr)
  248. return attr
  249. def remove(self, name):
  250. """Remove all attributes with the given *name*."""
  251. attrs = [attr for attr in self.attributes if attr.name == name.strip()]
  252. if not attrs:
  253. raise ValueError(name)
  254. for attr in attrs:
  255. self.attributes.remove(attr)