This uses jQuery to convert an HTML string containing < code > tags into language specific CodeMirror containers. This supports a "lang" attribute to indicate the CodeMirror mode for each code block. Here is some example input:
Here is some PHP code:
<code lang=php>
print "Hello World!";
</code>
And here is some Python code:
<code lang=python>
print "Hello World!";
</code>
Next you'll need to have this template somewhere on your DOM to use for each replacement block. You can add headings or styles to this to customize your code blocks.
<div id='code_template' style="display: none;">
<textarea></textarea>
</div>
Now here is the JavaScript that will find each < code > block, replace it with our template above, attach a CodeMirror instance, load the CodeMirror mode JavaScript file and set the mode for the syntax highlighter. If the language mode does not exist or no lang tag is found it will default to 'clike'.
function setMode(cm, mode) {
if(mode !== undefined) {
var script = '/codemirror/mode/'+mode+'/'+mode+'.js';
$.getScript(script, function(data, success) {
if(success) cm.setOption('mode', mode);
else cm.setOption('mode', 'clike');
});
}
else cm.setOption('mode', 'clike');
}
$(document).ready(function () {
$('code').each(function() {
var lang = $(this).attr('lang');
var template = $('#code_template').clone();
// Take the code and put it into the textarea.
template.find('textarea').val($(this).html());
template.show();
$(this).html(template);
var cm = CodeMirror.fromTextArea($(this).find('textarea')[0], {
lineNumbers: true,
matchBrackets: true
});
setMode(cm, lang);
});
}
http://qbnz.com/highlighter/index.php i thought GeSHI was better but annyway
jQuery is very handy for manipulating a page on the fly. You can reference page elements just as you would with CSS.