-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f003e69
commit 1a3aeee
Showing
1 changed file
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}, | ||
} |