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.
 
 
 
 

1438 lines
56 KiB

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