DEV Community

Fernando Paladini
Fernando Paladini

Posted on

Test and Audit a Single-Card Cloze Add-on for Anki in Python

When you highlight several words in an Anki note and click [...] repeatedly, Anki increments the cloze index ({{c1::1957}}, {{c2::Soviet Union}}, {{c3::Sputnik 1}}). That creates three review cards from one sentence instead of masking all blanks on a single card. Unless you hold Alt (Option on macOS) each time, you can split coupled facts across extra cards by accident.

paladini/anki-cloze-deletion-single-card is a 26-line, AGPL-3.0 Python add-on from March 2016 (published on AnkiWeb as 1392166854) that forces every cloze button action onto c1 so all blanks appear on one card. Because the whole plugin lives in Cloze_Deletion_Single_Card.py, it makes a focused case study in desktop plugin engineering: how to unit-test PyQt host hooks in pure Python without launching a GUI, and what changes between Anki 2.0 and Anki 2.1+.

In this tutorial, you will check out the verified master commit, build a zero-dependency unittest harness that stubs anki and aqt to test all four execution paths in milliseconds, and audit the architectural, regex, and licensing details that matter before porting legacy Anki plugins.

TL;DR

  • Check out commit 8731511 on master (the repository has no tagged releases).
  • Stub anki.hooks, aqt.editor, aqt.utils, and builtins._ to test every branch of Cloze_Deletion_Single_Card.py headlessly with unittest.
  • Notice why addMode = True emits a warning tooltip on non-Cloze notes yet still inserts {{c1::...}}, while editing an existing non-Cloze note aborts early.
  • Treat this code as an Anki 2.0 reference: modern Anki supports single-card clozes natively via Ctrl+Shift+Alt+C and uses addons21/ packages plus aqt.gui_hooks.

Prerequisites

You do not need Anki desktop or PyQt installed to verify the Python logic locally:

  • Git to clone paladini/anki-cloze-deletion-single-card at commit 873151137e531719701ad535352c634ab7db972f.
  • Python 3.9+ (python3 on Linux/macOS or py -3 on Windows), using only the standard library (unittest, types, importlib.util, and builtins).
  • Familiarity with Anki's Cloze Deletion note type and Python monkey-patching.

Minimal Working Path

Clone the repository at commit 873151137e531719701ad535352c634ab7db972f (the latest commit on master, which added a missing tooltip import in 8731511):

git clone https://github.com/paladini/anki-cloze-deletion-single-card.git
cd anki-cloze-deletion-single-card
git checkout 873151137e531719701ad535352c634ab7db972f
Enter fullscreen mode Exit fullscreen mode

Inspect Cloze_Deletion_Single_Card.py. Aside from header comments, the implementation is 19 lines:

from anki.hooks import wrap
from aqt.editor import Editor
from aqt.utils import showInfo, tooltip
import re

def newOnCloze(self):
    # check that the model is set up for cloze deletion
    if not re.search('{{(.*:)*cloze:',self.note.model()['tmpls'][0]['qfmt']):
        if self.addMode:
            tooltip(_("Warning, cloze deletions will not work until you switch the type at the top to Cloze."))
        else:
            showInfo(_("""\
To make a cloze deletion on an existing note, you need to change it \
to a cloze type first, via Edit>Change Note Type."""))
            return
    # always use 'c1' as Cloze Deletion tag.
    self.web.eval("wrap('{{c1::', '}}');")

Editor.onCloze = newOnCloze
Enter fullscreen mode Exit fullscreen mode

Importing Cloze_Deletion_Single_Card.py directly in a standalone Python process fails with ModuleNotFoundError because anki and aqt live inside the Anki desktop runtime, and _() relies on Anki injecting gettext into builtins.

Save test_cloze_single_card.py outside the repository so the working tree stays clean. It registers minimal module stubs in sys.modules and tests all four template and editor-mode combinations:

import builtins, importlib.util, os, sys, types, unittest
from pathlib import Path

REPO_DIR = Path(os.environ.get("ANKI_ADDON_REPO", "."))


