A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

198 linhas
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.attributes:
  56. result += " " + " ".join([str(attr) for attr in self.attributes])
  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.attributes:
  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.attributes and (len(tagnodes) == 1 and
  83. isinstance(tagnodes[0], Text)):
  84. write("<" + str(tagnodes[0]) + ">")
  85. else:
  86. write("<")
  87. get(self.tag)
  88. for attr in self.attributes:
  89. get(attr.name)
  90. if not attr.value:
  91. continue
  92. write(" = ")
  93. mark()
  94. get(attr.value)
  95. write(">")
  96. get(self.contents)
  97. if len(tagnodes) == 1 and isinstance(tagnodes[0], Text):
  98. write("</" + str(tagnodes[0]) + ">")
  99. else:
  100. write("</")
  101. get(self.tag)
  102. write(">")
  103. @property
  104. def type(self):
  105. """The tag type."""
  106. return self._type
  107. @property
  108. def tag(self):
  109. """The tag itself, as a :py:class:`~.Wikicode` object."""
  110. return self._tag
  111. @property
  112. def contents(self):
  113. """The contents of the tag, as a :py:class:`~.Wikicode` object."""
  114. return self._contents
  115. @property
  116. def attributes(self):
  117. """The list of attributes affecting the tag.
  118. Each attribute is an instance of :py:class:`~.Attribute`.
  119. """
  120. return self._attrs
  121. @property
  122. def showtag(self):
  123. """Whether to show the tag itself instead of a wikicode version."""
  124. return self._showtag
  125. @property
  126. def self_closing(self):
  127. """Whether the tag is self-closing with no content (like ``<br/>``)."""
  128. return self._self_closing
  129. @property
  130. def open_padding(self):
  131. """Spacing to insert before the first closing ``>``."""
  132. return self._open_padding
  133. @property
  134. def closing_tag(self):
  135. """The closing tag, as a :py:class:`~.Wikicode` object.
  136. This will usually equal :py:attr:`tag`, unless there is additional
  137. spacing, comments, or the like.
  138. """
  139. return self._closing_tag
  140. @type.setter
  141. def type(self, value):
  142. value = int(value)
  143. if value not in self.TAGS_ALL:
  144. raise ValueError(value)
  145. self._type = value
  146. for key in self.TRANSLATIONS:
  147. if self.TRANSLATIONS[key] == value:
  148. self._tag = self._closing_tag = parse_anything(key)
  149. @tag.setter
  150. def tag(self, value):
  151. self._tag = self._closing_tag = parse_anything(value)
  152. try:
  153. self._type = self.TRANSLATIONS[text]
  154. except KeyError:
  155. self._type = self.TAG_UNKNOWN
  156. @contents.setter
  157. def contents(self, value):
  158. self._contents = parse_anything(value)
  159. @showtag.setter
  160. def showtag(self, value):
  161. self._showtag = bool(value)
  162. @self_closing.setter
  163. def self_closing(self, value):
  164. self._self_closing = bool(value)
  165. @open_padding.setter
  166. def open_padding(self, value):
  167. self._open_padding = str(value)
  168. @closing_tag.setter
  169. def closing_tag(self, value):
  170. self._closing_tag = parse_anything(value)