A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

197 строки
6.3 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  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, Text
  24. from ..compat import str
  25. from ..tag_defs import TagDefinitions
  26. from ..utils import parse_anything
  27. __all__ = ["Tag"]
  28. class Tag(TagDefinitions, Node):
  29. """Represents an HTML-style tag in wikicode, like ``<ref>``."""
  30. def __init__(self, type_, tag, contents=None, attrs=None, showtag=True,
  31. self_closing=False, open_padding="", closing_tag=None):
  32. super(Tag, self).__init__()
  33. self._type = type_
  34. self._tag = tag
  35. self._contents = contents
  36. if attrs:
  37. self._attrs = attrs
  38. else:
  39. self._attrs = []
  40. self._showtag = showtag
  41. self._self_closing = self_closing
  42. self._open_padding = open_padding
  43. if closing_tag:
  44. self._closing_tag = closing_tag
  45. else:
  46. self._closing_tag = tag
  47. def __unicode__(self):
  48. if not self.showtag:
  49. open_, close = self.WIKICODE[self.type]
  50. if self.self_closing:
  51. return open_
  52. else:
  53. return open_ + str(self.contents) + close
  54. result = "<" + str(self.tag)
  55. if self.attrs:
  56. result += " " + " ".join([str(attr) for attr in self.attrs])
  57. if self.self_closing:
  58. result += self.open_padding + "/>"
  59. else:
  60. result += self.open_padding + ">" + str(self.contents)
  61. result += "</" + str(self.closing_tag) + ">"
  62. return result
  63. def __iternodes__(self, getter):
  64. yield None, self
  65. if self.showtag:
  66. for child in getter(self.tag):
  67. yield self.tag, child
  68. for attr in self.attrs:
  69. for child in getter(attr.name):
  70. yield attr.name, child
  71. if attr.value:
  72. for child in getter(attr.value):
  73. yield attr.value, child
  74. for child in getter(self.contents):
  75. yield self.contents, child
  76. def __strip__(self, normalize, collapse):
  77. if self.type in self.TAGS_VISIBLE:
  78. return self.contents.strip_code(normalize, collapse)
  79. return None
  80. def __showtree__(self, write, get, mark):
  81. tagnodes = self.tag.nodes
  82. if (not self.attrs and len(tagnodes) == 1 and isinstance(tagnodes[0], Text)):
  83. write("<" + str(tagnodes[0]) + ">")
  84. else:
  85. write("<")
  86. get(self.tag)
  87. for attr in self.attrs:
  88. get(attr.name)
  89. if not attr.value:
  90. continue
  91. write(" = ")
  92. mark()
  93. get(attr.value)
  94. write(">")
  95. get(self.contents)
  96. if len(tagnodes) == 1 and isinstance(tagnodes[0], Text):
  97. write("</" + str(tagnodes[0]) + ">")
  98. else:
  99. write("</")
  100. get(self.tag)
  101. write(">")
  102. @property
  103. def type(self):
  104. """The tag type."""
  105. return self._type
  106. @property
  107. def tag(self):
  108. """The tag itself, as a :py:class:`~.Wikicode` object."""
  109. return self._tag
  110. @property
  111. def contents(self):
  112. """The contents of the tag, as a :py: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 :py:class:`~.Attribute`.
  118. """
  119. return self._attrs
  120. @property
  121. def showtag(self):
  122. """Whether to show the tag itself instead of a wikicode version."""
  123. return self._showtag
  124. @property
  125. def self_closing(self):
  126. """Whether the tag is self-closing with no content (like ``<br/>``)."""
  127. return self._self_closing
  128. @property
  129. def open_padding(self):
  130. """Spacing to insert before the first closing ``>``."""
  131. return self._open_padding
  132. @property
  133. def closing_tag(self):
  134. """The closing tag, as a :py:class:`~.Wikicode` object.
  135. This will usually equal :py:attr:`tag`, unless there is additional
  136. spacing, comments, or the like.
  137. """
  138. return self._closing_tag
  139. @type.setter
  140. def type(self, value):
  141. value = int(value)
  142. if value not in self.TAGS_ALL:
  143. raise ValueError(value)
  144. self._type = value
  145. for key in self.TRANSLATIONS:
  146. if self.TRANSLATIONS[key] == value:
  147. self._tag = self._closing_tag = parse_anything(key)
  148. @tag.setter
  149. def tag(self, value):
  150. self._tag = self._closing_tag = parse_anything(value)
  151. try:
  152. self._type = self.TRANSLATIONS[text]
  153. except KeyError:
  154. self._type = self.TAG_UNKNOWN
  155. @contents.setter
  156. def contents(self, value):
  157. self._contents = parse_anything(value)
  158. @showtag.setter
  159. def showtag(self, value):
  160. self._showtag = bool(value)
  161. @self_closing.setter
  162. def self_closing(self, value):
  163. self._self_closing = bool(value)
  164. @open_padding.setter
  165. def open_padding(self, value):
  166. self._open_padding = str(value)
  167. @closing_tag.setter
  168. def closing_tag(self, value):
  169. self._closing_tag = parse_anything(value)