Reorder list items in the footnotes div.
| 440 | |
| 441 | |
| 442 | class FootnoteReorderingProcessor(Treeprocessor): |
| 443 | """ Reorder list items in the footnotes div. """ |
| 444 | |
| 445 | def __init__(self, footnotes: FootnoteExtension): |
| 446 | self.footnotes = footnotes |
| 447 | |
| 448 | def run(self, root: etree.Element) -> None: |
| 449 | if not self.footnotes.footnotes: |
| 450 | return |
| 451 | if self.footnotes.footnote_order != list(self.footnotes.footnotes.keys()): |
| 452 | for div in root.iter('div'): |
| 453 | if div.attrib.get('class', '') == 'footnote': |
| 454 | self.reorder_footnotes(div) |
| 455 | break |
| 456 | |
| 457 | def reorder_footnotes(self, parent: etree.Element) -> None: |
| 458 | old_list = parent.find('ol') |
| 459 | parent.remove(old_list) |
| 460 | items = old_list.findall('li') |
| 461 | |
| 462 | def order_by_id(li) -> int: |
| 463 | id = li.attrib.get('id', '').split(self.footnotes.get_separator(), 1)[-1] |
| 464 | return ( |
| 465 | self.footnotes.footnote_order.index(id) |
| 466 | if id in self.footnotes.footnote_order |
| 467 | else len(self.footnotes.footnotes) |
| 468 | ) |
| 469 | |
| 470 | items = sorted(items, key=order_by_id) |
| 471 | |
| 472 | new_list = etree.SubElement(parent, 'ol') |
| 473 | |
| 474 | for index, item in enumerate(items, start=1): |
| 475 | backlink = item.find('.//a[@class="footnote-backref"]') |
| 476 | backlink.set("title", self.footnotes.getConfig("BACKLINK_TITLE").format(index)) |
| 477 | new_list.append(item) |
| 478 | |
| 479 | |
| 480 | class FootnotePostprocessor(Postprocessor): |