diff --git a/qt/aqt/editor.py b/qt/aqt/editor.py index 816e0be71..083f0fd9d 100644 --- a/qt/aqt/editor.py +++ b/qt/aqt/editor.py @@ -420,9 +420,7 @@ class Editor: print("uncaught cmd", cmd) def mungeHTML(self, txt): - if txt in ("
", "

"): - return "" - return txt + return gui_hooks.editor_will_munge_html(txt, self) # Setting/unsetting the current note ###################################################################### @@ -1201,4 +1199,9 @@ def fontMungeHack(font): return re.sub(" L$", " Light", font) +def munge_html(txt, editor): + return "" if txt in ("
", "

") else txt + + gui_hooks.editor_will_use_font_for_field.append(fontMungeHack) +gui_hooks.editor_will_munge_html.append(munge_html) diff --git a/qt/aqt/gui_hooks.py b/qt/aqt/gui_hooks.py index 6f87684b8..bd25a03b9 100644 --- a/qt/aqt/gui_hooks.py +++ b/qt/aqt/gui_hooks.py @@ -1564,6 +1564,36 @@ class _EditorWillLoadNoteFilter: editor_will_load_note = _EditorWillLoadNoteFilter() +class _EditorWillMungeHtmlFilter: + """Allows manipulating the text that will be saved by the editor""" + + _hooks: List[Callable[[str, "aqt.editor.Editor"], str]] = [] + + def append(self, cb: Callable[[str, "aqt.editor.Editor"], str]) -> None: + """(txt: str, editor: aqt.editor.Editor)""" + self._hooks.append(cb) + + def remove(self, cb: Callable[[str, "aqt.editor.Editor"], str]) -> None: + if cb in self._hooks: + self._hooks.remove(cb) + + def count(self) -> int: + return len(self._hooks) + + def __call__(self, txt: str, editor: aqt.editor.Editor) -> str: + for filter in self._hooks: + try: + txt = filter(txt, editor) + except: + # if the hook fails, remove it + self._hooks.remove(filter) + raise + return txt + + +editor_will_munge_html = _EditorWillMungeHtmlFilter() + + class _EditorWillShowContextMenuHook: _hooks: List[Callable[["aqt.editor.EditorWebView", QMenu], None]] = [] diff --git a/qt/tools/genhooks_gui.py b/qt/tools/genhooks_gui.py index 1548d18ee..756b2c018 100644 --- a/qt/tools/genhooks_gui.py +++ b/qt/tools/genhooks_gui.py @@ -568,6 +568,12 @@ hooks = [ args=["note: anki.notes.Note"], legacy_hook="tagsUpdated", ), + Hook( + name="editor_will_munge_html", + args=["txt: str", "editor: aqt.editor.Editor"], + return_type="str", + doc="""Allows manipulating the text that will be saved by the editor""", + ), Hook( name="editor_will_use_font_for_field", args=["font: str"],