How To Use CodeMirror as a FrontEnd Editor

By | September 27, 2015

728x90-popads_1

How To Use CodeMirror as a FrontEnd Editor

In this tutorial I will show you how to create a online code editor like Codepen, jsFiddle,repl.it etc.

After reading this tutorial you will be able to create such kind of awesome tools with just few lines of code. Let’s see a demo of what we will be creating in this tutorial.

live_demo_button.fw_

Let’s see how to create such kind of tools.

code-mirror

What are the basic components?

These tools are made up of two basic components: code editor and code interpreter/compiler. Let’s see how to create a code editor and how to execute the code.

Creating a Frontend Code Editor

There are basically three ways of creating a code editor:

  1. We can use a HTML textarea element as a editor. But the problem with textarea element we cannot style the text inside it therefore its not possible to support syntax highlighting.
  2. We can use WYSIWYG HTML5 API’s contenteditable attribute to convert a div into a editor. We can also highlight code. But the problem is it will not support in old browsers.
  3. The final solution is to create your own custom editor from scratch. Creating a editor from required a lot of work because you need to emulate cursor, handle lots of keyboard and mouse events and also have to deal with a lot of data structure and algorithms. Therefore we can use open source custom text editors like CodeMirror. If you would have build your own editor then it would have been something like CodeMirror.

With just few lines of code we finished building a front end HTML code editor using CodeMirror.

Here we loaded XML highlighting mode library but if you need your code editor to highlight some other language then load appropriate mode library. For more information refer to CodeMirror docs.

Code Execution

If your editor is for front-end languages(HTML, CSS and JS) then you can execute the code inside an iframe. But if you code editor is for languages like C++, PHP, Java, Python etc then you can execute your code inside a Docker container and display the output on frontend.

Here I am creating a editor for frontend languages therefore I will execute code inside iFrame. here is the code to execute frontend code

Here we encoding the user entered code into base64 and assigning it to the iFrame via data URI. Here we are using jQuery base64 encoding library to encode code into base64.

Now you must be amazed to see how we created a frontend code editor with just few lines of code.

728x90-popads_1