MCPcopy Create free account
hub / github.com/Python-Markdown/markdown / FootnotePostTreeprocessor

Class FootnotePostTreeprocessor

markdown/extensions/footnotes.py:376–426  ·  view source on GitHub ↗

Amend footnote div with duplicates.

Source from the content-addressed store, hash-verified

374
375
376class FootnotePostTreeprocessor(Treeprocessor):
377 """ Amend footnote div with duplicates. """
378
379 def __init__(self, footnotes: FootnoteExtension):
380 self.footnotes = footnotes
381
382 def add_duplicates(self, li: etree.Element, duplicates: int) -> None:
383 """ Adjust current `li` and add the duplicates: `fnref2`, `fnref3`, etc. """
384 for link in li.iter('a'):
385 # Find the link that needs to be duplicated.
386 if link.attrib.get('class', '') == 'footnote-backref':
387 ref, rest = link.attrib['href'].split(self.footnotes.get_separator(), 1)
388 # Duplicate link the number of times we need to
389 # and point the to the appropriate references.
390 links = []
391 for index in range(2, duplicates + 1):
392 sib_link = copy.deepcopy(link)
393 sib_link.attrib['href'] = '%s%d%s%s' % (ref, index, self.footnotes.get_separator(), rest)
394 links.append(sib_link)
395 self.offset += 1
396 # Add all the new duplicate links.
397 el = list(li)[-1]
398 for link in links:
399 el.append(link)
400 break
401
402 def get_num_duplicates(self, li: etree.Element) -> int:
403 """ Get the number of duplicate refs of the footnote. """
404 fn, rest = li.attrib.get('id', '').split(self.footnotes.get_separator(), 1)
405 link_id = '{}ref{}{}'.format(fn, self.footnotes.get_separator(), rest)
406 return self.footnotes.found_refs.get(link_id, 0)
407
408 def handle_duplicates(self, parent: etree.Element) -> None:
409 """ Find duplicate footnotes and format and add the duplicates. """
410 for li in list(parent):
411 # Check number of duplicates footnotes and insert
412 # additional links if needed.
413 count = self.get_num_duplicates(li)
414 if count > 1:
415 self.add_duplicates(li, count)
416
417 def run(self, root: etree.Element) -> None:
418 """ Crawl the footnote div and add missing duplicate footnotes. """
419 self.offset = 0
420 for div in root.iter('div'):
421 if div.attrib.get('class', '') == 'footnote':
422 # Footnotes should be under the first ordered list under
423 # the footnote div. So once we find it, quit.
424 for ol in div.iter('ol'):
425 self.handle_duplicates(ol)
426 break
427
428
429class FootnoteTreeprocessor(Treeprocessor):

Callers 1

extendMarkdownMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected