How to setup CodeMirror

CodeMirror

Next →

In this tutorial we will learn to setup CodeMirror, a versatile text editor for the web.

Requirement

  1. Basic knowledge of HTML, CSS, JavaScript and jQuery
  2. Any one of the text editor like Sublime Text, Atom, Brackets or IDE like eclipse
  3. Web Browser like Chrome or Firefox
  4. CodeMirror files
  5. jQuery file

To download

CodeMirror: http://codemirror.net/

jQuery: https://jquery.com/

Optional

SublimeText: https://www.sublimetext.com/

Atom: https://atom.io/

Brackets: http://brackets.io/

eclipse: https://eclipse.org/

Steps

Download CodeMirror files.

Download jQuery file.

Create a project folder and name it codemirror

Inside the codemirror project folder create subfolders and name them js, css and plugin. The js folder will hold all the javascript files. The css folder will hold the stylesheets. And the plugin folder will contain the codemirror files.

Copy the codemirror.zip file that you downloaded earlier into the plugin folder and extract it. Once the file is extracted you can rename the folder as "codemirror" and remove the codemirror.zip file.

Now copy the jquery file that you downloaded in the js folder. You can rename this file as jquery.min.js

Now create an index.html page in the codemirror project folder and include the following files.

  • plugin/codemirror/lib/codemirror.css
  • plugin/codemirror/lib/codemirror.js
  • js/jquery.min.js

Now create a default.js file inside the js folder and include it in the index.html file.

Your index.html file should look like the following.


<!DOCTYPE html>
<html>
	<head>
		<title>CodeMirror</title>
		<link rel="stylesheet" type="text/css" href="plugin/codemirror/lib/codemirror.css">
	</head>
	<body>
		<textarea class="codemirror-textarea"></textarea>

		<!-- javascript -->
		<script type="text/javascript" src="js/jquery.min.js"></script>
		<script type="text/javascript" src="plugin/codemirror/lib/codemirror.js"></script>
		<script type="text/javascript" src="js/default.js"></script>
	</body>
</html>

Now open default.js file and write the following code.


$(document).ready(function(){
	//code here...
	var code = $(".codemirror-textarea")[0];
	var editor = CodeMirror.fromTextArea(code, {
		lineNumbers : true
	});
});

At this point you will have CodeMirror up and running!

Next →