Wednesday, September 14, 2016

Embedding ACE Editor on Blogger for Syntax Highlighting


Other Options:

There are many ways to include and highlight code in blogger. Ex: Github embed, html converted code with services such as hilite.me, Codepen, Jsfiddle to embed runnable js, html, css code.

Another option is using ace editor. The best part about this is it has many themes. Also there are multiple command to make it close to a full fledged editor with buttons to be used in blogger. Also the ability to enable and disable code editing.


Sample Java Code with Monokai Theme:

import java.util.*; class HW{ public static void main(String [] args){ System.out.println("HW"); } }


Sample C++ Code with XCode Theme:

#include<stdio.h> int main(){ long long ago; long time; time = 12; ago = (long long) time; printf("%lld\n", ago); return 0; }


How To Embed:

The usual instructions can be found here. The language modes can be found here and themes here.
Copy and paste the code below inside the div tags after opening a new post.
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.5/ace.js" type="text/javascript" charset="utf-8"></script>

Now create a div tag that will hold the editor with id of your choice.
<div id="editor" style="width:100%;height:12em;">
import java.util.*;

class HW{
    public static void main(String [] args){
        System.out.println("HW");
    }
}

</div>

So in the code above whatever is inside the div tags with that id will show up in the editor. Here, the code shows the hello world java code example. Finally enable ace editor for that div and set options deemed necessary.
<script>
    var editor = ace.edit("editor");

    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/java");
    editor.setReadOnly(true);
    editor.setShowPrintMargin(false);

</script>
If everything was done correctly the editor should show up.

1 comment:

Aamir Ahmad Ansari said...

It did helped, Thanks. But my code starts from line 2. Any Solutions for that.