PageRenderTime 48ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/Quicksilver/Tools/python-support/markdown/blockprocessors.py

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