A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 11 година
пре 11 година
пре 10 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 10 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 10 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 9 година
пре 11 година
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  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 math import log
  24. import re
  25. from . import contexts, tokens, ParserError
  26. from ..compat import htmlentities, range
  27. from ..definitions import (get_html_tag, is_parsable, is_single,
  28. is_single_only, is_scheme)
  29. __all__ = ["Tokenizer"]
  30. class BadRoute(Exception):
  31. """Raised internally when the current tokenization route is invalid."""
  32. def __init__(self, context=0):
  33. super(BadRoute, self).__init__()
  34. self.context = context
  35. class _TagOpenData(object):
  36. """Stores data about an HTML open tag, like ``<ref name="foo">``."""
  37. CX_NAME = 1 << 0
  38. CX_ATTR_READY = 1 << 1
  39. CX_ATTR_NAME = 1 << 2
  40. CX_ATTR_VALUE = 1 << 3
  41. CX_QUOTED = 1 << 4
  42. CX_NOTE_SPACE = 1 << 5
  43. CX_NOTE_EQUALS = 1 << 6
  44. CX_NOTE_QUOTE = 1 << 7
  45. def __init__(self):
  46. self.context = self.CX_NAME
  47. self.padding_buffer = {"first": "", "before_eq": "", "after_eq": ""}
  48. self.quoter = None
  49. self.reset = 0
  50. class Tokenizer(object):
  51. """Creates a list of tokens from a string of wikicode."""
  52. USES_C = False
  53. START = object()
  54. END = object()
  55. MARKERS = ["{", "}", "[", "]", "<", ">", "|", "=", "&", "'", "#", "*", ";",
  56. ":", "/", "-", "!", "\n", START, END]
  57. MAX_DEPTH = 40
  58. MAX_CYCLES = 100000
  59. regex = re.compile(r"([{}\[\]<>|=&'#*;:/\\\"\-!\n])", flags=re.IGNORECASE)
  60. tag_splitter = re.compile(r"([\s\"\'\\]+)")
  61. def __init__(self):
  62. self._text = None
  63. self._head = 0
  64. self._stacks = []
  65. self._global = 0
  66. self._depth = 0
  67. self._cycles = 0
  68. @property
  69. def _stack(self):
  70. """The current token stack."""
  71. return self._stacks[-1][0]
  72. @property
  73. def _context(self):
  74. """The current token context."""
  75. return self._stacks[-1][1]
  76. @_context.setter
  77. def _context(self, value):
  78. self._stacks[-1][1] = value
  79. @property
  80. def _textbuffer(self):
  81. """The current textbuffer."""
  82. return self._stacks[-1][2]
  83. @_textbuffer.setter
  84. def _textbuffer(self, value):
  85. self._stacks[-1][2] = value
  86. def _push(self, context=0):
  87. """Add a new token stack, context, and textbuffer to the list."""
  88. self._stacks.append([[], context, []])
  89. self._depth += 1
  90. self._cycles += 1
  91. def _push_textbuffer(self):
  92. """Push the textbuffer onto the stack as a Text node and clear it."""
  93. if self._textbuffer:
  94. self._stack.append(tokens.Text(text="".join(self._textbuffer)))
  95. self._textbuffer = []
  96. def _pop(self, keep_context=False):
  97. """Pop the current stack/context/textbuffer, returning the stack.
  98. If *keep_context* is ``True``, then we will replace the underlying
  99. stack's context with the current stack's.
  100. """
  101. self._push_textbuffer()
  102. self._depth -= 1
  103. if keep_context:
  104. context = self._context
  105. stack = self._stacks.pop()[0]
  106. self._context = context
  107. return stack
  108. return self._stacks.pop()[0]
  109. def _can_recurse(self):
  110. """Return whether or not our max recursion depth has been exceeded."""
  111. return self._depth < self.MAX_DEPTH and self._cycles < self.MAX_CYCLES
  112. def _fail_route(self):
  113. """Fail the current tokenization route.
  114. Discards the current stack/context/textbuffer and raises
  115. :exc:`.BadRoute`.
  116. """
  117. context = self._context
  118. self._pop()
  119. raise BadRoute(context)
  120. def _emit(self, token):
  121. """Write a token to the end of the current token stack."""
  122. self._push_textbuffer()
  123. self._stack.append(token)
  124. def _emit_first(self, token):
  125. """Write a token to the beginning of the current token stack."""
  126. self._push_textbuffer()
  127. self._stack.insert(0, token)
  128. def _emit_text(self, text):
  129. """Write text to the current textbuffer."""
  130. self._textbuffer.append(text)
  131. def _emit_all(self, tokenlist):
  132. """Write a series of tokens to the current stack at once."""
  133. if tokenlist and isinstance(tokenlist[0], tokens.Text):
  134. self._emit_text(tokenlist.pop(0).text)
  135. self._push_textbuffer()
  136. self._stack.extend(tokenlist)
  137. def _emit_text_then_stack(self, text):
  138. """Pop the current stack, write *text*, and then write the stack."""
  139. stack = self._pop()
  140. self._emit_text(text)
  141. if stack:
  142. self._emit_all(stack)
  143. self._head -= 1
  144. def _read(self, delta=0, wrap=False, strict=False):
  145. """Read the value at a relative point in the wikicode.
  146. The value is read from :attr:`self._head <_head>` plus the value of
  147. *delta* (which can be negative). If *wrap* is ``False``, we will not
  148. allow attempts to read from the end of the string if ``self._head +
  149. delta`` is negative. If *strict* is ``True``, the route will be failed
  150. (with :meth:`_fail_route`) if we try to read from past the end of the
  151. string; otherwise, :attr:`self.END <END>` is returned. If we try to
  152. read from before the start of the string, :attr:`self.START <START>` is
  153. returned.
  154. """
  155. index = self._head + delta
  156. if index < 0 and (not wrap or abs(index) > len(self._text)):
  157. return self.START
  158. try:
  159. return self._text[index]
  160. except IndexError:
  161. if strict:
  162. self._fail_route()
  163. return self.END
  164. def _parse_template(self):
  165. """Parse a template at the head of the wikicode string."""
  166. reset = self._head
  167. try:
  168. template = self._parse(contexts.TEMPLATE_NAME)
  169. except BadRoute:
  170. self._head = reset
  171. raise
  172. self._emit_first(tokens.TemplateOpen())
  173. self._emit_all(template)
  174. self._emit(tokens.TemplateClose())
  175. def _parse_argument(self):
  176. """Parse an argument at the head of the wikicode string."""
  177. reset = self._head
  178. try:
  179. argument = self._parse(contexts.ARGUMENT_NAME)
  180. except BadRoute:
  181. self._head = reset
  182. raise
  183. self._emit_first(tokens.ArgumentOpen())
  184. self._emit_all(argument)
  185. self._emit(tokens.ArgumentClose())
  186. def _parse_template_or_argument(self):
  187. """Parse a template or argument at the head of the wikicode string."""
  188. self._head += 2
  189. braces = 2
  190. while self._read() == "{":
  191. self._head += 1
  192. braces += 1
  193. self._push()
  194. while braces:
  195. if braces == 1:
  196. return self._emit_text_then_stack("{")
  197. if braces == 2:
  198. try:
  199. self._parse_template()
  200. except BadRoute:
  201. return self._emit_text_then_stack("{{")
  202. break
  203. try:
  204. self._parse_argument()
  205. braces -= 3
  206. except BadRoute:
  207. try:
  208. self._parse_template()
  209. braces -= 2
  210. except BadRoute:
  211. return self._emit_text_then_stack("{" * braces)
  212. if braces:
  213. self._head += 1
  214. self._emit_all(self._pop())
  215. if self._context & contexts.FAIL_NEXT:
  216. self._context ^= contexts.FAIL_NEXT
  217. def _handle_template_param(self):
  218. """Handle a template parameter at the head of the string."""
  219. if self._context & contexts.TEMPLATE_NAME:
  220. self._context ^= contexts.TEMPLATE_NAME
  221. elif self._context & contexts.TEMPLATE_PARAM_VALUE:
  222. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  223. else:
  224. self._emit_all(self._pop(keep_context=True))
  225. self._context |= contexts.TEMPLATE_PARAM_KEY
  226. self._emit(tokens.TemplateParamSeparator())
  227. self._push(self._context)
  228. def _handle_template_param_value(self):
  229. """Handle a template parameter's value at the head of the string."""
  230. self._emit_all(self._pop(keep_context=True))
  231. self._context ^= contexts.TEMPLATE_PARAM_KEY
  232. self._context |= contexts.TEMPLATE_PARAM_VALUE
  233. self._emit(tokens.TemplateParamEquals())
  234. def _handle_template_end(self):
  235. """Handle the end of a template at the head of the string."""
  236. if self._context & contexts.TEMPLATE_PARAM_KEY:
  237. self._emit_all(self._pop(keep_context=True))
  238. self._head += 1
  239. return self._pop()
  240. def _handle_argument_separator(self):
  241. """Handle the separator between an argument's name and default."""
  242. self._context ^= contexts.ARGUMENT_NAME
  243. self._context |= contexts.ARGUMENT_DEFAULT
  244. self._emit(tokens.ArgumentSeparator())
  245. def _handle_argument_end(self):
  246. """Handle the end of an argument at the head of the string."""
  247. self._head += 2
  248. return self._pop()
  249. def _parse_wikilink(self):
  250. """Parse an internal wikilink at the head of the wikicode string."""
  251. self._head += 2
  252. reset = self._head - 1
  253. try:
  254. wikilink = self._parse(contexts.WIKILINK_TITLE)
  255. except BadRoute:
  256. self._head = reset
  257. self._emit_text("[[")
  258. else:
  259. self._emit(tokens.WikilinkOpen())
  260. self._emit_all(wikilink)
  261. self._emit(tokens.WikilinkClose())
  262. def _handle_wikilink_separator(self):
  263. """Handle the separator between a wikilink's title and its text."""
  264. self._context ^= contexts.WIKILINK_TITLE
  265. self._context |= contexts.WIKILINK_TEXT
  266. self._emit(tokens.WikilinkSeparator())
  267. def _handle_wikilink_end(self):
  268. """Handle the end of a wikilink at the head of the string."""
  269. self._head += 1
  270. return self._pop()
  271. def _parse_bracketed_uri_scheme(self):
  272. """Parse the URI scheme of a bracket-enclosed external link."""
  273. self._push(contexts.EXT_LINK_URI)
  274. if self._read() == self._read(1) == "/":
  275. self._emit_text("//")
  276. self._head += 2
  277. else:
  278. valid = "abcdefghijklmnopqrstuvwxyz0123456789+.-"
  279. all_valid = lambda: all(char in valid for char in self._read())
  280. scheme = ""
  281. while self._read() is not self.END and all_valid():
  282. scheme += self._read()
  283. self._emit_text(self._read())
  284. self._head += 1
  285. if self._read() != ":":
  286. self._fail_route()
  287. self._emit_text(":")
  288. self._head += 1
  289. slashes = self._read() == self._read(1) == "/"
  290. if slashes:
  291. self._emit_text("//")
  292. self._head += 2
  293. if not is_scheme(scheme, slashes):
  294. self._fail_route()
  295. def _parse_free_uri_scheme(self):
  296. """Parse the URI scheme of a free (no brackets) external link."""
  297. valid = "abcdefghijklmnopqrstuvwxyz0123456789+.-"
  298. scheme = []
  299. try:
  300. # We have to backtrack through the textbuffer looking for our
  301. # scheme since it was just parsed as text:
  302. for chunk in reversed(self._textbuffer):
  303. for char in reversed(chunk):
  304. if char.isspace() or char in self.MARKERS:
  305. raise StopIteration()
  306. if char not in valid:
  307. raise BadRoute()
  308. scheme.append(char)
  309. except StopIteration:
  310. pass
  311. scheme = "".join(reversed(scheme))
  312. slashes = self._read() == self._read(1) == "/"
  313. if not is_scheme(scheme, slashes):
  314. raise BadRoute()
  315. self._push(self._context | contexts.EXT_LINK_URI)
  316. self._emit_text(scheme)
  317. self._emit_text(":")
  318. if slashes:
  319. self._emit_text("//")
  320. self._head += 2
  321. def _handle_free_link_text(self, punct, tail, this):
  322. """Handle text in a free ext link, including trailing punctuation."""
  323. if "(" in this and ")" in punct:
  324. punct = punct[:-1] # ')' is not longer valid punctuation
  325. if this.endswith(punct):
  326. for i in range(len(this) - 1, 0, -1):
  327. if this[i - 1] not in punct:
  328. break
  329. else:
  330. i = 0
  331. stripped = this[:i]
  332. if stripped and tail:
  333. self._emit_text(tail)
  334. tail = ""
  335. tail += this[i:]
  336. this = stripped
  337. elif tail:
  338. self._emit_text(tail)
  339. tail = ""
  340. self._emit_text(this)
  341. return punct, tail
  342. def _is_free_link_end(self, this, next):
  343. """Return whether the current head is the end of a free link."""
  344. # Built from _parse()'s end sentinels:
  345. after, ctx = self._read(2), self._context
  346. equal_sign_contexts = contexts.TEMPLATE_PARAM_KEY | contexts.HEADING
  347. return (this in (self.END, "\n", "[", "]", "<", ">") or
  348. this == next == "'" or
  349. (this == "|" and ctx & contexts.TEMPLATE) or
  350. (this == "=" and ctx & equal_sign_contexts) or
  351. (this == next == "}" and ctx & contexts.TEMPLATE) or
  352. (this == next == after == "}" and ctx & contexts.ARGUMENT))
  353. def _really_parse_external_link(self, brackets):
  354. """Really parse an external link."""
  355. if brackets:
  356. self._parse_bracketed_uri_scheme()
  357. invalid = ("\n", " ", "]")
  358. else:
  359. self._parse_free_uri_scheme()
  360. invalid = ("\n", " ", "[", "]")
  361. punct = tuple(",;\.:!?)")
  362. if self._read() is self.END or self._read()[0] in invalid:
  363. self._fail_route()
  364. tail = ""
  365. while True:
  366. this, next = self._read(), self._read(1)
  367. if this == "&":
  368. if tail:
  369. self._emit_text(tail)
  370. tail = ""
  371. self._parse_entity()
  372. elif (this == "<" and next == "!" and self._read(2) ==
  373. self._read(3) == "-"):
  374. if tail:
  375. self._emit_text(tail)
  376. tail = ""
  377. self._parse_comment()
  378. elif not brackets and self._is_free_link_end(this, next):
  379. return self._pop(), tail, -1
  380. elif this is self.END or this == "\n":
  381. self._fail_route()
  382. elif this == next == "{" and self._can_recurse():
  383. if tail:
  384. self._emit_text(tail)
  385. tail = ""
  386. self._parse_template_or_argument()
  387. elif this == "]":
  388. return self._pop(), tail, 0
  389. elif " " in this:
  390. before, after = this.split(" ", 1)
  391. if brackets:
  392. self._emit_text(before)
  393. self._emit(tokens.ExternalLinkSeparator())
  394. if after:
  395. self._emit_text(after)
  396. self._context ^= contexts.EXT_LINK_URI
  397. self._context |= contexts.EXT_LINK_TITLE
  398. self._head += 1
  399. return self._parse(push=False), None, 0
  400. punct, tail = self._handle_free_link_text(punct, tail, before)
  401. return self._pop(), tail + " " + after, 0
  402. elif not brackets:
  403. punct, tail = self._handle_free_link_text(punct, tail, this)
  404. else:
  405. self._emit_text(this)
  406. self._head += 1
  407. def _remove_uri_scheme_from_textbuffer(self, scheme):
  408. """Remove the URI scheme of a new external link from the textbuffer."""
  409. length = len(scheme)
  410. while length:
  411. if length < len(self._textbuffer[-1]):
  412. self._textbuffer[-1] = self._textbuffer[-1][:-length]
  413. break
  414. length -= len(self._textbuffer[-1])
  415. self._textbuffer.pop()
  416. def _parse_external_link(self, brackets):
  417. """Parse an external link at the head of the wikicode string."""
  418. reset = self._head
  419. self._head += 1
  420. try:
  421. bad_context = self._context & contexts.NO_EXT_LINKS
  422. if bad_context or not self._can_recurse():
  423. raise BadRoute()
  424. link, extra, delta = self._really_parse_external_link(brackets)
  425. except BadRoute:
  426. self._head = reset
  427. if not brackets and self._context & contexts.DL_TERM:
  428. self._handle_dl_term()
  429. else:
  430. self._emit_text(self._read())
  431. else:
  432. if not brackets:
  433. scheme = link[0].text.split(":", 1)[0]
  434. self._remove_uri_scheme_from_textbuffer(scheme)
  435. self._emit(tokens.ExternalLinkOpen(brackets=brackets))
  436. self._emit_all(link)
  437. self._emit(tokens.ExternalLinkClose())
  438. self._head += delta
  439. if extra:
  440. self._emit_text(extra)
  441. def _parse_heading(self):
  442. """Parse a section heading at the head of the wikicode string."""
  443. self._global |= contexts.GL_HEADING
  444. reset = self._head
  445. self._head += 1
  446. best = 1
  447. while self._read() == "=":
  448. best += 1
  449. self._head += 1
  450. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  451. try:
  452. title, level = self._parse(context)
  453. except BadRoute:
  454. self._head = reset + best - 1
  455. self._emit_text("=" * best)
  456. else:
  457. self._emit(tokens.HeadingStart(level=level))
  458. if level < best:
  459. self._emit_text("=" * (best - level))
  460. self._emit_all(title)
  461. self._emit(tokens.HeadingEnd())
  462. finally:
  463. self._global ^= contexts.GL_HEADING
  464. def _handle_heading_end(self):
  465. """Handle the end of a section heading at the head of the string."""
  466. reset = self._head
  467. self._head += 1
  468. best = 1
  469. while self._read() == "=":
  470. best += 1
  471. self._head += 1
  472. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  473. level = min(current, min(best, 6))
  474. try: # Try to check for a heading closure after this one
  475. after, after_level = self._parse(self._context)
  476. except BadRoute:
  477. if level < best:
  478. self._emit_text("=" * (best - level))
  479. self._head = reset + best - 1
  480. return self._pop(), level
  481. else: # Found another closure
  482. self._emit_text("=" * best)
  483. self._emit_all(after)
  484. return self._pop(), after_level
  485. def _really_parse_entity(self):
  486. """Actually parse an HTML entity and ensure that it is valid."""
  487. self._emit(tokens.HTMLEntityStart())
  488. self._head += 1
  489. this = self._read(strict=True)
  490. if this == "#":
  491. numeric = True
  492. self._emit(tokens.HTMLEntityNumeric())
  493. self._head += 1
  494. this = self._read(strict=True)
  495. if this[0].lower() == "x":
  496. hexadecimal = True
  497. self._emit(tokens.HTMLEntityHex(char=this[0]))
  498. this = this[1:]
  499. if not this:
  500. self._fail_route()
  501. else:
  502. hexadecimal = False
  503. else:
  504. numeric = hexadecimal = False
  505. valid = "0123456789abcdefABCDEF" if hexadecimal else "0123456789"
  506. if not numeric and not hexadecimal:
  507. valid += "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  508. if not all([char in valid for char in this]):
  509. self._fail_route()
  510. self._head += 1
  511. if self._read() != ";":
  512. self._fail_route()
  513. if numeric:
  514. test = int(this, 16) if hexadecimal else int(this)
  515. if test < 1 or test > 0x10FFFF:
  516. self._fail_route()
  517. else:
  518. if this not in htmlentities.entitydefs:
  519. self._fail_route()
  520. self._emit(tokens.Text(text=this))
  521. self._emit(tokens.HTMLEntityEnd())
  522. def _parse_entity(self):
  523. """Parse an HTML entity at the head of the wikicode string."""
  524. reset = self._head
  525. self._push()
  526. try:
  527. self._really_parse_entity()
  528. except BadRoute:
  529. self._head = reset
  530. self._emit_text(self._read())
  531. else:
  532. self._emit_all(self._pop())
  533. def _parse_comment(self):
  534. """Parse an HTML comment at the head of the wikicode string."""
  535. self._head += 4
  536. reset = self._head - 1
  537. self._push()
  538. while True:
  539. this = self._read()
  540. if this == self.END:
  541. self._pop()
  542. self._head = reset
  543. self._emit_text("<!--")
  544. return
  545. if this == self._read(1) == "-" and self._read(2) == ">":
  546. self._emit_first(tokens.CommentStart())
  547. self._emit(tokens.CommentEnd())
  548. self._emit_all(self._pop())
  549. self._head += 2
  550. if self._context & contexts.FAIL_NEXT:
  551. # _verify_safe() sets this flag while parsing a template
  552. # name when it encounters what might be a comment -- we
  553. # must unset it to let _verify_safe() know it was correct:
  554. self._context ^= contexts.FAIL_NEXT
  555. return
  556. self._emit_text(this)
  557. self._head += 1
  558. def _push_tag_buffer(self, data):
  559. """Write a pending tag attribute from *data* to the stack."""
  560. if data.context & data.CX_QUOTED:
  561. self._emit_first(tokens.TagAttrQuote(char=data.quoter))
  562. self._emit_all(self._pop())
  563. buf = data.padding_buffer
  564. self._emit_first(tokens.TagAttrStart(pad_first=buf["first"],
  565. pad_before_eq=buf["before_eq"], pad_after_eq=buf["after_eq"]))
  566. self._emit_all(self._pop())
  567. for key in data.padding_buffer:
  568. data.padding_buffer[key] = ""
  569. def _handle_tag_space(self, data, text):
  570. """Handle whitespace (*text*) inside of an HTML open tag."""
  571. ctx = data.context
  572. end_of_value = ctx & data.CX_ATTR_VALUE and not ctx & (data.CX_QUOTED | data.CX_NOTE_QUOTE)
  573. if end_of_value or (ctx & data.CX_QUOTED and ctx & data.CX_NOTE_SPACE):
  574. self._push_tag_buffer(data)
  575. data.context = data.CX_ATTR_READY
  576. elif ctx & data.CX_NOTE_SPACE:
  577. data.context = data.CX_ATTR_READY
  578. elif ctx & data.CX_ATTR_NAME:
  579. data.context |= data.CX_NOTE_EQUALS
  580. data.padding_buffer["before_eq"] += text
  581. if ctx & data.CX_QUOTED and not ctx & data.CX_NOTE_SPACE:
  582. self._emit_text(text)
  583. elif data.context & data.CX_ATTR_READY:
  584. data.padding_buffer["first"] += text
  585. elif data.context & data.CX_ATTR_VALUE:
  586. data.padding_buffer["after_eq"] += text
  587. def _handle_tag_text(self, text):
  588. """Handle regular *text* inside of an HTML open tag."""
  589. next = self._read(1)
  590. if not self._can_recurse() or text not in self.MARKERS:
  591. self._emit_text(text)
  592. elif text == next == "{":
  593. self._parse_template_or_argument()
  594. elif text == next == "[":
  595. self._parse_wikilink()
  596. elif text == "<":
  597. self._parse_tag()
  598. else:
  599. self._emit_text(text)
  600. def _handle_tag_data(self, data, text):
  601. """Handle all sorts of *text* data inside of an HTML open tag."""
  602. for chunk in self.tag_splitter.split(text):
  603. if not chunk:
  604. continue
  605. if data.context & data.CX_NAME:
  606. if chunk in self.MARKERS or chunk.isspace():
  607. self._fail_route() # Tags must start with text, not spaces
  608. data.context = data.CX_NOTE_SPACE
  609. elif chunk.isspace():
  610. self._handle_tag_space(data, chunk)
  611. continue
  612. elif data.context & data.CX_NOTE_SPACE:
  613. if data.context & data.CX_QUOTED:
  614. data.context = data.CX_ATTR_VALUE
  615. self._pop()
  616. self._head = data.reset - 1 # Will be auto-incremented
  617. return # Break early
  618. self._fail_route()
  619. elif data.context & data.CX_ATTR_READY:
  620. data.context = data.CX_ATTR_NAME
  621. self._push(contexts.TAG_ATTR)
  622. elif data.context & data.CX_ATTR_NAME:
  623. if chunk == "=":
  624. data.context = data.CX_ATTR_VALUE | data.CX_NOTE_QUOTE
  625. self._emit(tokens.TagAttrEquals())
  626. continue
  627. if data.context & data.CX_NOTE_EQUALS:
  628. self._push_tag_buffer(data)
  629. data.context = data.CX_ATTR_NAME
  630. self._push(contexts.TAG_ATTR)
  631. else: # data.context & data.CX_ATTR_VALUE assured
  632. escaped = self._read(-1) == "\\" and self._read(-2) != "\\"
  633. if data.context & data.CX_NOTE_QUOTE:
  634. data.context ^= data.CX_NOTE_QUOTE
  635. if chunk in "'\"" and not escaped:
  636. data.context |= data.CX_QUOTED
  637. data.quoter = chunk
  638. data.reset = self._head
  639. self._push(self._context)
  640. continue
  641. elif data.context & data.CX_QUOTED:
  642. if chunk == data.quoter and not escaped:
  643. data.context |= data.CX_NOTE_SPACE
  644. continue
  645. self._handle_tag_text(chunk)
  646. def _handle_tag_close_open(self, data, token):
  647. """Handle the closing of a open tag (``<foo>``)."""
  648. if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
  649. self._push_tag_buffer(data)
  650. self._emit(token(padding=data.padding_buffer["first"]))
  651. self._head += 1
  652. def _handle_tag_open_close(self):
  653. """Handle the opening of a closing tag (``</foo>``)."""
  654. self._emit(tokens.TagOpenClose())
  655. self._push(contexts.TAG_CLOSE)
  656. self._head += 1
  657. def _handle_tag_close_close(self):
  658. """Handle the ending of a closing tag (``</foo>``)."""
  659. strip = lambda tok: tok.text.rstrip().lower()
  660. closing = self._pop()
  661. if len(closing) != 1 or (not isinstance(closing[0], tokens.Text) or
  662. strip(closing[0]) != strip(self._stack[1])):
  663. self._fail_route()
  664. self._emit_all(closing)
  665. self._emit(tokens.TagCloseClose())
  666. return self._pop()
  667. def _handle_blacklisted_tag(self):
  668. """Handle the body of an HTML tag that is parser-blacklisted."""
  669. strip = lambda text: text.rstrip().lower()
  670. while True:
  671. this, next = self._read(), self._read(1)
  672. if this is self.END:
  673. self._fail_route()
  674. elif this == "<" and next == "/":
  675. self._head += 3
  676. if self._read() != ">" or (strip(self._read(-1)) !=
  677. strip(self._stack[1].text)):
  678. self._head -= 1
  679. self._emit_text("</")
  680. continue
  681. self._emit(tokens.TagOpenClose())
  682. self._emit_text(self._read(-1))
  683. self._emit(tokens.TagCloseClose())
  684. return self._pop()
  685. elif this == "&":
  686. self._parse_entity()
  687. else:
  688. self._emit_text(this)
  689. self._head += 1
  690. def _handle_single_only_tag_end(self):
  691. """Handle the end of an implicitly closing single-only HTML tag."""
  692. padding = self._stack.pop().padding
  693. self._emit(tokens.TagCloseSelfclose(padding=padding, implicit=True))
  694. self._head -= 1 # Offset displacement done by _handle_tag_close_open
  695. return self._pop()
  696. def _handle_single_tag_end(self):
  697. """Handle the stream end when inside a single-supporting HTML tag."""
  698. stack = self._stack
  699. # We need to find the index of the TagCloseOpen token corresponding to
  700. # the TagOpenOpen token located at index 0:
  701. depth = 1
  702. for index, token in enumerate(stack[2:], 2):
  703. if isinstance(token, tokens.TagOpenOpen):
  704. depth += 1
  705. elif isinstance(token, tokens.TagCloseOpen):
  706. depth -= 1
  707. if depth == 0:
  708. break
  709. else: # pragma: no cover (untestable/exceptional case)
  710. raise ParserError("_handle_single_tag_end() missed a TagCloseOpen")
  711. padding = stack[index].padding
  712. stack[index] = tokens.TagCloseSelfclose(padding=padding, implicit=True)
  713. return self._pop()
  714. def _really_parse_tag(self):
  715. """Actually parse an HTML tag, starting with the open (``<foo>``)."""
  716. data = _TagOpenData()
  717. self._push(contexts.TAG_OPEN)
  718. self._emit(tokens.TagOpenOpen())
  719. while True:
  720. this, next = self._read(), self._read(1)
  721. can_exit = (not data.context & (data.CX_QUOTED | data.CX_NAME) or
  722. data.context & data.CX_NOTE_SPACE)
  723. if this is self.END:
  724. if self._context & contexts.TAG_ATTR:
  725. if data.context & data.CX_QUOTED:
  726. # Unclosed attribute quote: reset, don't die
  727. data.context = data.CX_ATTR_VALUE
  728. self._pop()
  729. self._head = data.reset
  730. continue
  731. self._pop()
  732. self._fail_route()
  733. elif this == ">" and can_exit:
  734. self._handle_tag_close_open(data, tokens.TagCloseOpen)
  735. self._context = contexts.TAG_BODY
  736. if is_single_only(self._stack[1].text):
  737. return self._handle_single_only_tag_end()
  738. if is_parsable(self._stack[1].text):
  739. return self._parse(push=False)
  740. return self._handle_blacklisted_tag()
  741. elif this == "/" and next == ">" and can_exit:
  742. self._handle_tag_close_open(data, tokens.TagCloseSelfclose)
  743. return self._pop()
  744. else:
  745. self._handle_tag_data(data, this)
  746. self._head += 1
  747. def _handle_invalid_tag_start(self):
  748. """Handle the (possible) start of an implicitly closing single tag."""
  749. reset = self._head + 1
  750. self._head += 2
  751. try:
  752. if not is_single_only(self.tag_splitter.split(self._read())[0]):
  753. raise BadRoute()
  754. tag = self._really_parse_tag()
  755. except BadRoute:
  756. self._head = reset
  757. self._emit_text("</")
  758. else:
  759. tag[0].invalid = True # Set flag of TagOpenOpen
  760. self._emit_all(tag)
  761. def _parse_tag(self):
  762. """Parse an HTML tag at the head of the wikicode string."""
  763. reset = self._head
  764. self._head += 1
  765. try:
  766. tag = self._really_parse_tag()
  767. except BadRoute:
  768. self._head = reset
  769. self._emit_text("<")
  770. else:
  771. self._emit_all(tag)
  772. def _emit_style_tag(self, tag, markup, body):
  773. """Write the body of a tag and the tokens that should surround it."""
  774. self._emit(tokens.TagOpenOpen(wiki_markup=markup))
  775. self._emit_text(tag)
  776. self._emit(tokens.TagCloseOpen())
  777. self._emit_all(body)
  778. self._emit(tokens.TagOpenClose())
  779. self._emit_text(tag)
  780. self._emit(tokens.TagCloseClose())
  781. def _parse_italics(self):
  782. """Parse wiki-style italics."""
  783. reset = self._head
  784. try:
  785. stack = self._parse(contexts.STYLE_ITALICS)
  786. except BadRoute as route:
  787. self._head = reset
  788. if route.context & contexts.STYLE_PASS_AGAIN:
  789. new_ctx = contexts.STYLE_ITALICS | contexts.STYLE_SECOND_PASS
  790. stack = self._parse(new_ctx)
  791. else:
  792. return self._emit_text("''")
  793. self._emit_style_tag("i", "''", stack)
  794. def _parse_bold(self):
  795. """Parse wiki-style bold."""
  796. reset = self._head
  797. try:
  798. stack = self._parse(contexts.STYLE_BOLD)
  799. except BadRoute:
  800. self._head = reset
  801. if self._context & contexts.STYLE_SECOND_PASS:
  802. self._emit_text("'")
  803. return True
  804. elif self._context & contexts.STYLE_ITALICS:
  805. self._context |= contexts.STYLE_PASS_AGAIN
  806. self._emit_text("'''")
  807. else:
  808. self._emit_text("'")
  809. self._parse_italics()
  810. else:
  811. self._emit_style_tag("b", "'''", stack)
  812. def _parse_italics_and_bold(self):
  813. """Parse wiki-style italics and bold together (i.e., five ticks)."""
  814. reset = self._head
  815. try:
  816. stack = self._parse(contexts.STYLE_BOLD)
  817. except BadRoute:
  818. self._head = reset
  819. try:
  820. stack = self._parse(contexts.STYLE_ITALICS)
  821. except BadRoute:
  822. self._head = reset
  823. self._emit_text("'''''")
  824. else:
  825. reset = self._head
  826. try:
  827. stack2 = self._parse(contexts.STYLE_BOLD)
  828. except BadRoute:
  829. self._head = reset
  830. self._emit_text("'''")
  831. self._emit_style_tag("i", "''", stack)
  832. else:
  833. self._push()
  834. self._emit_style_tag("i", "''", stack)
  835. self._emit_all(stack2)
  836. self._emit_style_tag("b", "'''", self._pop())
  837. else:
  838. reset = self._head
  839. try:
  840. stack2 = self._parse(contexts.STYLE_ITALICS)
  841. except BadRoute:
  842. self._head = reset
  843. self._emit_text("''")
  844. self._emit_style_tag("b", "'''", stack)
  845. else:
  846. self._push()
  847. self._emit_style_tag("b", "'''", stack)
  848. self._emit_all(stack2)
  849. self._emit_style_tag("i", "''", self._pop())
  850. def _parse_style(self):
  851. """Parse wiki-style formatting (``''``/``'''`` for italics/bold)."""
  852. self._head += 2
  853. ticks = 2
  854. while self._read() == "'":
  855. self._head += 1
  856. ticks += 1
  857. italics = self._context & contexts.STYLE_ITALICS
  858. bold = self._context & contexts.STYLE_BOLD
  859. if ticks > 5:
  860. self._emit_text("'" * (ticks - 5))
  861. ticks = 5
  862. elif ticks == 4:
  863. self._emit_text("'")
  864. ticks = 3
  865. if (italics and ticks in (2, 5)) or (bold and ticks in (3, 5)):
  866. if ticks == 5:
  867. self._head -= 3 if italics else 2
  868. return self._pop()
  869. elif not self._can_recurse():
  870. if ticks == 3:
  871. if self._context & contexts.STYLE_SECOND_PASS:
  872. self._emit_text("'")
  873. return self._pop()
  874. if self._context & contexts.STYLE_ITALICS:
  875. self._context |= contexts.STYLE_PASS_AGAIN
  876. self._emit_text("'" * ticks)
  877. elif ticks == 2:
  878. self._parse_italics()
  879. elif ticks == 3:
  880. if self._parse_bold():
  881. return self._pop()
  882. else: # ticks == 5
  883. self._parse_italics_and_bold()
  884. self._head -= 1
  885. def _handle_list_marker(self):
  886. """Handle a list marker at the head (``#``, ``*``, ``;``, ``:``)."""
  887. markup = self._read()
  888. if markup == ";":
  889. self._context |= contexts.DL_TERM
  890. self._emit(tokens.TagOpenOpen(wiki_markup=markup))
  891. self._emit_text(get_html_tag(markup))
  892. self._emit(tokens.TagCloseSelfclose())
  893. def _handle_list(self):
  894. """Handle a wiki-style list (``#``, ``*``, ``;``, ``:``)."""
  895. self._handle_list_marker()
  896. while self._read(1) in ("#", "*", ";", ":"):
  897. self._head += 1
  898. self._handle_list_marker()
  899. def _handle_hr(self):
  900. """Handle a wiki-style horizontal rule (``----``) in the string."""
  901. length = 4
  902. self._head += 3
  903. while self._read(1) == "-":
  904. length += 1
  905. self._head += 1
  906. self._emit(tokens.TagOpenOpen(wiki_markup="-" * length))
  907. self._emit_text("hr")
  908. self._emit(tokens.TagCloseSelfclose())
  909. def _handle_dl_term(self):
  910. """Handle the term in a description list (``foo`` in ``;foo:bar``)."""
  911. self._context ^= contexts.DL_TERM
  912. if self._read() == ":":
  913. self._handle_list_marker()
  914. else:
  915. self._emit_text("\n")
  916. def _emit_table_tag(self, open_open_markup, tag, style, padding,
  917. close_open_markup, contents, open_close_markup):
  918. """Emit a table tag."""
  919. self._emit(tokens.TagOpenOpen(wiki_markup=open_open_markup))
  920. self._emit_text(tag)
  921. if style:
  922. self._emit_all(style)
  923. if close_open_markup:
  924. self._emit(tokens.TagCloseOpen(wiki_markup=close_open_markup,
  925. padding=padding))
  926. else:
  927. self._emit(tokens.TagCloseOpen(padding=padding))
  928. if contents:
  929. self._emit_all(contents)
  930. self._emit(tokens.TagOpenClose(wiki_markup=open_close_markup))
  931. self._emit_text(tag)
  932. self._emit(tokens.TagCloseClose())
  933. def _handle_table_style(self, end_token):
  934. """Handle style attributes for a table until ``end_token``."""
  935. data = _TagOpenData()
  936. data.context = _TagOpenData.CX_ATTR_READY
  937. while True:
  938. this = self._read()
  939. can_exit = (not data.context & data.CX_QUOTED or
  940. data.context & data.CX_NOTE_SPACE)
  941. if this == end_token and can_exit:
  942. if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
  943. self._push_tag_buffer(data)
  944. if this.isspace():
  945. data.padding_buffer["first"] += this
  946. return data.padding_buffer["first"]
  947. elif this is self.END or this == end_token:
  948. if self._context & contexts.TAG_ATTR:
  949. if data.context & data.CX_QUOTED:
  950. # Unclosed attribute quote: reset, don't die
  951. data.context = data.CX_ATTR_VALUE
  952. self._pop()
  953. self._head = data.reset
  954. continue
  955. self._pop()
  956. self._fail_route()
  957. else:
  958. self._handle_tag_data(data, this)
  959. self._head += 1
  960. def _parse_table(self):
  961. """Parse a wikicode table by starting with the first line."""
  962. reset = self._head + 1
  963. self._head += 2
  964. self._push(contexts.TABLE_OPEN)
  965. try:
  966. padding = self._handle_table_style("\n")
  967. except BadRoute:
  968. self._head = reset
  969. self._emit_text("{|")
  970. return
  971. style = self._pop()
  972. self._head += 1
  973. try:
  974. table = self._parse(contexts.TABLE_OPEN)
  975. except BadRoute:
  976. self._head = reset
  977. self._emit_text("{|")
  978. return
  979. self._emit_table_tag("{|", "table", style, padding, None, table, "|}")
  980. # Offset displacement done by _parse():
  981. self._head -= 1
  982. def _handle_table_row(self):
  983. """Parse as style until end of the line, then continue."""
  984. self._head += 2
  985. if not self._can_recurse():
  986. self._emit_text("|-")
  987. self._head -= 1
  988. return
  989. self._push(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
  990. try:
  991. padding = self._handle_table_style("\n")
  992. except BadRoute:
  993. self._pop()
  994. raise
  995. style = self._pop()
  996. # Don't parse the style separator:
  997. self._head += 1
  998. row = self._parse(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
  999. self._emit_table_tag("|-", "tr", style, padding, None, row, "")
  1000. # Offset displacement done by parse():
  1001. self._head -= 1
  1002. def _handle_table_cell(self, markup, tag, line_context):
  1003. """Parse as normal syntax unless we hit a style marker, then parse
  1004. style as HTML attributes and the remainder as normal syntax."""
  1005. old_context = self._context
  1006. padding, style = "", None
  1007. self._head += len(markup)
  1008. reset = self._head
  1009. if not self._can_recurse():
  1010. self._emit_text(markup)
  1011. self._head -= 1
  1012. return
  1013. cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1014. line_context | contexts.TABLE_CELL_STYLE)
  1015. cell_context = self._context
  1016. self._context = old_context
  1017. reset_for_style = cell_context & contexts.TABLE_CELL_STYLE
  1018. if reset_for_style:
  1019. self._head = reset
  1020. self._push(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1021. line_context)
  1022. padding = self._handle_table_style("|")
  1023. style = self._pop()
  1024. # Don't parse the style separator:
  1025. self._head += 1
  1026. cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1027. line_context)
  1028. cell_context = self._context
  1029. self._context = old_context
  1030. close_open_markup = "|" if reset_for_style else None
  1031. self._emit_table_tag(markup, tag, style, padding, close_open_markup,
  1032. cell, "")
  1033. # Keep header/cell line contexts:
  1034. self._context |= cell_context & (contexts.TABLE_TH_LINE |
  1035. contexts.TABLE_TD_LINE)
  1036. # Offset displacement done by parse():
  1037. self._head -= 1
  1038. def _handle_table_cell_end(self, reset_for_style=False):
  1039. """Returns the current context, with the TABLE_CELL_STYLE flag set if
  1040. it is necessary to reset and parse style attributes."""
  1041. if reset_for_style:
  1042. self._context |= contexts.TABLE_CELL_STYLE
  1043. else:
  1044. self._context &= ~contexts.TABLE_CELL_STYLE
  1045. return self._pop(keep_context=True)
  1046. def _handle_table_row_end(self):
  1047. """Return the stack in order to handle the table row end."""
  1048. return self._pop()
  1049. def _handle_table_end(self):
  1050. """Return the stack in order to handle the table end."""
  1051. self._head += 2
  1052. return self._pop()
  1053. def _handle_end(self):
  1054. """Handle the end of the stream of wikitext."""
  1055. if self._context & contexts.FAIL:
  1056. if self._context & contexts.TAG_BODY:
  1057. if is_single(self._stack[1].text):
  1058. return self._handle_single_tag_end()
  1059. if self._context & contexts.TABLE_CELL_OPEN:
  1060. self._pop()
  1061. if self._context & contexts.DOUBLE:
  1062. self._pop()
  1063. self._fail_route()
  1064. return self._pop()
  1065. def _verify_safe(self, this):
  1066. """Make sure we are not trying to write an invalid character."""
  1067. context = self._context
  1068. if context & contexts.FAIL_NEXT:
  1069. return False
  1070. if context & contexts.WIKILINK_TITLE:
  1071. if this == "]" or this == "{":
  1072. self._context |= contexts.FAIL_NEXT
  1073. elif this == "\n" or this == "[" or this == "}":
  1074. return False
  1075. return True
  1076. elif context & contexts.EXT_LINK_TITLE:
  1077. return this != "\n"
  1078. elif context & contexts.TEMPLATE_NAME:
  1079. if this == "{" or this == "}" or this == "[":
  1080. self._context |= contexts.FAIL_NEXT
  1081. return True
  1082. if this == "]":
  1083. return False
  1084. if this == "|":
  1085. return True
  1086. if context & contexts.HAS_TEXT:
  1087. if context & contexts.FAIL_ON_TEXT:
  1088. if this is self.END or not this.isspace():
  1089. if this == "<" and self._read(1) == "!":
  1090. self._context |= contexts.FAIL_NEXT
  1091. return True
  1092. return False
  1093. else:
  1094. if this == "\n":
  1095. self._context |= contexts.FAIL_ON_TEXT
  1096. elif this is self.END or not this.isspace():
  1097. self._context |= contexts.HAS_TEXT
  1098. return True
  1099. elif context & contexts.TAG_CLOSE:
  1100. return this != "<"
  1101. else:
  1102. if context & contexts.FAIL_ON_EQUALS:
  1103. if this == "=":
  1104. return False
  1105. elif context & contexts.FAIL_ON_LBRACE:
  1106. if this == "{" or (self._read(-1) == self._read(-2) == "{"):
  1107. if context & contexts.TEMPLATE:
  1108. self._context |= contexts.FAIL_ON_EQUALS
  1109. else:
  1110. self._context |= contexts.FAIL_NEXT
  1111. return True
  1112. self._context ^= contexts.FAIL_ON_LBRACE
  1113. elif context & contexts.FAIL_ON_RBRACE:
  1114. if this == "}":
  1115. self._context |= contexts.FAIL_NEXT
  1116. return True
  1117. self._context ^= contexts.FAIL_ON_RBRACE
  1118. elif this == "{":
  1119. self._context |= contexts.FAIL_ON_LBRACE
  1120. elif this == "}":
  1121. self._context |= contexts.FAIL_ON_RBRACE
  1122. return True
  1123. def _parse(self, context=0, push=True):
  1124. """Parse the wikicode string, using *context* for when to stop."""
  1125. if push:
  1126. self._push(context)
  1127. while True:
  1128. this = self._read()
  1129. if self._context & contexts.UNSAFE:
  1130. if not self._verify_safe(this):
  1131. if self._context & contexts.DOUBLE:
  1132. self._pop()
  1133. self._fail_route()
  1134. if this not in self.MARKERS:
  1135. self._emit_text(this)
  1136. self._head += 1
  1137. continue
  1138. if this is self.END:
  1139. return self._handle_end()
  1140. next = self._read(1)
  1141. if this == next == "{":
  1142. if self._can_recurse():
  1143. self._parse_template_or_argument()
  1144. else:
  1145. self._emit_text("{")
  1146. elif this == "|" and self._context & contexts.TEMPLATE:
  1147. self._handle_template_param()
  1148. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  1149. self._handle_template_param_value()
  1150. elif this == next == "}" and self._context & contexts.TEMPLATE:
  1151. return self._handle_template_end()
  1152. elif this == "|" and self._context & contexts.ARGUMENT_NAME:
  1153. self._handle_argument_separator()
  1154. elif this == next == "}" and self._context & contexts.ARGUMENT:
  1155. if self._read(2) == "}":
  1156. return self._handle_argument_end()
  1157. else:
  1158. self._emit_text("}")
  1159. elif this == next == "[" and self._can_recurse():
  1160. if not self._context & contexts.NO_WIKILINKS:
  1161. self._parse_wikilink()
  1162. else:
  1163. self._emit_text("[")
  1164. elif this == "|" and self._context & contexts.WIKILINK_TITLE:
  1165. self._handle_wikilink_separator()
  1166. elif this == next == "]" and self._context & contexts.WIKILINK:
  1167. return self._handle_wikilink_end()
  1168. elif this == "[":
  1169. self._parse_external_link(True)
  1170. elif this == ":" and self._read(-1) not in self.MARKERS:
  1171. self._parse_external_link(False)
  1172. elif this == "]" and self._context & contexts.EXT_LINK_TITLE:
  1173. return self._pop()
  1174. elif this == "=" and not self._global & contexts.GL_HEADING:
  1175. if self._read(-1) in ("\n", self.START):
  1176. self._parse_heading()
  1177. else:
  1178. self._emit_text("=")
  1179. elif this == "=" and self._context & contexts.HEADING:
  1180. return self._handle_heading_end()
  1181. elif this == "\n" and self._context & contexts.HEADING:
  1182. self._fail_route()
  1183. elif this == "&":
  1184. self._parse_entity()
  1185. elif this == "<" and next == "!":
  1186. if self._read(2) == self._read(3) == "-":
  1187. self._parse_comment()
  1188. else:
  1189. self._emit_text(this)
  1190. elif this == "<" and next == "/" and self._read(2) is not self.END:
  1191. if self._context & contexts.TAG_BODY:
  1192. self._handle_tag_open_close()
  1193. else:
  1194. self._handle_invalid_tag_start()
  1195. elif this == "<" and not self._context & contexts.TAG_CLOSE:
  1196. if self._can_recurse():
  1197. self._parse_tag()
  1198. else:
  1199. self._emit_text("<")
  1200. elif this == ">" and self._context & contexts.TAG_CLOSE:
  1201. return self._handle_tag_close_close()
  1202. elif this == next == "'" and not self._skip_style_tags:
  1203. result = self._parse_style()
  1204. if result is not None:
  1205. return result
  1206. elif self._read(-1) in ("\n", self.START) and this in ("#", "*", ";", ":"):
  1207. self._handle_list()
  1208. elif self._read(-1) in ("\n", self.START) and this == next == self._read(2) == self._read(3) == "-":
  1209. self._handle_hr()
  1210. elif this in ("\n", ":") and self._context & contexts.DL_TERM:
  1211. self._handle_dl_term()
  1212. if this == "\n":
  1213. # Kill potential table contexts
  1214. self._context &= ~contexts.TABLE_CELL_LINE_CONTEXTS
  1215. # Start of table parsing
  1216. elif this == "{" and next == "|" and (self._read(-1) in ("\n", self.START) or
  1217. (self._read(-2) in ("\n", self.START) and self._read(-1).isspace())):
  1218. if self._can_recurse():
  1219. self._parse_table()
  1220. else:
  1221. self._emit_text("{|")
  1222. elif self._context & contexts.TABLE_OPEN:
  1223. if this == next == "|" and self._context & contexts.TABLE_TD_LINE:
  1224. if self._context & contexts.TABLE_CELL_OPEN:
  1225. return self._handle_table_cell_end()
  1226. self._handle_table_cell("||", "td", contexts.TABLE_TD_LINE)
  1227. elif this == next == "|" and self._context & contexts.TABLE_TH_LINE:
  1228. if self._context & contexts.TABLE_CELL_OPEN:
  1229. return self._handle_table_cell_end()
  1230. self._handle_table_cell("||", "th", contexts.TABLE_TH_LINE)
  1231. elif this == next == "!" and self._context & contexts.TABLE_TH_LINE:
  1232. if self._context & contexts.TABLE_CELL_OPEN:
  1233. return self._handle_table_cell_end()
  1234. self._handle_table_cell("!!", "th", contexts.TABLE_TH_LINE)
  1235. elif this == "|" and self._context & contexts.TABLE_CELL_STYLE:
  1236. return self._handle_table_cell_end(reset_for_style=True)
  1237. # on newline, clear out cell line contexts
  1238. elif this == "\n" and self._context & contexts.TABLE_CELL_LINE_CONTEXTS:
  1239. self._context &= ~contexts.TABLE_CELL_LINE_CONTEXTS
  1240. self._emit_text(this)
  1241. elif (self._read(-1) in ("\n", self.START) or
  1242. (self._read(-2) in ("\n", self.START) and self._read(-1).isspace())):
  1243. if this == "|" and next == "}":
  1244. if self._context & contexts.TABLE_CELL_OPEN:
  1245. return self._handle_table_cell_end()
  1246. if self._context & contexts.TABLE_ROW_OPEN:
  1247. return self._handle_table_row_end()
  1248. return self._handle_table_end()
  1249. elif this == "|" and next == "-":
  1250. if self._context & contexts.TABLE_CELL_OPEN:
  1251. return self._handle_table_cell_end()
  1252. if self._context & contexts.TABLE_ROW_OPEN:
  1253. return self._handle_table_row_end()
  1254. self._handle_table_row()
  1255. elif this == "|":
  1256. if self._context & contexts.TABLE_CELL_OPEN:
  1257. return self._handle_table_cell_end()
  1258. self._handle_table_cell("|", "td", contexts.TABLE_TD_LINE)
  1259. elif this == "!":
  1260. if self._context & contexts.TABLE_CELL_OPEN:
  1261. return self._handle_table_cell_end()
  1262. self._handle_table_cell("!", "th", contexts.TABLE_TH_LINE)
  1263. else:
  1264. self._emit_text(this)
  1265. else:
  1266. self._emit_text(this)
  1267. else:
  1268. self._emit_text(this)
  1269. self._head += 1
  1270. def tokenize(self, text, context=0, skip_style_tags=False):
  1271. """Build a list of tokens from a string of wikicode and return it."""
  1272. self._skip_style_tags = skip_style_tags
  1273. split = self.regex.split(text)
  1274. self._text = [segment for segment in split if segment]
  1275. self._head = self._global = self._depth = self._cycles = 0
  1276. try:
  1277. tokens = self._parse(context)
  1278. except BadRoute: # pragma: no cover (untestable/exceptional case)
  1279. raise ParserError("Python tokenizer exited with BadRoute")
  1280. if self._stacks: # pragma: no cover (untestable/exceptional case)
  1281. err = "Python tokenizer exited with non-empty token stack"
  1282. raise ParserError(err)
  1283. return tokens