JavaScript - Syntax Highlighting - CodeMirror Hello World
Jump to navigation
Jump to search
About
NOTE: This page is a daughter page of: JavaScript - Syntax Highlighting
CodeMirror is a powerful syntax highlighter written in JavaScript and CSS, but reading the manual it still took me a little while to get started... here's a nice hello world that load the SQL module (you need to load at least one module) and allows resizing.
Instructions:
- Download CodeMirror from: codemirror.net.
- Unzip and then you'll want the "lib" and "mode" subdirectories to "codemirror-downloaded/".
- Create "code-mirror-hello-world.html" as follows:
CodeMirror Easy Example
code-mirror-hello-world.html:
<html lang="en">
<head>
<title>CodeMirror: Hello World Example</title>
<!---------------------- INCLUDES START ---------------------->
<!-- Download this from: (https://codemirror.net/ ... source) -->
<script src="codemirror-downloaded/lib/codemirror.js"></script>
<link rel="stylesheet" href="codemirror-downloaded/lib/codemirror.css">
<script src="codemirror-downloaded/mode/sql/sql.js"></script>
<!---------------------- INCLUDES END ---------------------->
<style>
/* Change the overall fontsize of textarea code text. */
.CodeMirror {
/* font-family: Arial, monospace; */
font-size: 10px;
border: 1px solid black;
/* resize: both; ... Sadly resize won't work here. */
width: auto;
height: auto; /* Stretch to fit container. */
}
/* Container just for size. */
.textarea-container {
width: 600px;
height: 400px;
resize: both;
overflow: auto;
padding: 2px;
background-color: #eee;
}
</style>
</head>
<body>
This is a very basic example of using CodeMirror for an SQL area:<br><br>
<div class="textarea-container">
<textarea id="my-text-area">SELECT * FROM life
</textarea>
</div>
<script>
// CodeMirror can replace a chosen text area with their highlighted version.
var myTextArea = document.getElementById('my-text-area');
var myCodeMirror = CodeMirror.fromTextArea(myTextArea, {
lineNumbers: true,
tabSize: 2,
lineWrapping: true
});
</script>
</body>
</html>
Code license | For all of the code on my site... if there are specific instruction or licence comments please leave them in. If you copy my code with minimum modifications to another webpage, or into any code other people will see I would love an acknowledgment to my site.... otherwise, the license for this code is more-or-less WTFPL (do what you want)! If only copying <20 lines, then don't bother. That said - if you'd like to add a web-link to my site www.andrewnoske.com or (better yet) the specific page with code, that's a really sweet gestures! Links to the page may be useful to yourself or your users and helps increase traffic to my site. Hope my code is useful! :)
|