def load_addon():
    events = []
    anki_mod, hooks_mod = types.ModuleType("anki"), types.ModuleType("anki.hooks")
    hooks_mod.wrap = lambda old, new, pos="after": (old, new, pos)
    anki_mod.hooks = hooks_mod

    aqt_mod = types.ModuleType("aqt")
    editor_mod, utils_mod = types.ModuleType("aqt.editor"), types.ModuleType("aqt.utils")

    class StubEditor:
        def onCloze(self):
            raise AssertionError("Original Editor.onCloze was not overridden")

    editor_mod.Editor = StubEditor
    utils_mod.tooltip = lambda msg: events.append(("tooltip", msg))
    utils_mod.showInfo = lambda msg: events.append(("showInfo", msg))
    aqt_mod.editor, aqt_mod.utils = editor_mod, utils_mod

    sys.modules.update({
        "anki": anki_mod, "anki.hooks": hooks_mod,
        "aqt": aqt_mod, "aqt.editor": editor_mod, "aqt.utils": utils_mod,
    })
    builtins._ = lambda text: text

    spec = importlib.util.spec_from_file_location(
        "cloze_single_card", REPO_DIR / "Cloze_Deletion_Single_Card.py"
    )
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return StubEditor, events


class ClozeSingleCardTests(unittest.TestCase):
    def setUp(self):
        self.EditorClass, self.events = load_addon()

    def _editor(self, qfmt, add_mode):
        ed = self.EditorClass()
        ed.addMode = add_mode
        ed.note = types.SimpleNamespace(model=lambda: {"tmpls": [{"qfmt": qfmt}]})
        ed.web = types.SimpleNamespace(eval=lambda js: self.events.append(("eval", js)))
        return ed

    def test_standard_cloze_wraps_c1(self):
        self._editor("{{cloze:Text}}", True).onCloze()
        self.assertEqual(self.events, [("eval", "wrap('{{c1::', '}}');")])

    def test_filtered_cloze_wraps_c1(self):
        self._editor("{{type:cloze:Text}}", False).onCloze()
        self.assertEqual(self.events, [("eval", "wrap('{{c1::', '}}');")])

    def test_basic_add_mode_warns_and_wraps(self):
        self._editor("{{Front}}", True).onCloze()
        self.assertEqual(self.events[0][0], "tooltip")
        self.assertEqual(self.events[1], ("eval", "wrap('{{c1::', '}}');"))

    def test_basic_edit_mode_blocks_early(self):
        self._editor("{{Front}}", False).onCloze()
        self.assertEqual(len(self.events), 1)
        self.assertEqual(self.events[0][0], "showInfo")


if __name__ == "__main__":
    unittest.main(verbosity=2)
Enter fullscreen mode Exit fullscreen mode

Expected Result and Reproducible Verification

Point ANKI_ADDON_REPO at your checkout and run the suite (in PowerShell, set $env:ANKI_ADDON_REPO first and run py -3 test_cloze_single_card.py):

ANKI_ADDON_REPO=/path/to/anki-cloze-deletion-single-card python3 test_cloze_single_card.py
Enter fullscreen mode Exit fullscreen mode

Verified local execution outputs:

test_basic_add_mode_warns_and_wraps (__main__.ClozeSingleCardTests.test_basic_add_mode_warns_and_wraps) ... ok
test_basic_edit_mode_blocks_early (__main__.ClozeSingleCardTests.test_basic_edit_mode_blocks_early) ... ok
test_filtered_cloze_wraps_c1 (__main__.ClozeSingleCardTests.test_filtered_cloze_wraps_c1) ... ok
test_standard_cloze_wraps_c1 (__main__.ClozeSingleCardTests.test_standard_cloze_wraps_c1) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.002s

OK
Enter fullscreen mode Exit fullscreen mode

Every branch runs without starting Qt widgets, an SQLite collection, or a WebView process.

Why It Works

