A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

278 wiersze
8.2 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 ..utils import parse_anything
  26. __all__ = ["Tag"]
  27. class Tag(Node):
  28. """Represents an HTML-style tag in wikicode, like ``<ref>``."""
  29. TAG_UNKNOWN = 0
  30. # Basic HTML:
  31. TAG_ITALIC = 1
  32. TAG_BOLD = 2
  33. TAG_UNDERLINE = 3
  34. TAG_STRIKETHROUGH = 4
  35. TAG_UNORDERED_LIST = 5
  36. TAG_ORDERED_LIST = 6
  37. TAG_DEF_TERM = 7
  38. TAG_DEF_ITEM = 8
  39. TAG_BLOCKQUOTE = 9
  40. TAG_RULE = 10
  41. TAG_BREAK = 11
  42. TAG_ABBR = 12
  43. TAG_PRE = 13
  44. TAG_MONOSPACE = 14
  45. TAG_CODE = 15
  46. TAG_SPAN = 16
  47. TAG_DIV = 17
  48. TAG_FONT = 18
  49. TAG_SMALL = 19
  50. TAG_BIG = 20
  51. TAG_CENTER = 21
  52. # MediaWiki parser hooks:
  53. TAG_REF = 101
  54. TAG_GALLERY = 102
  55. TAG_MATH = 103
  56. TAG_NOWIKI = 104
  57. TAG_NOINCLUDE = 105
  58. TAG_INCLUDEONLY = 106
  59. TAG_ONLYINCLUDE = 107
  60. # Additional parser hooks:
  61. TAG_SYNTAXHIGHLIGHT = 201
  62. TAG_POEM = 202
  63. # Lists of tags:
  64. TAGS_INVISIBLE = set((TAG_REF, TAG_GALLERY, TAG_MATH, TAG_NOINCLUDE))
  65. TAGS_VISIBLE = set(range(300)) - TAGS_INVISIBLE
  66. TRANSLATIONS = {
  67. "i": TAG_ITALIC,
  68. "em": TAG_ITALIC,
  69. "b": TAG_BOLD,
  70. "strong": TAG_BOLD,
  71. "u": TAG_UNDERLINE,
  72. "s": TAG_STRIKETHROUGH,
  73. "ul": TAG_UNORDERED_LIST,
  74. "ol": TAG_ORDERED_LIST,
  75. "dt": TAG_DEF_TERM,
  76. "dd": TAG_DEF_ITEM,
  77. "blockquote": TAG_BLOCKQUOTE,
  78. "hl": TAG_RULE,
  79. "br": TAG_BREAK,
  80. "abbr": TAG_ABBR,
  81. "pre": TAG_PRE,
  82. "tt": TAG_MONOSPACE,
  83. "code": TAG_CODE,
  84. "span": TAG_SPAN,
  85. "div": TAG_DIV,
  86. "font": TAG_FONT,
  87. "small": TAG_SMALL,
  88. "big": TAG_BIG,
  89. "center": TAG_CENTER,
  90. "ref": TAG_REF,
  91. "gallery": TAG_GALLERY,
  92. "math": TAG_MATH,
  93. "nowiki": TAG_NOWIKI,
  94. "noinclude": TAG_NOINCLUDE,
  95. "includeonly": TAG_INCLUDEONLY,
  96. "onlyinclude": TAG_ONLYINCLUDE,
  97. "syntaxhighlight": TAG_SYNTAXHIGHLIGHT,
  98. "source": TAG_SYNTAXHIGHLIGHT,
  99. "poem": TAG_POEM,
  100. }
  101. def __init__(self, type_, tag, contents=None, attrs=None, showtag=True,
  102. self_closing=False, open_padding="", close_padding=""):
  103. super(Tag, self).__init__()
  104. self._type = type_
  105. self._tag = tag
  106. self._contents = contents
  107. if attrs:
  108. self._attrs = attrs
  109. else:
  110. self._attrs = []
  111. self._showtag = showtag
  112. self._self_closing = self_closing
  113. self._open_padding = open_padding
  114. self._close_padding = close_padding
  115. def __unicode__(self):
  116. if not self.showtag:
  117. open_, close = self._translate()
  118. if self.self_closing:
  119. return open_
  120. else:
  121. return open_ + str(self.contents) + close
  122. result = "<" + str(self.tag)
  123. if self.attrs:
  124. result += " " + " ".join([str(attr) for attr in self.attrs])
  125. if self.self_closing:
  126. result += self.open_padding + "/>"
  127. else:
  128. result += self.open_padding + ">" + str(self.contents)
  129. result += "</" + str(self.tag) + self.close_padding + ">"
  130. return result
  131. def __iternodes__(self, getter):
  132. yield None, self
  133. if self.showtag:
  134. for child in getter(self.tag):
  135. yield self.tag, child
  136. for attr in self.attrs:
  137. for child in getter(attr.name):
  138. yield attr.name, child
  139. if attr.value:
  140. for child in getter(attr.value):
  141. yield attr.value, child
  142. for child in getter(self.contents):
  143. yield self.contents, child
  144. def __strip__(self, normalize, collapse):
  145. if self.type in self.TAGS_VISIBLE:
  146. return self.contents.strip_code(normalize, collapse)
  147. return None
  148. def __showtree__(self, write, get, mark):
  149. tagnodes = self.tag.nodes
  150. if (not self.attrs and len(tagnodes) == 1 and isinstance(tagnodes[0], Text)):
  151. write("<" + str(tagnodes[0]) + ">")
  152. else:
  153. write("<")
  154. get(self.tag)
  155. for attr in self.attrs:
  156. get(attr.name)
  157. if not attr.value:
  158. continue
  159. write(" = ")
  160. mark()
  161. get(attr.value)
  162. write(">")
  163. get(self.contents)
  164. if len(tagnodes) == 1 and isinstance(tagnodes[0], Text):
  165. write("</" + str(tagnodes[0]) + ">")
  166. else:
  167. write("</")
  168. get(self.tag)
  169. write(">")
  170. def _translate(self):
  171. """If the HTML-style tag has a wikicode representation, return that.
  172. For example, ``<b>Foo</b>`` can be represented as ``'''Foo'''``. This
  173. returns a tuple of the character starting the sequence and the
  174. character ending it.
  175. """
  176. translations = {
  177. self.TAG_ITALIC: ("''", "''"),
  178. self.TAG_BOLD: ("'''", "'''"),
  179. self.TAG_UNORDERED_LIST: ("*", ""),
  180. self.TAG_ORDERED_LIST: ("#", ""),
  181. self.TAG_DEF_TERM: (";", ""),
  182. self.TAG_DEF_ITEM: (":", ""),
  183. self.TAG_RULE: ("----", ""),
  184. }
  185. return translations[self.type]
  186. @property
  187. def type(self):
  188. """The tag type."""
  189. return self._type
  190. @property
  191. def tag(self):
  192. """The tag itself, as a :py:class:`~.Wikicode` object."""
  193. return self._tag
  194. @property
  195. def contents(self):
  196. """The contents of the tag, as a :py:class:`~.Wikicode` object."""
  197. return self._contents
  198. @property
  199. def attrs(self):
  200. """The list of attributes affecting the tag.
  201. Each attribute is an instance of :py:class:`~.Attribute`.
  202. """
  203. return self._attrs
  204. @property
  205. def showtag(self):
  206. """Whether to show the tag itself instead of a wikicode version."""
  207. return self._showtag
  208. @property
  209. def self_closing(self):
  210. """Whether the tag is self-closing with no content (like ``<br/>``)."""
  211. return self._self_closing
  212. @property
  213. def open_padding(self):
  214. """Spacing to insert before the first closing >."""
  215. return self._open_padding
  216. @property
  217. def close_padding(self):
  218. """Spacing to insert before the last closing > (excl. self-closing)."""
  219. return self._close_padding
  220. @type.setter
  221. def type(self, value):
  222. value = int(value)
  223. if value not in self.TAGS_INVISIBLE | self.TAGS_VISIBLE:
  224. raise ValueError(value)
  225. self._type = value
  226. @tag.setter
  227. def tag(self, value):
  228. self._tag = parse_anything(value)
  229. @contents.setter
  230. def contents(self, value):
  231. self._contents = parse_anything(value)
  232. @showtag.setter
  233. def showtag(self, value):
  234. self._showtag = bool(value)
  235. @self_closing.setter
  236. def self_closing(self, value):
  237. self._self_closing = bool(value)
  238. @open_padding.setter
  239. def open_padding(self, value):
  240. self._open_padding = str(value)
  241. @close_padding.setter
  242. def close_padding(self, value):
  243. self._close_padding = str(value)