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

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