21

I am implementing a UI which is supposed to look pretty much like the one on math.stackexchange.com:

  1. Using fancy Markdown like you are used to on stackoverflow
  2. Parsing formulars using MathJax between $...$-signs.

So I downloaded the PageDown demo and set it up, which works pretty well. Now I try to let MathJax being loaded dynamically everytime the <textarea>changes.

MathJax got an example for this approach but I'm not able to get it running. This is what 'my' code looks like:

     <link rel="stylesheet" type="text/css" href="demo.css" />

    <script type="text/javascript" src="../../Markdown.Converter.js"></script>
    <script type="text/javascript" src="../../Markdown.Sanitizer.js"></script>
    <script type="text/javascript" src="../../Markdown.Editor.js"></script>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"></script>
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [["$","$"],["\\(","\\)"]]
        }
      });
    $("#wmd-input").keypress(function(event){
        UpdateMath($(this).val());
    });
    </script>
    <script type="text/javascript" src="../../../mathjax-MathJax-07669ac/MathJax.js?config=TeX-AMS_HTML-full">
    </script>
</head>
<body>
    <script>
      (function () {
        var QUEUE = MathJax.Hub.queue;  // shorthand for the queue
        var math = null;                // the element jax for the math output.

        QUEUE.Push(function () {
          math = MathJax.Hub.getAllJax("#wmd-preview")[0];
        });

        window.UpdateMath = function (TeX) {
          QUEUE.Push(["Text",math,"\\displaystyle{"+TeX+"}"]);
        }
      })();
    </script>

    <div class="wmd-panel">
        <div id="wmd-button-bar"></div>
        <textarea class="wmd-input" id="wmd-input" value=""/>

    </textarea>
    </div>
    <div id="wmd-preview" class="wmd-panel wmd-preview"></div>
    <br /> <br />
    <script type="text/javascript">(function () {
                 var converter1 = Markdown.getSanitizingConverter();
            var editor1 = new Markdown.Editor(converter1);
            editor1.run();
        })();
    </script>
</body>

This snippet should update the preview everytime the keypress event is fired. Instead on page onload the tex is rendered fine but as soon as I start typing the $...$code is printed in the preview box.

Community
  • 1
  • 1
Milla Well
  • 3,193
  • 3
  • 35
  • 50

4 Answers4

24

There are several problems with your current setup. First, the example you have borrowed from is an example of updating a single equation, not paragraphs that includes multiple equations. For that, you would need to consider the second dynamic example (from the MathJax examples page). You should be getting an error message in your browser console that will have to do with a null value (math will be null unless you start out with some math in the editor to begin with).

But there is a second issue, which is that the wmd editor will be updating the wmd-preview area, and you should coordinate with it to do the MathJax updating, as otherwise it might change the content of the div while MathJax is working on it. Wmd is also smarter about when it does updates than just on every keypress (e.g., arrow keys don't cause updates), so it will be more efficient to coordinate as well. The SE version of wmd has hooks to allow you to do that, and I suspect the one you are using does as well.

Finally, you are going to have to do more work to protect the mathematics from the Markdown engine so that things like underscores and backslashes don't get processed by Markdown when they appear in mathematics. That is a bit tricky, but without that, you will run into lots of problems with your TeX code not getting processed properly.

To deal with the last two issues, you might consider looking at the code used by MSE for hooking MathJax into wmd. Perhaps that will give you some clues about how to do it.

Davide Cervone
  • 11,211
  • 1
  • 28
  • 48
  • Perfect, you helped me so much! My code now runs like you predicted: Both is working fine, but sometimes wmd is first and sometimes mathjax and each is overwriting the other. You posted that link to MSE, but I got my difficulties to read through it! What are the basic tricks done in that snippet or: Do you know about a SSCCE somewhere? – Milla Well Jun 27 '12 at 20:55
  • 1
    I think the code it commented pretty well. The main idea is to strip out the math (and replace by tokens) then run Markdown, then replace the tokens by the original math afterward. The hooks to get this inserted into the wmd workflow are in the prepareWmdForMathJax call. You can probably use your `editor1` for the EditorObject. The stuff at the bottom of the file patches MathJax to allow it to be cancelled while running. There are some routines to work around issues in IE or other browsers, but the rest I hope should be commented enough to tell what is going on. – Davide Cervone Jun 27 '12 at 21:42
  • @DavideCervone - your link to the code used by MSE appears to be broken, has the URL changed? – Aron Ahmadia Oct 11 '12 at 10:46
  • 3
    @AronAhmadia, it looks like they have changed to a minified version, so it is no longer easy to read. I have changed the link to their new copy, but you might want to use some [de-obfuscation site](http://jsbeautifier.org/) if you want to read it. I also put the [original copy](http://www.math.union.edu/~dpvc/transfer/mathjax/mathjax-editing.js) of the code that I provided to them on a server for you. They made a few changes to handle a problem with `split()` in IE (I think it was) and to prevent a problem with backticks containing dollar signs. – Davide Cervone Oct 11 '12 at 12:04
  • @DavideCervone - we're using this code for improved MathJax rendering within the IPython notebook. I didn't realize that you were the original author (indeed, I addressed the split problem with an improved regex parser courtesy Levithan). Do you mind releasing this code under BSD? You can see the current pull request here: https://github.com/ipython/ipython/pull/2349/ (your code lives in mathjaxutils.js). – Aron Ahmadia Oct 11 '12 at 13:52
  • Is Apache2 rather then BSD ok? I was going to include it as part of a sample in the MathJax examples directory, and the rest of MathJax is Apache2, so that would be easier for me if I could keep everything the same license. – Davide Cervone Oct 11 '12 at 15:48
  • @DavideCervone Absolutely! Yes, let me know when you have a permanent URL and I will link to it from the pull request (I don't anticipate it getting merged in for a couple more days, so there's no rush). – Aron Ahmadia Oct 11 '12 at 18:27
  • Sorry for the long delay in getting back to you (grading etc taking all my time). I don't have the final code ready for distribution yet, so don't have anything to point you to, and probably won't for some time. If it would help for me to add a license statement to the copy that I linked to above, I can do that. – Davide Cervone Oct 19 '12 at 22:18
  • @DavideCervone - No worries, thanks again for writing the code and your permission, our JS code has been merged in and you have been credited, ping me on SE or email when you have a link and I will update the IPython source to point to it. – Aron Ahmadia Oct 21 '12 at 16:08
  • In order to get your "original copy" script to work with the latest pagedown I had to change the "preSafe" hook to "postConversion" hook. It complained no such hook existed (preSafe). I am not sure if this change is correct or not, it was a guess - but it seems to work. – Andrew Tomazos Nov 30 '12 at 17:05
  • If you managed to have it working, can you share your code @DavideCervone ? Thanks a lot in advance! – Basj Mar 29 '15 at 22:59
  • @basj, I have not worked on the OP's code, only pointed out some issues that I knew would be problematic (having written the code used by MSE, which I linked to in my response. They have since minified the code, so looking there is not so helpful. [Here](http://www.math.union.edu/locate/Cervone/transfer/mathjax/mathjax-editing.js) is the code I originally contributed, though they did modify it to work with earlier IE versions (the split command doesn't work properly there). – Davide Cervone Mar 30 '15 at 10:02
  • @DavideCervone How to use this code http://www.math.union.edu/~dpvc/transfer/mathjax/mathjax-editing.js ? Is it another layer on top of Pagedown's `var editor1 = new Markdown.Editor(converter1); editor1.run();` ? Would you have a small example on how to use it? – Basj Mar 31 '15 at 11:29
  • @basj, sorry, that is all that I have. It is used in the StackExchange sites that provide MathJax support, so I guess that serves as an example of sorts. You might need to look at a page on math.stackexchange.com to see how it is called from there. It looks like Andrew Tomazos (four comments above) got it to work in Pagedown, so perhaps you can ping him for an example. – Davide Cervone Mar 31 '15 at 17:43
  • @AndrewTomazos Can you paste your code solution somewhere? (=how to make MathJax work with latest Pagedown). I am really interested and I opened a bounty for this – Basj Mar 31 '15 at 19:04
  • @DavideCervone : I posted an example GitHub project here : https://github.com/josephernest/pagedown_mathjax_example , reusing your `mathjax-editing.js`. [Live demo here](http://josephernest.github.io/pagedown_mathjax_example/pagedownmathjax.html). It currently displays the equations at first display of the page, but then, while writing in the `textarea`, no TeX rendering anymore. Can you help to debug this litlte thing? Probably it's just a very small thing. – Basj Apr 01 '15 at 14:40
  • @Basj, It appears that you have not hooked any of the mathjax-editing functions into your editor object. The `prepareWmdForMathJax` function is the one that did that for StackExchange, but this is never called by your code, so you will need to do something similar to that in your own code. I do not know Pagedown enough to tell you what you need to do, and can not really help you to debug this, but the key connections between my code and Wmd are made in that routine, so you should probably start there. – Davide Cervone Apr 01 '15 at 15:24
  • Ok I'll update this @DavideCervone ! A last thing: `$$..$$` are now parsed correctly but not inline `$...$` equations. Is it set up in your `mathjax-editing.js`, where ? – Basj Apr 01 '15 at 16:30
  • @basj, No, that is part of the MathJax configuration for your page. You need to enable dollar signs if you want to use them (since they are so common in non-mathematical text). See the [documentation](http://docs.mathjax.org/en/latest/start.html?highlight=dollar#tex-and-latex-input) for details about how to turn them on. When you get it working, will you update your live demo? – Davide Cervone Apr 01 '15 at 17:32
  • @Basj, did you ever have any luck creating a working example for the mathjax-editing script? – Antonio Vargas Oct 10 '15 at 17:14
  • @Basj, you may be interested in [my answer](http://stackoverflow.com/a/33181168/2420140). – Antonio Vargas Oct 17 '15 at 00:02
  • For anyone still interested, the MSE implementation has been open sourced under MIT license as pointed out by @Sergey. See https://gist.github.com/gdalgas/a652bce3a173ddc59f66 . – Megh Parikh Sep 14 '16 at 19:20
15

I just combined marked (another Markdown library than Pagedown) and "MathJax" into "markdown+mathjax live editor".

See the demo: http://kerzol.github.io/markdown-mathjax/editor.html

And get the source: https://github.com/kerzol/markdown-mathjax

Basj
  • 41,386
  • 99
  • 383
  • 673
kerzol
  • 325
  • 2
  • 14
  • Welcome on Stackoverflow. I think this should be a comment because it does not answer the question. You don't have enough reputation to post a comment. Please be patient until you're granted the needed rights. – Thomas Weller Feb 04 '14 at 21:19
  • yes, it should be a comment. Is it possible to transform my message from "answer" to "comment"? I know i cannot do it, but maybe a moderator can? – kerzol Feb 04 '14 at 21:39
  • thanks anyhow for making it work! I will very soon look into it. – Milla Well Feb 05 '14 at 07:42
  • @MillaWell and if you find any errors please let me know. – kerzol Feb 05 '14 at 08:01
  • 1
    Nice solution @SergeyKirgizov but slow : there is a time like 1 second between writing and rendering. This is not there on http://math.stackexchange.com – Basj Mar 29 '15 at 22:59
  • Hello @Basj, I created a new issue https://github.com/kerzol/markdown-mathjax/issues/8 . Can you please provide the name of your browser? Is it true for any browser on your machine? – kerzol Mar 30 '15 at 08:01
  • @Basj Do you have the same problem with http://cdn.mathjax.org/mathjax/latest/test/sample-dynamic-2.html ? – kerzol Mar 30 '15 at 08:14
  • @Basj I have tried to change smth. Is it faster now? – kerzol Mar 30 '15 at 08:36
  • I use (with Win7) Firefox 36 (nearly 1 sec latency), Chrome 39 (~500ms latency) @SergeyKirgizov , and, yes, I have the same problem with http://cdn.mathjax.org/mathjax/latest/test/sample-dynamic-2.html ... Where is your latest updated version? http://kerzol.github.io/markdown-mathjax/editor.html ? I tried but it's the same problem – Basj Mar 30 '15 at 10:51
  • Well, ok. I'll try to find the problem. But currently I don't see the reason of 1 sec latency :( – kerzol Mar 30 '15 at 11:52
  • I tried at Win8-Firefox... there is small delay between writing and rendering, but it's clearly less than 1 sec. – kerzol Mar 30 '15 at 11:57
  • compare with http://math.stackexchange.com/questions/ask : there is no latency at all when you write non-math and only standard Markdown. Can you see the difference? – Basj Mar 30 '15 at 13:53
  • Indeed, i see the difference. But i cannot read their obfuscated code http://cdn.sstatic.net/Js/mathjax-editing.en.js . Do you have any ideas why http://cdn.mathjax.org/mathjax/latest/test/sample-dynamic-2.html is so slow? – kerzol Mar 30 '15 at 14:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/74111/discussion-between-sergey-kirgizov-and-basj). – kerzol Mar 30 '15 at 15:09
  • It's better @SergeyKirgizov but still a little buggy. We can move to chat. – Basj Mar 31 '15 at 11:31
  • SergeyKirgizov this codes cleaner than the [SO gist one](https://gist.github.com/gdalgas/a652bce3a173ddc59f66) in the @Jeff Moser 's post. It is also a more straightforward combination of the codes for the *pagedown* and *Mathjax* in an input element I have reviewed so far. Is there any drawbacks to it? Should I prefer it over the [SO gist one](https://gist.github.com/gdalgas/a652bce3a173ddc59f66). – sçuçu Sep 06 '16 at 18:52
  • @Işık if you ask about issues in my code... There is [rendering speed issue](https://github.com/kerzol/markdown-mathjax/issues/8) and [some problems related to markdown-latex syntax conflicts](https://github.com/kerzol/markdown-mathjax/issues) – kerzol Sep 06 '16 at 20:54
  • 1
    @Işık There are also a conceptual difference between Marked and PageDown. Marked is "a full-featured markdown parser and compiler, written in JavaScript", but PageDown is a markdown editor. Sometimes people prefer [Marked](https://github.com/yoavram/markx/issues/44). – kerzol Sep 06 '16 at 21:11
  • And that means Marked may be possible easy to incorporate in a custom text editor than PageDown – sçuçu Sep 06 '16 at 21:16
  • 2
    Have anybody managed to actually that mentioned [SE gist](https://gist.github.com/gdalgas/a652bce3a173ddc59f66) to work, anybody other than SE apparently? I am still unable to get it work. – sçuçu Sep 06 '16 at 22:03
13

I've created a basic example for how to get Pagedown and MathJax working together using a slight modification of Stack Exchange's mathjax-editing.js.

Stack Exchange's code is based on Davide Cervone's, see his comment on another answer.

The code for the example can be viewed on github.

Community
  • 1
  • 1
Antonio Vargas
  • 496
  • 3
  • 9
  • Thanks for this @AntonioVargas, but there is still an annoying flickering with math rendering *each time we press a key*. This is not present when we write in Math.SE for example. Do you have an idea? – Basj Nov 21 '16 at 18:18
  • Something else: in your live example, the URL for the .js is out-dated. It would be nice if you can update with new .js source. – Basj Nov 21 '16 at 18:22
  • @Basj, Math.SE was recently updated with a new rendering script. It used to flicker too (and I used the old version of the code in my example). If you can get a copy of their new mathjax-editing.js script you can probably just paste it into my example to get the new behavior. – Antonio Vargas Nov 21 '16 at 18:38
  • Do you have a link for the new math SE mathjax-editing.js @AntonioVargas? Would be interesting to see if it flickers or not. – Basj Nov 21 '16 at 19:38
  • So if I understand well, there is : 1. original SE code, 2. David's modification, 3. `MJPDEditing.js` = your modification of David's code ? Is this correct? – Basj Nov 21 '16 at 19:39
  • @Basj The chain goes David's code > SE's code > MJPDEditing.js. I don't have a link to their new js file. Let me know if you find it though. – Antonio Vargas Nov 21 '16 at 21:55
  • 1
    Here is the newest version: http://dev.stackoverflow.com/content/js/mathjax-editing.js (14kB). For future reference, this is gdalgas version (12kB) : https://gist.github.com/gdalgas/a652bce3a173ddc59f66. This is DavidCervone version (7 kB) : http://www.math.union.edu/~dpvc/transfer/mathjax/mathjax-editing.js. This is AntonioVargas version (12 kB) : https://github.com/szego/pagedown-mathjax-example/blob/master/MJPDEditing.js – Basj Nov 21 '16 at 22:06
  • Do you know @AntonioVargas how to stop `$...$` to be rendered as math from JS code? Is there some sort of `editor1.disablemath();` / `editor1.enablemath();` method? – Basj Nov 22 '16 at 22:51
  • @Basj, it's part of the MathJax.Hub.Config(); command in the [html file](https://github.com/szego/pagedown-mathjax-example/blob/master/example.html). – Antonio Vargas Nov 23 '16 at 07:55
  • Thanks @AntonioVargas. Let's imagine `MathJax.Hub.Config();` has already been called, and that then a few minutes later, the user clicks on a button to disable math display. Should I call `MathJax.Hub.Config();` once again, to disable math, how would you do that? – Basj Nov 23 '16 at 09:40
  • @Basj, that question is best directed at someone more familiar with the mathjax-editing.js file. – Antonio Vargas Nov 23 '16 at 09:45
  • 2
    The example page is nothing but two textareas that do nothing. – Adam Leggett Jun 12 '17 at 22:12
  • @AdamLeggett, yes, it appears that some of the links have been broken. – Antonio Vargas Jun 22 '17 at 13:50
  • 1
    How to hook mathjax-editing.js when I use `converter.makeHtml("$a_1$ ")` so that I can Handle mathematical formulas correctly. – C. Ding Apr 10 '18 at 09:36
7

Geoff Dalgas on the Stack Overflow just released their MathJax + PageDown integration code as a gist. See the Meta post for more details.

Community
  • 1
  • 1
Jeff Moser
  • 19,727
  • 6
  • 65
  • 85
  • 2
    I am a little confused by the code in this gist. The alternative with `marked` library seems more reachable sourcecode-wise. Do you have any comments of selecting one of those two? – sçuçu Sep 06 '16 at 18:58