let PageDown and MathJax work together
Asked Answered
T

4

22

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.

Testes answered 27/6, 2012 at 14:30 Comment(1)
Hello, if you have successfully done what you wanted to do, Can I have a link to you blog?Mayst
A
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.

Attalanta answered 16/10, 2015 at 23:51 Comment(14)
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?Bodine
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.Bodine
@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.Attalanta
Do you have a link for the new math SE mathjax-editing.js @AntonioVargas? Would be interesting to see if it flickers or not.Bodine
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?Bodine
@Bodine 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.Attalanta
Here is the newest version: dev.stackoverflow.com/content/js/mathjax-editing.js (14kB). For future reference, this is gdalgas version (12kB) : gist.github.com/gdalgas/a652bce3a173ddc59f66. This is DavidCervone version (7 kB) : math.union.edu/~dpvc/transfer/mathjax/mathjax-editing.js. This is AntonioVargas version (12 kB) : github.com/szego/pagedown-mathjax-example/blob/master/…Bodine
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?Bodine
@Basj, it's part of the MathJax.Hub.Config(); command in the html file.Attalanta
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?Bodine
@Basj, that question is best directed at someone more familiar with the mathjax-editing.js file.Attalanta
The example page is nothing but two textareas that do nothing.Snake
@AdamLeggett, yes, it appears that some of the links have been broken.Attalanta
How to hook mathjax-editing.js when I use converter.makeHtml("$a_1$ ") so that I can Handle mathematical formulas correctly.Latten
F
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.

Fungible answered 27/6, 2012 at 16:35 Comment(22)
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?Testes
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.Fungible
@DavideCervone - your link to the code used by MSE appears to be broken, has the URL changed?Fessler
@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 if you want to read it. I also put the original copy 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.Fungible
@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: github.com/ipython/ipython/pull/2349 (your code lives in mathjaxutils.js).Fessler
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.Fungible
@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).Fessler
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.Fungible
@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.Fessler
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.Amazement
If you managed to have it working, can you share your code @DavideCervone ? Thanks a lot in advance!Bodine
@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 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).Fungible
@DavideCervone How to use this code 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?Bodine
@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.Fungible
@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 thisBodine
@DavideCervone : I posted an example GitHub project here : github.com/josephernest/pagedown_mathjax_example , reusing your mathjax-editing.js. Live demo here. 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.Bodine
@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.Fungible
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 ?Bodine
@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 for details about how to turn them on. When you get it working, will you update your live demo?Fungible
@Basj, did you ever have any luck creating a working example for the mathjax-editing script?Attalanta
@Basj, you may be interested in my answer.Attalanta
For anyone still interested, the MSE implementation has been open sourced under MIT license as pointed out by @Sergey. See gist.github.com/gdalgas/a652bce3a173ddc59f66 .Velate
O
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

Outofdoors answered 4/2, 2014 at 20:53 Comment(20)
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.Molest
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?Outofdoors
thanks anyhow for making it work! I will very soon look into it.Testes
@MillaWell and if you find any errors please let me know.Outofdoors
Nice solution @SergeyKirgizov but slow : there is a time like 1 second between writing and rendering. This is not there on math.stackexchange.comBodine
Hello @Basj, I created a new issue 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?Outofdoors
@Bodine Do you have the same problem with cdn.mathjax.org/mathjax/latest/test/sample-dynamic-2.html ?Outofdoors
@Bodine I have tried to change smth. Is it faster now?Outofdoors
I use (with Win7) Firefox 36 (nearly 1 sec latency), Chrome 39 (~500ms latency) @SergeyKirgizov , and, yes, I have the same problem with cdn.mathjax.org/mathjax/latest/test/sample-dynamic-2.html ... Where is your latest updated version? kerzol.github.io/markdown-mathjax/editor.html ? I tried but it's the same problemBodine
Well, ok. I'll try to find the problem. But currently I don't see the reason of 1 sec latency :(Outofdoors
I tried at Win8-Firefox... there is small delay between writing and rendering, but it's clearly less than 1 sec.Outofdoors
compare with 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?Bodine
Indeed, i see the difference. But i cannot read their obfuscated code cdn.sstatic.net/Js/mathjax-editing.en.js . Do you have any ideas why cdn.mathjax.org/mathjax/latest/test/sample-dynamic-2.html is so slow?Outofdoors
Let us continue this discussion in chat.Outofdoors
It's better @SergeyKirgizov but still a little buggy. We can move to chat.Bodine
SergeyKirgizov this codes cleaner than the SO gist one 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.Triplicate
@Işık if you ask about issues in my code... There is rendering speed issue and some problems related to markdown-latex syntax conflictsOutofdoors
@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.Outofdoors
And that means Marked may be possible easy to incorporate in a custom text editor than PageDownTriplicate
Have anybody managed to actually that mentioned SE gist to work, anybody other than SE apparently? I am still unable to get it work.Triplicate
A
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.

Attalanta answered 16/10, 2015 at 23:51 Comment(14)
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?Bodine
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.Bodine
@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.Attalanta
Do you have a link for the new math SE mathjax-editing.js @AntonioVargas? Would be interesting to see if it flickers or not.Bodine
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?Bodine
@Bodine 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.Attalanta
Here is the newest version: dev.stackoverflow.com/content/js/mathjax-editing.js (14kB). For future reference, this is gdalgas version (12kB) : gist.github.com/gdalgas/a652bce3a173ddc59f66. This is DavidCervone version (7 kB) : math.union.edu/~dpvc/transfer/mathjax/mathjax-editing.js. This is AntonioVargas version (12 kB) : github.com/szego/pagedown-mathjax-example/blob/master/…Bodine
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?Bodine
@Basj, it's part of the MathJax.Hub.Config(); command in the html file.Attalanta
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?Bodine
@Basj, that question is best directed at someone more familiar with the mathjax-editing.js file.Attalanta
The example page is nothing but two textareas that do nothing.Snake
@AdamLeggett, yes, it appears that some of the links have been broken.Attalanta
How to hook mathjax-editing.js when I use converter.makeHtml("$a_1$ ") so that I can Handle mathematical formulas correctly.Latten
G
7

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

Gaul answered 12/2, 2016 at 16:55 Comment(1)
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?Triplicate

© 2022 - 2024 — McMap. All rights reserved.