A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

682 řádky
26 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from __future__ import unicode_literals
  23. from math import log
  24. import re
  25. import string
  26. from . import contexts
  27. from . import tokens
  28. from ..nodes.tag import Tag
  29. from ..compat import htmlentities
  30. __all__ = ["Tokenizer"]
  31. class BadRoute(Exception):
  32. """Raised internally when the current tokenization route is invalid."""
  33. pass
  34. class Tokenizer(object):
  35. """Creates a list of tokens from a string of wikicode."""
  36. START = object()
  37. END = object()
  38. MARKERS = ["{", "}", "[", "]", "<", ">", "|", "=", "&", "#", "*", ";", ":",
  39. "/", "-", "!", "\n", END]
  40. regex = re.compile(r"([{}\[\]<>|=&#*;:/\-!\n])", flags=re.IGNORECASE)
  41. def __init__(self):
  42. self._text = None
  43. self._head = 0
  44. self._stacks = []
  45. self._global = 0
  46. @property
  47. def _stack(self):
  48. """The current token stack."""
  49. return self._stacks[-1][0]
  50. @property
  51. def _context(self):
  52. """The current token context."""
  53. return self._stacks[-1][1]
  54. @_context.setter
  55. def _context(self, value):
  56. self._stacks[-1][1] = value
  57. @property
  58. def _textbuffer(self):
  59. """The current textbuffer."""
  60. return self._stacks[-1][2]
  61. @_textbuffer.setter
  62. def _textbuffer(self, value):
  63. self._stacks[-1][2] = value
  64. def _push(self, context=0):
  65. """Add a new token stack, context, and textbuffer to the list."""
  66. self._stacks.append([[], context, []])
  67. def _push_textbuffer(self):
  68. """Push the textbuffer onto the stack as a Text node and clear it."""
  69. if self._textbuffer:
  70. self._stack.append(tokens.Text(text="".join(self._textbuffer)))
  71. self._textbuffer = []
  72. def _pop(self, keep_context=False):
  73. """Pop the current stack/context/textbuffer, returing the stack.
  74. If *keep_context* is ``True``, then we will replace the underlying
  75. stack's context with the current stack's.
  76. """
  77. self._push_textbuffer()
  78. if keep_context:
  79. context = self._context
  80. stack = self._stacks.pop()[0]
  81. self._context = context
  82. return stack
  83. return self._stacks.pop()[0]
  84. def _fail_route(self):
  85. """Fail the current tokenization route.
  86. Discards the current stack/context/textbuffer and raises
  87. :py:exc:`~.BadRoute`.
  88. """
  89. self._pop()
  90. raise BadRoute()
  91. def _write(self, token):
  92. """Write a token to the end of the current token stack."""
  93. self._push_textbuffer()
  94. self._stack.append(token)
  95. def _write_first(self, token):
  96. """Write a token to the beginning of the current token stack."""
  97. self._push_textbuffer()
  98. self._stack.insert(0, token)
  99. def _write_text(self, text):
  100. """Write text to the current textbuffer."""
  101. self._textbuffer.append(text)
  102. def _write_all(self, tokenlist):
  103. """Write a series of tokens to the current stack at once."""
  104. if tokenlist and isinstance(tokenlist[0], tokens.Text):
  105. self._write_text(tokenlist.pop(0).text)
  106. self._push_textbuffer()
  107. self._stack.extend(tokenlist)
  108. def _write_text_then_stack(self, text):
  109. """Pop the current stack, write *text*, and then write the stack."""
  110. stack = self._pop()
  111. self._write_text(text)
  112. if stack:
  113. self._write_all(stack)
  114. self._head -= 1
  115. def _read(self, delta=0, wrap=False, strict=False):
  116. """Read the value at a relative point in the wikicode.
  117. The value is read from :py:attr:`self._head <_head>` plus the value of
  118. *delta* (which can be negative). If *wrap* is ``False``, we will not
  119. allow attempts to read from the end of the string if ``self._head +
  120. delta`` is negative. If *strict* is ``True``, the route will be failed
  121. (with :py:meth:`_fail_route`) if we try to read from past the end of
  122. the string; otherwise, :py:attr:`self.END <END>` is returned. If we try
  123. to read from before the start of the string, :py:attr:`self.START
  124. <START>` is returned.
  125. """
  126. index = self._head + delta
  127. if index < 0 and (not wrap or abs(index) > len(self._text)):
  128. return self.START
  129. try:
  130. return self._text[index]
  131. except IndexError:
  132. if strict:
  133. self._fail_route()
  134. return self.END
  135. def _parse_template_or_argument(self):
  136. """Parse a template or argument at the head of the wikicode string."""
  137. self._head += 2
  138. braces = 2
  139. while self._read() == "{":
  140. self._head += 1
  141. braces += 1
  142. self._push()
  143. while braces:
  144. if braces == 1:
  145. return self._write_text_then_stack("{")
  146. if braces == 2:
  147. try:
  148. self._parse_template()
  149. except BadRoute:
  150. return self._write_text_then_stack("{{")
  151. break
  152. try:
  153. self._parse_argument()
  154. braces -= 3
  155. except BadRoute:
  156. try:
  157. self._parse_template()
  158. braces -= 2
  159. except BadRoute:
  160. return self._write_text_then_stack("{" * braces)
  161. if braces:
  162. self._head += 1
  163. self._write_all(self._pop())
  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._write_first(tokens.TemplateOpen())
  173. self._write_all(template)
  174. self._write(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._write_first(tokens.ArgumentOpen())
  184. self._write_all(argument)
  185. self._write(tokens.ArgumentClose())
  186. def _verify_safe(self, unsafes):
  187. """Verify that there are no unsafe characters in the current stack.
  188. The route will be failed if the name contains any element of *unsafes*
  189. in it (not merely at the beginning or end). This is used when parsing a
  190. template name or parameter key, which cannot contain newlines.
  191. """
  192. self._push_textbuffer()
  193. if self._stack:
  194. text = [tok for tok in self._stack if isinstance(tok, tokens.Text)]
  195. text = "".join([token.text for token in text]).strip()
  196. if text and any([unsafe in text for unsafe in unsafes]):
  197. self._fail_route()
  198. def _handle_template_param(self):
  199. """Handle a template parameter at the head of the string."""
  200. if self._context & contexts.TEMPLATE_NAME:
  201. self._verify_safe(["\n", "{", "}", "[", "]"])
  202. self._context ^= contexts.TEMPLATE_NAME
  203. elif self._context & contexts.TEMPLATE_PARAM_VALUE:
  204. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  205. elif self._context & contexts.TEMPLATE_PARAM_KEY:
  206. self._write_all(self._pop(keep_context=True))
  207. self._context |= contexts.TEMPLATE_PARAM_KEY
  208. self._write(tokens.TemplateParamSeparator())
  209. self._push(self._context)
  210. def _handle_template_param_value(self):
  211. """Handle a template parameter's value at the head of the string."""
  212. try:
  213. self._verify_safe(["\n", "{{", "}}"])
  214. except BadRoute:
  215. self._pop()
  216. raise
  217. self._write_all(self._pop(keep_context=True))
  218. self._context ^= contexts.TEMPLATE_PARAM_KEY
  219. self._context |= contexts.TEMPLATE_PARAM_VALUE
  220. self._write(tokens.TemplateParamEquals())
  221. def _handle_template_end(self):
  222. """Handle the end of a template at the head of the string."""
  223. if self._context & contexts.TEMPLATE_NAME:
  224. self._verify_safe(["\n", "{", "}", "[", "]"])
  225. elif self._context & contexts.TEMPLATE_PARAM_KEY:
  226. self._write_all(self._pop(keep_context=True))
  227. self._head += 1
  228. return self._pop()
  229. def _handle_argument_separator(self):
  230. """Handle the separator between an argument's name and default."""
  231. self._verify_safe(["\n", "{{", "}}"])
  232. self._context ^= contexts.ARGUMENT_NAME
  233. self._context |= contexts.ARGUMENT_DEFAULT
  234. self._write(tokens.ArgumentSeparator())
  235. def _handle_argument_end(self):
  236. """Handle the end of an argument at the head of the string."""
  237. if self._context & contexts.ARGUMENT_NAME:
  238. self._verify_safe(["\n", "{{", "}}"])
  239. self._head += 2
  240. return self._pop()
  241. def _parse_wikilink(self):
  242. """Parse an internal wikilink at the head of the wikicode string."""
  243. self._head += 2
  244. reset = self._head - 1
  245. try:
  246. wikilink = self._parse(contexts.WIKILINK_TITLE)
  247. except BadRoute:
  248. self._head = reset
  249. self._write_text("[[")
  250. else:
  251. self._write(tokens.WikilinkOpen())
  252. self._write_all(wikilink)
  253. self._write(tokens.WikilinkClose())
  254. def _handle_wikilink_separator(self):
  255. """Handle the separator between a wikilink's title and its text."""
  256. self._verify_safe(["\n", "{", "}", "[", "]"])
  257. self._context ^= contexts.WIKILINK_TITLE
  258. self._context |= contexts.WIKILINK_TEXT
  259. self._write(tokens.WikilinkSeparator())
  260. def _handle_wikilink_end(self):
  261. """Handle the end of a wikilink at the head of the string."""
  262. if self._context & contexts.WIKILINK_TITLE:
  263. self._verify_safe(["\n", "{", "}", "[", "]"])
  264. self._head += 1
  265. return self._pop()
  266. def _parse_heading(self):
  267. """Parse a section heading at the head of the wikicode string."""
  268. self._global |= contexts.GL_HEADING
  269. reset = self._head
  270. self._head += 1
  271. best = 1
  272. while self._read() == "=":
  273. best += 1
  274. self._head += 1
  275. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  276. try:
  277. title, level = self._parse(context)
  278. except BadRoute:
  279. self._head = reset + best - 1
  280. self._write_text("=" * best)
  281. else:
  282. self._write(tokens.HeadingStart(level=level))
  283. if level < best:
  284. self._write_text("=" * (best - level))
  285. self._write_all(title)
  286. self._write(tokens.HeadingEnd())
  287. finally:
  288. self._global ^= contexts.GL_HEADING
  289. def _handle_heading_end(self):
  290. """Handle the end of a section heading at the head of the string."""
  291. reset = self._head
  292. self._head += 1
  293. best = 1
  294. while self._read() == "=":
  295. best += 1
  296. self._head += 1
  297. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  298. level = min(current, min(best, 6))
  299. try:
  300. after, after_level = self._parse(self._context)
  301. except BadRoute:
  302. if level < best:
  303. self._write_text("=" * (best - level))
  304. self._head = reset + best - 1
  305. return self._pop(), level
  306. else:
  307. self._write_text("=" * best)
  308. self._write_all(after)
  309. return self._pop(), after_level
  310. def _really_parse_entity(self):
  311. """Actually parse an HTML entity and ensure that it is valid."""
  312. self._write(tokens.HTMLEntityStart())
  313. self._head += 1
  314. this = self._read(strict=True)
  315. if this == "#":
  316. numeric = True
  317. self._write(tokens.HTMLEntityNumeric())
  318. self._head += 1
  319. this = self._read(strict=True)
  320. if this[0].lower() == "x":
  321. hexadecimal = True
  322. self._write(tokens.HTMLEntityHex(char=this[0]))
  323. this = this[1:]
  324. if not this:
  325. self._fail_route()
  326. else:
  327. hexadecimal = False
  328. else:
  329. numeric = hexadecimal = False
  330. valid = string.hexdigits if hexadecimal else string.digits
  331. if not numeric and not hexadecimal:
  332. valid += string.ascii_letters
  333. if not all([char in valid for char in this]):
  334. self._fail_route()
  335. self._head += 1
  336. if self._read() != ";":
  337. self._fail_route()
  338. if numeric:
  339. test = int(this, 16) if hexadecimal else int(this)
  340. if test < 1 or test > 0x10FFFF:
  341. self._fail_route()
  342. else:
  343. if this not in htmlentities.entitydefs:
  344. self._fail_route()
  345. self._write(tokens.Text(text=this))
  346. self._write(tokens.HTMLEntityEnd())
  347. def _parse_entity(self):
  348. """Parse an HTML entity at the head of the wikicode string."""
  349. reset = self._head
  350. self._push()
  351. try:
  352. self._really_parse_entity()
  353. except BadRoute:
  354. self._head = reset
  355. self._write_text(self._read())
  356. else:
  357. self._write_all(self._pop())
  358. def _parse_comment(self):
  359. """Parse an HTML comment at the head of the wikicode string."""
  360. self._head += 4
  361. reset = self._head - 1
  362. try:
  363. comment = self._parse(contexts.COMMENT)
  364. except BadRoute:
  365. self._head = reset
  366. self._write_text("<!--")
  367. else:
  368. self._write(tokens.CommentStart())
  369. self._write_all(comment)
  370. self._write(tokens.CommentEnd())
  371. self._head += 2
  372. def _parse_tag(self):
  373. """Parse an HTML tag at the head of the wikicode string."""
  374. reset = self._head
  375. self._head += 1
  376. try:
  377. tokens = self._parse(contexts.TAG_OPEN_NAME)
  378. except BadRoute:
  379. self._head = reset
  380. self._write_text("<")
  381. else:
  382. self._write_all(tokens)
  383. def _get_tag_type_from_stack(self):
  384. self._push_textbuffer()
  385. if not self._stack:
  386. return None # Tag has an empty name?
  387. text = [tok for tok in self._stack if isinstance(tok, tokens.Text)]
  388. text = "".join([token.text for token in text]).rstrip().lower()
  389. try:
  390. return Tag.TRANSLATIONS[text]
  391. except KeyError:
  392. return Tag.TAG_UNKNOWN
  393. def _actually_close_tag_opening(self):
  394. if self._context & contexts.TAG_OPEN_ATTR:
  395. if self._context & contexts.TAG_OPEN_ATTR_NAME:
  396. self._context ^= contexts.TAG_OPEN_ATTR_NAME
  397. if self._context & contexts.TAG_OPEN_ATTR_BODY:
  398. self._context ^= contexts.TAG_OPEN_ATTR_BODY
  399. else:
  400. tag = self._get_tag_type_from_stack()
  401. if not tag:
  402. self._fail_route()
  403. self._write_first(tokens.TagOpenOpen(type=tag, showtag=True))
  404. self._context ^= contexts.TAG_OPEN_NAME
  405. self._context |= contexts.TAG_BODY
  406. ## If the last element was TagAttrStart, remove it, add " " to its padding, then return that
  407. padding = ""
  408. return padding
  409. def _actually_handle_chunk(self, chunks, is_new):
  410. if is_new and not self._context & contexts.TAG_OPEN_ATTR_QUOTED:
  411. padding = 0
  412. while chunks:
  413. if chunks[0] == "":
  414. padding += 1
  415. chunks.pop(0)
  416. else:
  417. break
  418. self._write(tokens.TagAttrStart(padding=" " * padding))
  419. elif self._context & contexts.TAG_OPEN_ATTR_IGNORE:
  420. self._context ^= contexts.TAG_OPEN_ATTR_IGNORE
  421. chunks.pop(0)
  422. return
  423. elif self._context & contexts.TAG_OPEN_ATTR_QUOTED:
  424. self._write_text(" ") # Quoted chunks don't lose their spaces
  425. if chunks:
  426. chunk = chunks.pop(0)
  427. if self._context & contexts.TAG_OPEN_ATTR_BODY:
  428. self._context ^= contexts.TAG_OPEN_ATTR_BODY
  429. self._context |= contexts.TAG_OPEN_ATTR_NAME
  430. if self._context & contexts.TAG_OPEN_ATTR_QUOTED:
  431. if re.search(r'[^\\]"', chunk[:-1]):
  432. self._fail_route()
  433. if re.search(r'[^\\]"$', chunk):
  434. self._write_text(chunk[:-1])
  435. self._context ^= contexts.TAG_OPEN_ATTR_QUOTED
  436. self._context |= contexts.TAG_OPEN_ATTR_NAME
  437. return True # Back to _handle_tag_attribute_body()
  438. self._write_text(chunk)
  439. def _handle_tag_chunk(self, text):
  440. if " " not in text:
  441. self._write_text(text)
  442. return
  443. chunks = text.split(" ")
  444. is_new = False
  445. is_quoted = False
  446. if self._context & contexts.TAG_OPEN_NAME:
  447. self._write_text(chunks.pop(0))
  448. tag = self._get_tag_type_from_stack()
  449. if not tag:
  450. self._fail_route()
  451. self._write_first(tokens.TagOpenOpen(type=tag, showtag=True))
  452. self._context ^= contexts.TAG_OPEN_NAME
  453. self._context |= contexts.TAG_OPEN_ATTR_NAME
  454. self._actually_handle_chunk(chunks, True)
  455. is_new = True
  456. while chunks:
  457. result = self._actually_handle_chunk(chunks, is_new)
  458. is_quoted = result or is_quoted
  459. is_new = True
  460. if is_quoted:
  461. return self._pop()
  462. def _handle_tag_attribute_body(self):
  463. self._context ^= contexts.TAG_OPEN_ATTR_NAME
  464. self._context |= contexts.TAG_OPEN_ATTR_BODY
  465. self._write(tokens.TagAttrEquals())
  466. next = self._read(1)
  467. if next not in self.MARKERS and next.startswith('"'):
  468. chunks = None
  469. if " " in next:
  470. chunks = next.split(" ")
  471. next = chunks.pop(0)
  472. if re.search(r'[^\\]"$', next[1:]):
  473. if not re.search(r'[^\\]"', next[1:-1]):
  474. self._write(tokens.TagAttrQuote())
  475. self._write_text(next[1:-1])
  476. self._head += 1
  477. else:
  478. if not re.search(r'[^\\]"', next[1:]):
  479. self._head += 1
  480. reset = self._head
  481. try:
  482. attr = self._parse(contexts.TAG_OPEN_ATTR_QUOTED | contexts.TAG_OPEN_ATTR_IGNORE)
  483. except BadRoute:
  484. self._head = reset
  485. self._write_text(next)
  486. else:
  487. self._write(tokens.TagAttrQuote())
  488. self._write_text(next[1:])
  489. self._write_all(attr)
  490. return
  491. self._context ^= contexts.TAG_OPEN_ATTR_BODY
  492. self._context |= contexts.TAG_OPEN_ATTR_NAME
  493. while chunks:
  494. self._actually_handle_chunk(chunks, True)
  495. def _handle_tag_close_open(self):
  496. padding = self._actually_close_tag_opening()
  497. self._write(tokens.TagCloseOpen(padding=padding))
  498. def _handle_tag_selfclose(self):
  499. padding = self._actually_close_tag_opening()
  500. self._write(tokens.TagCloseSelfclose(padding=padding))
  501. self._head += 1
  502. return self._pop()
  503. def _handle_tag_open_close(self):
  504. self._write(tokens.TagOpenClose())
  505. self._push(contexts.TAG_CLOSE)
  506. self._head += 1
  507. def _handle_tag_close_close(self):
  508. tag = self._get_tag_type_from_stack()
  509. closing = self._pop()
  510. if tag != self._stack[0].type:
  511. # Closing and opening tags are not the same, so fail this route:
  512. self._fail_route()
  513. self._write_all(closing)
  514. self._write(tokens.TagCloseClose())
  515. return self._pop()
  516. def _parse(self, context=0):
  517. """Parse the wikicode string, using *context* for when to stop."""
  518. self._push(context)
  519. while True:
  520. this = self._read()
  521. if this not in self.MARKERS:
  522. if self._context & contexts.TAG_OPEN:
  523. should_exit = self._handle_tag_chunk(this)
  524. if should_exit:
  525. return should_exit
  526. else:
  527. self._write_text(this)
  528. self._head += 1
  529. continue
  530. if this is self.END:
  531. fail = (
  532. contexts.TEMPLATE | contexts.ARGUMENT | contexts.WIKILINK |
  533. contexts.HEADING | contexts.COMMENT | contexts.TAG)
  534. double_fail = (
  535. contexts.TEMPLATE_PARAM_KEY | contexts.TAG_CLOSE |
  536. contexts.TAG_OPEN_ATTR_QUOTED)
  537. if self._context & double_fail:
  538. self._pop()
  539. if self._context & fail:
  540. self._fail_route()
  541. return self._pop()
  542. next = self._read(1)
  543. if self._context & contexts.COMMENT:
  544. if this == next == "-" and self._read(2) == ">":
  545. return self._pop()
  546. else:
  547. self._write_text(this)
  548. elif this == next == "{":
  549. self._parse_template_or_argument()
  550. elif this == "|" and self._context & contexts.TEMPLATE:
  551. self._handle_template_param()
  552. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  553. self._handle_template_param_value()
  554. elif this == next == "}" and self._context & contexts.TEMPLATE:
  555. return self._handle_template_end()
  556. elif this == "|" and self._context & contexts.ARGUMENT_NAME:
  557. self._handle_argument_separator()
  558. elif this == next == "}" and self._context & contexts.ARGUMENT:
  559. if self._read(2) == "}":
  560. return self._handle_argument_end()
  561. else:
  562. self._write_text("}")
  563. elif this == next == "[":
  564. if not self._context & contexts.WIKILINK_TITLE:
  565. self._parse_wikilink()
  566. else:
  567. self._write_text("[")
  568. elif this == "|" and self._context & contexts.WIKILINK_TITLE:
  569. self._handle_wikilink_separator()
  570. elif this == next == "]" and self._context & contexts.WIKILINK:
  571. return self._handle_wikilink_end()
  572. elif this == "=" and not self._global & contexts.GL_HEADING:
  573. if self._read(-1) in ("\n", self.START):
  574. self._parse_heading()
  575. elif self._context & contexts.TAG_OPEN_ATTR_NAME:
  576. self._handle_tag_attribute_body()
  577. else:
  578. self._write_text("=")
  579. elif this == "=" and self._context & contexts.HEADING:
  580. return self._handle_heading_end()
  581. elif this == "\n" and self._context & contexts.HEADING:
  582. self._fail_route()
  583. elif this == "&":
  584. self._parse_entity()
  585. elif this == "<" and next == "!":
  586. if self._read(2) == self._read(3) == "-":
  587. self._parse_comment()
  588. else:
  589. self._write_text(this)
  590. elif this == "<" and next != "/" and (
  591. not self._context & (contexts.TAG ^ contexts.TAG_BODY)):
  592. self._parse_tag()
  593. elif self._context & (contexts.TAG_OPEN ^ contexts.TAG_OPEN_ATTR_QUOTED):
  594. if this == "\n":
  595. if self._context & contexts.TAG_CLOSE:
  596. self._pop()
  597. self._fail_route()
  598. elif this == ">":
  599. self._handle_tag_close_open()
  600. elif this == "/" and next == ">":
  601. return self._handle_tag_selfclose()
  602. elif this == "=" and self._context & contexts.TAG_OPEN_ATTR_NAME:
  603. self._handle_tag_attribute_body()
  604. elif this == "<" and next == "/" and (
  605. self._context & contexts.TAG_BODY):
  606. self._handle_tag_open_close()
  607. elif this == ">" and self._context & contexts.TAG_CLOSE:
  608. return self._handle_tag_close_close()
  609. else:
  610. self._write_text(this)
  611. self._head += 1
  612. def tokenize(self, text):
  613. """Build a list of tokens from a string of wikicode and return it."""
  614. split = self.regex.split(text)
  615. self._text = [segment for segment in split if segment]
  616. return self._parse()