Three details explain how Cloze_Deletion_Single_Card.py works and what the unit tests prove:

  1. Filter-aware template detection. Rather than checking the note type's display name (which users localize or rename), re.search('{{(.*:)*cloze:', self.note.model()['tmpls'][0]['qfmt']) inspects qfmt, matching both {{cloze:Text}} and chained filters like {{type:cloze:Text}}.
  2. Asymmetric Add vs. Edit guardrails. Under if self.addMode:, drafting a new note on Basic triggers tooltip(...) and still inserts {{c1::...}} so you can switch the Note Type to Cloze afterward. When self.addMode is False, changing note types needs a separate menu action, so showInfo(...) warns and return aborts early.
  3. Fixed c1 WebView bridge. Standard Anki 2.0 Editor.onCloze scanned fields for the highest {{cN:: tag and incremented N unless Alt was held. Calling self.web.eval("wrap('{{c1::', '}}');") skips scanning and wraps selections in {{c1:: and }}.

Failure Modes, Limitations, and Security Boundaries

Account for five constraints verified against the repository and current Anki docs before reusing this code:

  • Anki 2.0 layout vs. Anki 2.1+ architecture. Placing one .py file in addons/ targets Anki 2.0 (readme.md). Per Porting Anki 2.0 add-ons and Add-on Development Introduction, Anki 2.1+ requires addons21/<package>/__init__.py, replaces note.model() with note.note_type(), and moves editor formatting into TypeScript and Svelte where Python Editor.onCloze overrides and global wrap(...) no longer apply.
  • Native shortcut in modern Anki. For multiple clozes on c1, Anki's Adding/Editing manual documents holding Alt (Option on macOS) while clicking [...] or pressing Ctrl+Shift+Alt+C (Cmd+Option+Shift+C on macOS) to reuse the current cloze number without an add-on.
  • Direct monkey-patching vs. composable hooks. Line 7 imports wrap from anki.hooks without using it, while line 26 overwrites Editor.onCloze = newOnCloze, clobbering other add-ons. Modern plugins register callbacks via aqt.gui_hooks as shown in Hooks & Filters.
  • Implicit builtins._ and greedy regex. Commit 8731511 fixed an unimported tooltip call, yet _() still assumes Anki 2.0 injected gettext into builtins. Also, tmpls[0]['qfmt'] checks only template 0, and r'{{(.*:)*cloze:' nests greedy .* inside *, risking backtracking on malformed {{a:b:c:... text; r'\{\{(?:[^}:]*:)*cloze:' stays linear.
  • No sandbox and AGPL-3.0 vs. GPL-3.0 mismatch. Anki add-ons run as unsandboxed local Python with full collection and filesystem access. Also note a license mismatch: license and readme.md declare GNU AGPL-3.0 (citing AnkiWeb terms), whereas line 3 of Cloze_Deletion_Single_Card.py says GNU GPL, version 3 or later. Treat the root license file (AGPL-3.0) as authoritative before redistributing derivatives.

FAQ

Does this repository publish tagged releases or PyPI packages?

No. GitHub has zero tags and zero releases; commit 873151137e531719701ad535352c634ab7db972f (March 24, 2016) is the master state alongside AnkiWeb ID 1392166854.

Why did the initial commit fail on Basic notes?

Commit 59685f1 called tooltip(...) and showInfo(...) without importing them from aqt.utils. Commit 8731511 added from aqt.utils import showInfo, tooltip.

Can you still create a c2 card with this add-on active in Anki 2.0?

Only by typing {{c2::...}} manually. Because newOnCloze always evaluates wrap('{{c1::', '}}');, the toolbar button always inserts c1.

Takeaway

Even a 26-line plugin carries control-flow subtleties, host-version boundaries, and license obligations. Isolating GUI imports behind sys.modules stubs in unittest verifies legacy behavior in milliseconds before porting to Anki 2.1's gui_hooks and Svelte editor.

Disclosure: This tutorial was researched and drafted with AI assistance. All repository files, commit diffs, official Anki docs, and unittest outputs were verified against commit 873151137e531719701ad535352c634ab7db972f of paladini/anki-cloze-deletion-single-card and executed locally in Python 3.

When you maintain or audit plugins for desktop apps like Anki, VS Code, or Obsidian, do you stub the host API in unit tests or rely on end-to-end runs inside the host app?

Top comments (0)