Reputation: 602
I am trying to use codemirror to my website a versatile text editor implemented in JavaScript for the browser. But the syntax highlight is not working. codeMirror Documentation didn't help me much. here is my code.
<html>
<head>
<meta charset="utf-8">
<title>Code Mirror</title>
<link rel="stylesheet" type="text/css" href="codemirror.css">
<script type="text/javascript" src="codemirror.js"></script>
</head>
<body>
<textarea id='demotext'>
function foo() {
for(i = 0, i < 10, i++)
console.log(i);
}
</textarea>
<script type="text/javascript">
var editor = CodeMirror.fromTextArea(document.getElementById("demotext"), {
lineNumbers: true,
mode: "javascript"
});
</script>
</body>
</html>
my code syntax inside textarea is not highlighting. CodeMirror syntax highlighting is not working here.
Upvotes: 15
Views: 15544
Reputation: 11
I just want write full scripts for the answer with step by step so for the newbie can follow along when want to test the full code how to implement codemirror.
Make sure to download codemirror library from the website not from GitHub release.
As I write this, CodeMirror version is 5.65.14. Extract and rename the folder without version number.
Write your HTML file parallel with codemirror folder. Don't create HTML file inside codemirror folder. I want to show in this code that we want to used CodeMirror as Syntax Highlighting for our website, not as code editor, so copy the code below:
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0" />
<title>Syntax Highlighting With CodeMirror 5</title>
<link href="codemirror/lib/codemirror.css" rel="stylesheet" />
<!-- CodeMirror Theme -->
<link rel="stylesheet" href="codemirror/theme/yonce.css" />
<script src="codemirror/lib/codemirror.js"></script>
<!-- add an add-on -->
<script src="codemirror/addon/edit/matchbrackets.js"></script>
<script src="codemirror/addon/selection/active-line.js"></script>
<!-- add mode of language that we want to syntax highlighting the code -->
<script src="codemirror/mode/javascript/javascript.js"></script>
</head>
<body>
<textarea id='kloningspoon-code'>
function foo() {
for(i = 0, i < 10, i++)
console.log(i);
}
</textarea>
<script>
CodeMirror.fromTextArea( document.getElementById("kloningspoon-code"), {
readOnly: true,
mode: "javascript",
theme: "yonce",
lineNumbers: true,
matchBrackets: true,
lineWrapping: true,
cursorHeight: 0,
styleActiveLine: true,
});
</script>
</body>
</html>
Explanation
I hope this can help.
Upvotes: 1
Reputation: 8929
You need to load the mode for the language you want to highlight. In this case, load mode/javascript/javascript.js
from the distribution.
Upvotes: 27