A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

317 lines
11 KiB

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