blockprocessors.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. """
  2. Python Markdown
  3. A Python implementation of John Gruber's Markdown.
  4. Documentation: https://python-markdown.github.io/
  5. GitHub: https://github.com/Python-Markdown/markdown/
  6. PyPI: https://pypi.org/project/Markdown/
  7. Started by Manfred Stienstra (http://www.dwerg.net/).
  8. Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
  9. Currently maintained by Waylan Limberg (https://github.com/waylan),
  10. Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
  11. Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
  12. Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
  13. Copyright 2004 Manfred Stienstra (the original version)
  14. License: BSD (see LICENSE.md for details).
  15. CORE MARKDOWN BLOCKPARSER
  16. ===========================================================================
  17. This parser handles basic parsing of Markdown blocks. It doesn't concern
  18. itself with inline elements such as **bold** or *italics*, but rather just
  19. catches blocks, lists, quotes, etc.
  20. The BlockParser is made up of a bunch of BlockProcessors, each handling a
  21. different type of block. Extensions may add/replace/remove BlockProcessors
  22. as they need to alter how markdown blocks are parsed.
  23. """
  24. import logging
  25. import re
  26. import xml.etree.ElementTree as etree
  27. from . import util
  28. from .blockparser import BlockParser
  29. logger = logging.getLogger('MARKDOWN')
  30. def build_block_parser(md, **kwargs):
  31. """ Build the default block parser used by Markdown. """
  32. parser = BlockParser(md)
  33. parser.blockprocessors.register(EmptyBlockProcessor(parser), 'empty', 100)
  34. parser.blockprocessors.register(ListIndentProcessor(parser), 'indent', 90)
  35. parser.blockprocessors.register(CodeBlockProcessor(parser), 'code', 80)
  36. parser.blockprocessors.register(HashHeaderProcessor(parser), 'hashheader', 70)
  37. parser.blockprocessors.register(SetextHeaderProcessor(parser), 'setextheader', 60)
  38. parser.blockprocessors.register(HRProcessor(parser), 'hr', 50)
  39. parser.blockprocessors.register(OListProcessor(parser), 'olist', 40)
  40. parser.blockprocessors.register(UListProcessor(parser), 'ulist', 30)
  41. parser.blockprocessors.register(BlockQuoteProcessor(parser), 'quote', 20)
  42. parser.blockprocessors.register(ParagraphProcessor(parser), 'paragraph', 10)
  43. return parser
  44. class BlockProcessor:
  45. """ Base class for block processors.
  46. Each subclass will provide the methods below to work with the source and
  47. tree. Each processor will need to define it's own ``test`` and ``run``
  48. methods. The ``test`` method should return True or False, to indicate
  49. whether the current block should be processed by this processor. If the
  50. test passes, the parser will call the processors ``run`` method.
  51. """
  52. def __init__(self, parser):
  53. self.parser = parser
  54. self.tab_length = parser.md.tab_length
  55. def lastChild(self, parent):
  56. """ Return the last child of an etree element. """
  57. if len(parent):
  58. return parent[-1]
  59. else:
  60. return None
  61. def detab(self, text):
  62. """ Remove a tab from the front of each line of the given text. """
  63. newtext = []
  64. lines = text.split('\n')
  65. for line in lines:
  66. if line.startswith(' '*self.tab_length):
  67. newtext.append(line[self.tab_length:])
  68. elif not line.strip():
  69. newtext.append('')
  70. else:
  71. break
  72. return '\n'.join(newtext), '\n'.join(lines[len(newtext):])
  73. def looseDetab(self, text, level=1):
  74. """ Remove a tab from front of lines but allowing dedented lines. """
  75. lines = text.split('\n')
  76. for i in range(len(lines)):
  77. if lines[i].startswith(' '*self.tab_length*level):
  78. lines[i] = lines[i][self.tab_length*level:]
  79. return '\n'.join(lines)
  80. def test(self, parent, block):
  81. """ Test for block type. Must be overridden by subclasses.
  82. As the parser loops through processors, it will call the ``test``
  83. method on each to determine if the given block of text is of that
  84. type. This method must return a boolean ``True`` or ``False``. The
  85. actual method of testing is left to the needs of that particular
  86. block type. It could be as simple as ``block.startswith(some_string)``
  87. or a complex regular expression. As the block type may be different
  88. depending on the parent of the block (i.e. inside a list), the parent
  89. etree element is also provided and may be used as part of the test.
  90. Keywords:
  91. * ``parent``: A etree element which will be the parent of the block.
  92. * ``block``: A block of text from the source which has been split at
  93. blank lines.
  94. """
  95. pass # pragma: no cover
  96. def run(self, parent, blocks):
  97. """ Run processor. Must be overridden by subclasses.
  98. When the parser determines the appropriate type of a block, the parser
  99. will call the corresponding processor's ``run`` method. This method
  100. should parse the individual lines of the block and append them to
  101. the etree.
  102. Note that both the ``parent`` and ``etree`` keywords are pointers
  103. to instances of the objects which should be edited in place. Each
  104. processor must make changes to the existing objects as there is no
  105. mechanism to return new/different objects to replace them.
  106. This means that this method should be adding SubElements or adding text
  107. to the parent, and should remove (``pop``) or add (``insert``) items to
  108. the list of blocks.
  109. Keywords:
  110. * ``parent``: A etree element which is the parent of the current block.
  111. * ``blocks``: A list of all remaining blocks of the document.
  112. """
  113. pass # pragma: no cover
  114. class ListIndentProcessor(BlockProcessor):
  115. """ Process children of list items.
  116. Example:
  117. * a list item
  118. process this part
  119. or this part
  120. """
  121. ITEM_TYPES = ['li']
  122. LIST_TYPES = ['ul', 'ol']
  123. def __init__(self, *args):
  124. super().__init__(*args)
  125. self.INDENT_RE = re.compile(r'^(([ ]{%s})+)' % self.tab_length)
  126. def test(self, parent, block):
  127. return block.startswith(' '*self.tab_length) and \
  128. not self.parser.state.isstate('detabbed') and \
  129. (parent.tag in self.ITEM_TYPES or
  130. (len(parent) and parent[-1] is not None and
  131. (parent[-1].tag in self.LIST_TYPES)))
  132. def run(self, parent, blocks):
  133. block = blocks.pop(0)
  134. level, sibling = self.get_level(parent, block)
  135. block = self.looseDetab(block, level)
  136. self.parser.state.set('detabbed')
  137. if parent.tag in self.ITEM_TYPES:
  138. # It's possible that this parent has a 'ul' or 'ol' child list
  139. # with a member. If that is the case, then that should be the
  140. # parent. This is intended to catch the edge case of an indented
  141. # list whose first member was parsed previous to this point
  142. # see OListProcessor
  143. if len(parent) and parent[-1].tag in self.LIST_TYPES:
  144. self.parser.parseBlocks(parent[-1], [block])
  145. else:
  146. # The parent is already a li. Just parse the child block.
  147. self.parser.parseBlocks(parent, [block])
  148. elif sibling.tag in self.ITEM_TYPES:
  149. # The sibling is a li. Use it as parent.
  150. self.parser.parseBlocks(sibling, [block])
  151. elif len(sibling) and sibling[-1].tag in self.ITEM_TYPES:
  152. # The parent is a list (``ol`` or ``ul``) which has children.
  153. # Assume the last child li is the parent of this block.
  154. if sibling[-1].text:
  155. # If the parent li has text, that text needs to be moved to a p
  156. # The p must be 'inserted' at beginning of list in the event
  157. # that other children already exist i.e.; a nested sublist.
  158. p = etree.Element('p')
  159. p.text = sibling[-1].text
  160. sibling[-1].text = ''
  161. sibling[-1].insert(0, p)
  162. self.parser.parseChunk(sibling[-1], block)
  163. else:
  164. self.create_item(sibling, block)
  165. self.parser.state.reset()
  166. def create_item(self, parent, block):
  167. """ Create a new li and parse the block with it as the parent. """
  168. li = etree.SubElement(parent, 'li')
  169. self.parser.parseBlocks(li, [block])
  170. def get_level(self, parent, block):
  171. """ Get level of indent based on list level. """
  172. # Get indent level
  173. m = self.INDENT_RE.match(block)
  174. if m:
  175. indent_level = len(m.group(1))/self.tab_length
  176. else:
  177. indent_level = 0
  178. if self.parser.state.isstate('list'):
  179. # We're in a tightlist - so we already are at correct parent.
  180. level = 1
  181. else:
  182. # We're in a looselist - so we need to find parent.
  183. level = 0
  184. # Step through children of tree to find matching indent level.
  185. while indent_level > level:
  186. child = self.lastChild(parent)
  187. if (child is not None and
  188. (child.tag in self.LIST_TYPES or child.tag in self.ITEM_TYPES)):
  189. if child.tag in self.LIST_TYPES:
  190. level += 1
  191. parent = child
  192. else:
  193. # No more child levels. If we're short of indent_level,
  194. # we have a code block. So we stop here.
  195. break
  196. return level, parent
  197. class CodeBlockProcessor(BlockProcessor):
  198. """ Process code blocks. """
  199. def test(self, parent, block):
  200. return block.startswith(' '*self.tab_length)
  201. def run(self, parent, blocks):
  202. sibling = self.lastChild(parent)
  203. block = blocks.pop(0)
  204. theRest = ''
  205. if (sibling is not None and sibling.tag == "pre" and
  206. len(sibling) and sibling[0].tag == "code"):
  207. # The previous block was a code block. As blank lines do not start
  208. # new code blocks, append this block to the previous, adding back
  209. # linebreaks removed from the split into a list.
  210. code = sibling[0]
  211. block, theRest = self.detab(block)
  212. code.text = util.AtomicString(
  213. '{}\n{}\n'.format(code.text, util.code_escape(block.rstrip()))
  214. )
  215. else:
  216. # This is a new codeblock. Create the elements and insert text.
  217. pre = etree.SubElement(parent, 'pre')
  218. code = etree.SubElement(pre, 'code')
  219. block, theRest = self.detab(block)
  220. code.text = util.AtomicString('%s\n' % util.code_escape(block.rstrip()))
  221. if theRest:
  222. # This block contained unindented line(s) after the first indented
  223. # line. Insert these lines as the first block of the master blocks
  224. # list for future processing.
  225. blocks.insert(0, theRest)
  226. class BlockQuoteProcessor(BlockProcessor):
  227. RE = re.compile(r'(^|\n)[ ]{0,3}>[ ]?(.*)')
  228. def test(self, parent, block):
  229. return bool(self.RE.search(block))
  230. def run(self, parent, blocks):
  231. block = blocks.pop(0)
  232. m = self.RE.search(block)
  233. if m:
  234. before = block[:m.start()] # Lines before blockquote
  235. # Pass lines before blockquote in recursively for parsing forst.
  236. self.parser.parseBlocks(parent, [before])
  237. # Remove ``> `` from beginning of each line.
  238. block = '\n'.join(
  239. [self.clean(line) for line in block[m.start():].split('\n')]
  240. )
  241. sibling = self.lastChild(parent)
  242. if sibling is not None and sibling.tag == "blockquote":
  243. # Previous block was a blockquote so set that as this blocks parent
  244. quote = sibling
  245. else:
  246. # This is a new blockquote. Create a new parent element.
  247. quote = etree.SubElement(parent, 'blockquote')
  248. # Recursively parse block with blockquote as parent.
  249. # change parser state so blockquotes embedded in lists use p tags
  250. self.parser.state.set('blockquote')
  251. self.parser.parseChunk(quote, block)
  252. self.parser.state.reset()
  253. def clean(self, line):
  254. """ Remove ``>`` from beginning of a line. """
  255. m = self.RE.match(line)
  256. if line.strip() == ">":
  257. return ""
  258. elif m:
  259. return m.group(2)
  260. else:
  261. return line
  262. class OListProcessor(BlockProcessor):
  263. """ Process ordered list blocks. """
  264. TAG = 'ol'
  265. # The integer (python string) with which the lists starts (default=1)
  266. # Eg: If list is intialized as)
  267. # 3. Item
  268. # The ol tag will get starts="3" attribute
  269. STARTSWITH = '1'
  270. # Lazy ol - ignore startswith
  271. LAZY_OL = True
  272. # List of allowed sibling tags.
  273. SIBLING_TAGS = ['ol', 'ul']
  274. def __init__(self, parser):
  275. super().__init__(parser)
  276. # Detect an item (``1. item``). ``group(1)`` contains contents of item.
  277. self.RE = re.compile(r'^[ ]{0,%d}\d+\.[ ]+(.*)' % (self.tab_length - 1))
  278. # Detect items on secondary lines. they can be of either list type.
  279. self.CHILD_RE = re.compile(r'^[ ]{0,%d}((\d+\.)|[*+-])[ ]+(.*)' %
  280. (self.tab_length - 1))
  281. # Detect indented (nested) items of either type
  282. self.INDENT_RE = re.compile(r'^[ ]{%d,%d}((\d+\.)|[*+-])[ ]+.*' %
  283. (self.tab_length, self.tab_length * 2 - 1))
  284. def test(self, parent, block):
  285. return bool(self.RE.match(block))
  286. def run(self, parent, blocks):
  287. # Check fr multiple items in one block.
  288. items = self.get_items(blocks.pop(0))
  289. sibling = self.lastChild(parent)
  290. if sibling is not None and sibling.tag in self.SIBLING_TAGS:
  291. # Previous block was a list item, so set that as parent
  292. lst = sibling
  293. # make sure previous item is in a p- if the item has text,
  294. # then it isn't in a p
  295. if lst[-1].text:
  296. # since it's possible there are other children for this
  297. # sibling, we can't just SubElement the p, we need to
  298. # insert it as the first item.
  299. p = etree.Element('p')
  300. p.text = lst[-1].text
  301. lst[-1].text = ''
  302. lst[-1].insert(0, p)
  303. # if the last item has a tail, then the tail needs to be put in a p
  304. # likely only when a header is not followed by a blank line
  305. lch = self.lastChild(lst[-1])
  306. if lch is not None and lch.tail:
  307. p = etree.SubElement(lst[-1], 'p')
  308. p.text = lch.tail.lstrip()
  309. lch.tail = ''
  310. # parse first block differently as it gets wrapped in a p.
  311. li = etree.SubElement(lst, 'li')
  312. self.parser.state.set('looselist')
  313. firstitem = items.pop(0)
  314. self.parser.parseBlocks(li, [firstitem])
  315. self.parser.state.reset()
  316. elif parent.tag in ['ol', 'ul']:
  317. # this catches the edge case of a multi-item indented list whose
  318. # first item is in a blank parent-list item:
  319. # * * subitem1
  320. # * subitem2
  321. # see also ListIndentProcessor
  322. lst = parent
  323. else:
  324. # This is a new list so create parent with appropriate tag.
  325. lst = etree.SubElement(parent, self.TAG)
  326. # Check if a custom start integer is set
  327. if not self.LAZY_OL and self.STARTSWITH != '1':
  328. lst.attrib['start'] = self.STARTSWITH
  329. self.parser.state.set('list')
  330. # Loop through items in block, recursively parsing each with the
  331. # appropriate parent.
  332. for item in items:
  333. if item.startswith(' '*self.tab_length):
  334. # Item is indented. Parse with last item as parent
  335. self.parser.parseBlocks(lst[-1], [item])
  336. else:
  337. # New item. Create li and parse with it as parent
  338. li = etree.SubElement(lst, 'li')
  339. self.parser.parseBlocks(li, [item])
  340. self.parser.state.reset()
  341. def get_items(self, block):
  342. """ Break a block into list items. """
  343. items = []
  344. for line in block.split('\n'):
  345. m = self.CHILD_RE.match(line)
  346. if m:
  347. # This is a new list item
  348. # Check first item for the start index
  349. if not items and self.TAG == 'ol':
  350. # Detect the integer value of first list item
  351. INTEGER_RE = re.compile(r'(\d+)')
  352. self.STARTSWITH = INTEGER_RE.match(m.group(1)).group()
  353. # Append to the list
  354. items.append(m.group(3))
  355. elif self.INDENT_RE.match(line):
  356. # This is an indented (possibly nested) item.
  357. if items[-1].startswith(' '*self.tab_length):
  358. # Previous item was indented. Append to that item.
  359. items[-1] = '{}\n{}'.format(items[-1], line)
  360. else:
  361. items.append(line)
  362. else:
  363. # This is another line of previous item. Append to that item.
  364. items[-1] = '{}\n{}'.format(items[-1], line)
  365. return items
  366. class UListProcessor(OListProcessor):
  367. """ Process unordered list blocks. """
  368. TAG = 'ul'
  369. def __init__(self, parser):
  370. super().__init__(parser)
  371. # Detect an item (``1. item``). ``group(1)`` contains contents of item.
  372. self.RE = re.compile(r'^[ ]{0,%d}[*+-][ ]+(.*)' % (self.tab_length - 1))
  373. class HashHeaderProcessor(BlockProcessor):
  374. """ Process Hash Headers. """
  375. # Detect a header at start of any line in block
  376. RE = re.compile(r'(?:^|\n)(?P<level>#{1,6})(?P<header>(?:\\.|[^\\])*?)#*(?:\n|$)')
  377. def test(self, parent, block):
  378. return bool(self.RE.search(block))
  379. def run(self, parent, blocks):
  380. block = blocks.pop(0)
  381. m = self.RE.search(block)
  382. if m:
  383. before = block[:m.start()] # All lines before header
  384. after = block[m.end():] # All lines after header
  385. if before:
  386. # As the header was not the first line of the block and the
  387. # lines before the header must be parsed first,
  388. # recursively parse this lines as a block.
  389. self.parser.parseBlocks(parent, [before])
  390. # Create header using named groups from RE
  391. h = etree.SubElement(parent, 'h%d' % len(m.group('level')))
  392. h.text = m.group('header').strip()
  393. if after:
  394. # Insert remaining lines as first block for future parsing.
  395. blocks.insert(0, after)
  396. else: # pragma: no cover
  397. # This should never happen, but just in case...
  398. logger.warn("We've got a problem header: %r" % block)
  399. class SetextHeaderProcessor(BlockProcessor):
  400. """ Process Setext-style Headers. """
  401. # Detect Setext-style header. Must be first 2 lines of block.
  402. RE = re.compile(r'^.*?\n[=-]+[ ]*(\n|$)', re.MULTILINE)
  403. def test(self, parent, block):
  404. return bool(self.RE.match(block))
  405. def run(self, parent, blocks):
  406. lines = blocks.pop(0).split('\n')
  407. # Determine level. ``=`` is 1 and ``-`` is 2.
  408. if lines[1].startswith('='):
  409. level = 1
  410. else:
  411. level = 2
  412. h = etree.SubElement(parent, 'h%d' % level)
  413. h.text = lines[0].strip()
  414. if len(lines) > 2:
  415. # Block contains additional lines. Add to master blocks for later.
  416. blocks.insert(0, '\n'.join(lines[2:]))
  417. class HRProcessor(BlockProcessor):
  418. """ Process Horizontal Rules. """
  419. RE = r'^[ ]{0,3}((-+[ ]{0,2}){3,}|(_+[ ]{0,2}){3,}|(\*+[ ]{0,2}){3,})[ ]*'
  420. # Detect hr on any line of a block.
  421. SEARCH_RE = re.compile(RE, re.MULTILINE)
  422. def test(self, parent, block):
  423. m = self.SEARCH_RE.search(block)
  424. # No atomic grouping in python so we simulate it here for performance.
  425. # The regex only matches what would be in the atomic group - the HR.
  426. # Then check if we are at end of block or if next char is a newline.
  427. if m and (m.end() == len(block) or block[m.end()] == '\n'):
  428. # Save match object on class instance so we can use it later.
  429. self.match = m
  430. return True
  431. return False
  432. def run(self, parent, blocks):
  433. block = blocks.pop(0)
  434. match = self.match
  435. # Check for lines in block before hr.
  436. prelines = block[:match.start()].rstrip('\n')
  437. if prelines:
  438. # Recursively parse lines before hr so they get parsed first.
  439. self.parser.parseBlocks(parent, [prelines])
  440. # create hr
  441. etree.SubElement(parent, 'hr')
  442. # check for lines in block after hr.
  443. postlines = block[match.end():].lstrip('\n')
  444. if postlines:
  445. # Add lines after hr to master blocks for later parsing.
  446. blocks.insert(0, postlines)
  447. class EmptyBlockProcessor(BlockProcessor):
  448. """ Process blocks that are empty or start with an empty line. """
  449. def test(self, parent, block):
  450. return not block or block.startswith('\n')
  451. def run(self, parent, blocks):
  452. block = blocks.pop(0)
  453. filler = '\n\n'
  454. if block:
  455. # Starts with empty line
  456. # Only replace a single line.
  457. filler = '\n'
  458. # Save the rest for later.
  459. theRest = block[1:]
  460. if theRest:
  461. # Add remaining lines to master blocks for later.
  462. blocks.insert(0, theRest)
  463. sibling = self.lastChild(parent)
  464. if (sibling is not None and sibling.tag == 'pre' and
  465. len(sibling) and sibling[0].tag == 'code'):
  466. # Last block is a codeblock. Append to preserve whitespace.
  467. sibling[0].text = util.AtomicString(
  468. '{}{}'.format(sibling[0].text, filler)
  469. )
  470. class ParagraphProcessor(BlockProcessor):
  471. """ Process Paragraph blocks. """
  472. def test(self, parent, block):
  473. return True
  474. def run(self, parent, blocks):
  475. block = blocks.pop(0)
  476. if block.strip():
  477. # Not a blank block. Add to parent, otherwise throw it away.
  478. if self.parser.state.isstate('list'):
  479. # The parent is a tight-list.
  480. #
  481. # Check for any children. This will likely only happen in a
  482. # tight-list when a header isn't followed by a blank line.
  483. # For example:
  484. #
  485. # * # Header
  486. # Line 2 of list item - not part of header.
  487. sibling = self.lastChild(parent)
  488. if sibling is not None:
  489. # Insetrt after sibling.
  490. if sibling.tail:
  491. sibling.tail = '{}\n{}'.format(sibling.tail, block)
  492. else:
  493. sibling.tail = '\n%s' % block
  494. else:
  495. # Append to parent.text
  496. if parent.text:
  497. parent.text = '{}\n{}'.format(parent.text, block)
  498. else:
  499. parent.text = block.lstrip()
  500. else:
  501. # Create a regular paragraph
  502. p = etree.SubElement(parent, 'p')
  503. p.text = block.lstrip()