[Share] Markdown + Syntax Highlighting + KaTeX

I use Anki to create flashcards that contain Python and math (displayed using KaTeX).

There was some healthy discussion in 52895 and 63515. They were super helpful and gave me an initial starting point but I noticed that KaTeX wasn’t rendering well and & would be replaced with &.

Thanks to my code in this gist, I now have the following:

As these posts get locked after 30 days, I’ll keep the gist updated and open for comments, but sharing the code below, too.

Front

<script type="module" src="https://cdn.jsdelivr.net/npm/zero-md@3?register"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">

<zero-md>
  <template data-append>
    <style>
      div {
        background-color: transparent !important;
      }
    </style>
  </template>
  <script type="text/markdown">
{{Front}}
  </script>
</zero-md>

Back

<script type="module" src="https://cdn.jsdelivr.net/npm/zero-md@3?register"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">

<zero-md>
  <template data-append>
    <style>
      div {
        background-color: transparent !important;
      }
    </style>
  </template>
  <script type="text/markdown">
{{Front}}
  </script>
</zero-md>

<hr id=answer>

<zero-md>
  <template data-append>
    <style>
      div {
        background-color: transparent !important;
      }
    </style>
  </template>
  <script type="text/markdown">
{{Back}}
  </script>
</zero-md>

<script>
(function() {
  function unescapeEntities(text) {
    return text
      .replace(/&amp;/g, '&')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&quot;/g, '"');
  }
  
  function fixMarkdownScripts() {
    document.querySelectorAll('script[type="text/markdown"]').forEach(script => {
      const original = script.textContent;
      const fixed = unescapeEntities(original);
      if (original !== fixed) {
        script.textContent = fixed;
      }
    });
  }
  
  fixMarkdownScripts();
  
  // Watch for any DOM changes (like when Anki flips cards)
  const observer = new MutationObserver(() => {
    fixMarkdownScripts();
  });
  
  observer.observe(document.body, {
    childList: true,
    subtree: true
  });
  
  // Also fix on visibility change (when card is shown/hidden)
  document.addEventListener('visibilitychange', fixMarkdownScripts);
})();
</script>

Unfortunately, Anki won’t let me share links to the GitHub Gist that I will keep updated

It’s a limitation of this forum site because your account is too new. Anki isn’t the culprit.

Anyways, you can post the link inside of a codeblock like this: forums.ankiweb.net.

2 Likes

The GitHub gist:

https://gist.github.com/olimorris/a025b1bbcdfdda5953a85bafdc6e5725
1 Like