Skip to content

Commit

Permalink
Add n2y.plugins.footnotes
Browse files Browse the repository at this point in the history
  • Loading branch information
bimbashrestha committed Aug 9, 2022
1 parent f003e69 commit 1a3aeee
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions n2y/plugins/footnotes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import re

from pandoc.types import Note, Str, Para

from n2y.rich_text import TextRichText
from n2y.blocks import ParagraphBlock


class ParagraphWithFootnoteBlock(ParagraphBlock):
require_second_pass = True

def __init__(self, client, notion_data, page, get_children=True):
super().__init__(client, notion_data, page, get_children)
if not self.client.first_pass_complete:
self.client.plugin_data["footnotes"] = {}

def to_pandoc(self):
if not self._is_footnote():
return super().to_pandoc()
if not self.client.first_pass_complete:
self.client.plugin_data["footnotes"][self._footnote()] = self._footnote_ast()
return None

def _is_footnote(self):
return self._footnote() is not None

def _footnote(self):
first_str = self.rich_text.to_plain_text().split(" ")[0]
footnotes = re.findall(r"\[(\d+)\]:", first_str)
if len(footnotes) != 1:
return None
return footnotes[0]

def _footnote_ast(self):
ast = super().to_pandoc()
return Para(ast[0][2:]) if not isinstance(ast, list) else [Para(ast[0][0][2:])] + ast[1:]


class TextRichTextWithFootnoteRef(TextRichText):
def to_pandoc(self):
if not self.client.first_pass_complete:
return super().to_pandoc()
pandoc_ast_with_refs = []
for token in super().to_pandoc():
if not isinstance(token, Str):
pandoc_ast_with_refs.append(token)
continue
refs = re.findall(r"\[\^(\d+)\]", token[0])
if len(refs) != 1:
pandoc_ast_with_refs.append(token)
continue
block = self.client.plugin_data["footnotes"][refs[0]]
footnote = Note(block) if isinstance(block, list) else Note([block])
pandoc_ast_with_refs.append(footnote)
return pandoc_ast_with_refs


notion_classes = {
"blocks": {"paragraph": ParagraphWithFootnoteBlock},
"rich_texts": {"text": TextRichTextWithFootnoteRef},
}

0 comments on commit 1a3aeee

Please sign in to comment.