Edit
Just realized a simpler method exists. Read method 2 below. I'm keeping the old method and its explanations intact and just include the improved jQuery code.
If you are asking about a native method of the package, the answer is no, it only works with textarea
. But if you are open to using workarounds, here is one that works (tested).
I have used jQuery here, but its use is not a must and you can achieve the same with pure js code, though it would be longer and not as neat as jQuery code.
Now, let's get to the workaround.
Suppose you have a <pre>
with code inside, that you want to turn into editor-less syntax-highlighted codemirror container:
<pre id="mycode">
<?php
echo 'hi';
$a = 10;
if($a == 5) echo 'too small';
?>
</pre>
What you do is,
- change the
<pre>
to <textarea>
,
- attach codemirror to the textarea,
- hide the fake cursor and keep it hidden, and
- do not allow the hidden codemirror's textarea grab the focus (and snatch it back when it does).
For the last action I have used the method suggested by Travis Webb. Here is the jQuery code that does these four things:
$(document).ready(function() {
// (1) replace pre with textarea
$('#mycode').replaceWith('<textarea id="code">' + $('#mycode').html() + '</textarea>');
// (2) attach codemirror
var editor = CodeMirror.fromTextArea($("#code"), {
lineNumbers: true,
mode: "application/x-httpd-php"
});
// (3) hide the fake cursor
$('pre.CodeMirror-cursor').hide();
// [4] textarea to grab and keep the focus
$('body').append('<textarea id="tricky" style="height: 1px; position: fixed; width: 1px; top: 0; margin-top: -100px;" wrap="off"></textarea>');
// (4) grab focus
$('#tricky').focus();
// [4] if focus is lost (probably to codemirror)
$('#tricky').blur(function() {
// (4) re-claim focus
$('#tricky').focus();
// (3) keep the fake cursor hidden
$('pre.CodeMirror-cursor').hide();
});
});
Method Two
Instead of wrestling with cursor and all that, we can remove the elements that make the editor tick. Here is the code:
$(document).ready(function() {
$('#mycode').replaceWith('<textarea id="code">' + $('#mycode').html() + '</textarea>');
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "application/x-httpd-php"
});
$('pre.CodeMirror-cursor').remove();
$('div.CodeMirror').find('textarea').blur().parent().remove();
$('div.CodeMirror').find('pre:first').remove();
$('textarea#code').remove();
});