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

Class FootnotePostTreeprocessor

markdown/extensions/footnotes.py:383–433  ·  view source on GitHub ↗

Amend footnote div with duplicates.

Source from the content-addressed store, hash-verified

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

Callers 1

extendMarkdownMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected