CodeMirror 2 - Highlight only (no editor)
Solution 1
A much nicer and easier solution is to just set the readOnly property of the CodeMirror instance to true, like this:
$('.code').each(function() {
var $this = $(this),
$code = $this.html();
$this.empty();
var myCodeMirror = CodeMirror(this, {
value: $code,
mode: 'javascript',
lineNumbers: !$this.is('.inline'),
readOnly: true
});
});
Just add the class .code
to the tag containing the code and it will be syntax highlighted. I've also added support for inline code, by using the class .inline
.
Solution 2
As a somewhat late update, CodeMirror 2 recently gained this ability. See http://codemirror.net/demo/runmode.html
Solution 3
You should use a standalone code syntax highlighter: SyntaxHighlighter 3 works really well.
If you really want CodeMirror, there is a readOnly
option:
var myCodeMirror = CodeMirror(function(elt) {
myElement.parentNode.replaceChild(myElement, elt); // myElement is your <pre> or <div>
}, {
value: myElement.value,
readOnly: true
});
Solution 4
CodeMirror V2 contains a runmode.js.
I've wrote an example using runmode with gutter.
check: http://jsfiddle.net/lyhcode/37vHL/2/
Solution 5
Heres an simpler solution using codemirror runmode and jquery:
<pre class='code'>{:message => 'sample code'}</pre>
$(document).ready(function() {
$('.code').each(function(index, e) {
$(e).addClass('cm-s-default'); // apply a theme class
CodeMirror.runMode($(e).text(), "javascript", $(e)[0]);
});
});
Comments
-
Alex over 2 years
Can CodeMirror 2 be used to highlight code from a
DIV
orPRE
tag (without the editor)?Like CodeMirror 1 used to be able to do with the hightlightText() function? For example here: http://codemirror.net/1/highlight.html, after you press run highlight (the highlighted text below)
Also can it highlight code from a inline element, like
<code>
, and keep the results inline, like Google's Prettify does?