Sandro Turriate

Coder, cook, explorer

The ideal CodeMirror setup

Oct 26, 2020

CodeMirror is a powerful, full-fledged code editor in the browser that’s used all around the web. Below I outline how to get it running with the ideal set of plugins.

I like using Codemirror with a hotkey for commenting and uncommenting code, search and replace with search results displayed on the scrollbar, matching bracket highlighting, code folding, and syntax highlighting for html, css, javascript, and handlebars. If that sounds good to you, follow below.
N.B. The order of the plugins you add matter, and are usually noted in the plugin docs. Also, I happened to install Codemirror into the /static directory. You may install it wherever you like.

Add CodeMirror to the head of your document.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<script src="/static/codemirror.js"></script>

<script src="/static/addon/comment/comment.js"></script>
<script src="/static/addon/mode/simple.js"></script>
<script src="/static/addon/mode/multiplex.js"></script>
<script src="/static/addon/dialog/dialog.js"></script>
<script src="/static/addon/search/searchcursor.js"></script>
<script src="/static/addon/search/search.js"></script>
<script src="/static/addon/scroll/annotatescrollbar.js"></script>
<script src="/static/addon/search/matchesonscrollbar.js"></script>
<script src="/static/addon/edit/matchbrackets.js"></script>
<script src="/static/addon/fold/foldcode.js"></script>
<script src="/static/addon/fold/foldgutter.js"></script>
<script src="/static/addon/fold/brace-fold.js"></script>
<script src="/static/addon/fold/xml-fold.js"></script>
<script src="/static/addon/fold/indent-fold.js"></script>
<script src="/static/addon/fold/comment-fold.js"></script>
<script src="/static/mode/javascript/javascript.js"></script>
<script src="/static/mode/css/css.js"></script>
<script src="/static/mode/xml/xml.js"></script>
<script src="/static/mode/handlebars/handlebars.js"></script>
<script src="/static/mode/htmlmixed/htmlmixed.js"></script>

<link rel="stylesheet" href="/static/codemirror.css"/>
<link rel="stylesheet" href="/static/addon/dialog/dialog.css"/>
<link rel="stylesheet" href="/static/addon/search/matchesonscrollbar.css"/>
<link rel="stylesheet" href="/static/addon/fold/foldgutter.css"/>
The order of plugins matters.

Use Javascript to instantiate an instance of CodeMirror.

1
2
3
4
5
6
7
8
9
CodeMirror.fromTextArea(txt, {
    lineWrapping: true,
    lineNumbers: true,
    matchBrackets: true,
    foldGutter: true,
    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
    extraKeys: {"Alt-F": "findPersistent", "Cmd-/": 'toggleComment'},
    theme: "default my-custom-theme",
  })
Use Codemirror with options to replace a textarea.

Here’s what the final result looks like. image showing codemirror setup