Search code examples
javascriptpythonjupyter-notebookmathjax

Jupyter notebook equation number increases each time cell is run


I followed the answer to this question and used the following to get equation numbers in a Jupyter notebook:

%%javascript
MathJax.Hub.Config({
  TeX: { equationNumbers: { autoNumber: "AMS" } }
});

However, each time I update a markdown cell with an equation in it, the number increases by one or continues from the greatest number already in the notebook.

For example, the first equation might be numbered (3) if the cell was edited two times and it is the only equation in the notebook, or it might be numbered (5) if there are 4 equations in the notebook and the cell was edited once. If I close the notebook and open it again all the numbers are correct.

Is there a way to stop this from happening or to fix it without closing and opening the notebook?


Solution

  • If you add

    MathJax.Hub.Register.StartupHook("TeX AMSmath Ready", function () {
      var AMS = MathJax.Extension['TeX/AMSmath'];
      MathJax.InputJax.TeX.postfilterHooks.Add(function (data) {
        var jax = data.script.MathJax;
        jax.startNumber = AMS.startNumber;
        jax.eqLabels = AMS.eqlabels;
        jax.eqIDs = AMS.eqIDs;
      });
      MathJax.InputJax.TeX.prefilterHooks.Add(function (data) {
        var jax = data.script.MathJax;
        if (jax.startNumber != undefined) {
          AMS.startNumber = jax.startNumber;
          Object.keys(jax.eqLabels).forEach(function (x) {delete AMS.labels[x]});
          Object.keys(jax.eqIDs).forEach(function (x) {delete AMS.IDs[x]});
        }
      }, 1);
    });
    

    to your %%javascript section, that will set up some pre- and post-filters that save the information about the equation numbers, labels, and equation IDs that are part of the equation when it is processed, and if reprocessed, it will reset the equation numbering to start at the number of the given equation, and clear the labels and IDs from the records of the ones in use, so that it should re-typeset using the existing equation number (and not error about duplicate \label macros, and not change the tag IDs used for linking to the equation).

    I think that should do what you are looking for.