diff --git a/anki/template/template.py b/anki/template/template.py index d7f748b17..82ba12ce0 100644 --- a/anki/template/template.py +++ b/anki/template/template.py @@ -207,8 +207,20 @@ class Template: # look for clozes wrapped in mathjax, and change {{cx to {{Cx def _removeFormattingFromMathjax(self, txt, ord): - regex = r"(\\[([]).*?"+(clozeReg%ord)+r".*?(\\[\])])" + opening = ["\\(", "\\["] + closing = ["\\)", "\\]"] + regex = r"(\\[([])(.*?)"+(clozeReg%ord)+r"(.*?)(\\[\])])" def repl(m): + enclosed = True + for s in closing: + if s in m.group(1): + enclosed = False + for s in opening: + if s in m.group(7): + enclosed = False + if not enclosed: + return m.group(0) + # remove formatting return m.group(0).replace("{{c", "{{C") txt = re.sub(regex, repl, txt) return txt diff --git a/tests/test_models.py b/tests/test_models.py index bbab7f7c0..39ea748b4 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -187,6 +187,19 @@ def test_cloze(): f.flush() assert len(f.cards()) == 2 +def test_cloze_mathjax(): + d = getEmptyCol() + d.models.setCurrent(d.models.byName("Cloze")) + f = d.newNote() + f['Text'] = r'{{c1::ok}} \(2^2\) {{c2::not ok}} \(2^{{c3::2}}\) \(x^3\) {{c4::blah}} {{c5::text with \(x^2\) jax}}' + assert d.addNote(f) + assert len(f.cards()) == 5 + assert "class=cloze" in f.cards()[0].q() + assert "class=cloze" in f.cards()[1].q() + assert "class=cloze" not in f.cards()[2].q() + assert "class=cloze" in f.cards()[3].q() + assert "class=cloze" in f.cards()[4].q() + def test_chained_mods(): d = getEmptyCol() d.models.setCurrent(d.models.byName("Cloze"))