Search code examples
asp.netasp.net-mvc-5syntax-highlightingprettifypagedown

Automatic SyntaxHighlighter with Prettify


Working on a school project where we have creating a forum based website. We are using PageDown and Prettify to handle the text.
but like it's now we have to use <!--?prettify?-->on the code to get it out nice and smooth, but are there some way we can tell the program to handle all <pre>tags from PageDown automatic with prettify?

Are there some disadvantage to have automatic SyntaxHighlighter?

1# Possible solution, but not what i had in mind:

You can add $("pre").addClass("prettyprint"); to javascript. This code will give every pre tag the prettyprint class, but this short code will not work in Markdown preview so for me this is only a 50% solution.

2# Possible solution on preview, but not user friendly:

I have found out that you can call a function prettyPrint(); to highlight all the <pre>tags with class="prettyprint". So if we combined solution on with this and add a setInterval()(or something else like .click) to make calls we will get something that work with Markdown preview. I believe this way is not user friendly because it's using alot of computer power (I think) and if you watch closely you can see a little flicker sometimes in the <pre> tags.
This is the code:

var timer = setInterval(prettytimer, 0);

function prettytimer() {
    $("pre").addClass("prettyprint");
    prettyPrint();
};

If someone wondering why there is no .removeClass() or hasClass() check, that's because .addClass() doesn't add same class twice.


Solution

  • 3# solution i went for:

    This is the solution i went for in the preview handler site and solution 1# on rest of the web-page. There might be some better ways but this way will give you the Stack Overflow feeling.

    var timer;
    
    //If the code button have been pressed {}
    $("#wmd-code-button").click(function () {
        clearTimeout(timer);
        timer = setTimeout(prettytimer, 3000);
    });
    
    //when on key have been released inside textarea
    $(".wmd-input").on("keyup", function () {
        clearTimeout(timer);
        timer = setTimeout(prettytimer, 3000);
    });
    
    //If `timer` reach 3000 (3 seconds) execute this
    function prettytimer() {
        $("pre").addClass("prettyprint");
        prettyPrint();
    };
    

    If you are using pageDown Markdown then you don't have to make any changes to this code, just copy it inside your javascript file :)