CodeMirror Keymapping
by Hanna Reed
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://codemirror.net/lib/codemirror.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/mode/javascript/javascript.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.35.0/codemirror.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
<div class="codemirror_wrap">
<textarea class="editor" style="display: none;">var str = "Hello,World!"; console.log("hello, there!"); $(document).on('click', '.btn', function() { $(this).toggleClass('active'); });</textarea>
</div>
CSS
.codemirror_wrap {
width: 450px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.CodeMirror {
height: auto !important;
border-radius: 5px;
}
.CodeMirror-sizer {
padding-bottom: 10px !important;
}
JavaScript
var editorOptions = {
autoRefresh: true,
firstLineNumber: 1,
lineNumbers: true,
smartIndent: true,
lineWrapping: true,
indentWithTabs: true,
refresh: true,
mode: 'javascript'
};
$('.codemirror_wrap').each(function() {
var cm = $(this);
var editor = CodeMirror.fromTextArea(cm.find(".editor")[0], editorOptions);
cm[0].editor = editor;
editor.save();
});
var keys = {};
$(document).on('keydown', '.CodeMirror', function(e) {
var cm = $(this).closest('.codemirror_wrap'); // the editor's wrapper
var editor = cm[0].editor;
keys[e.which] = true; // set key[keycode pressed] to true
// detect if each key we want is down
if (keys[18] && keys[219]) {
alert('Alt / Option + [ clicked!');
}
});
$(document).keyup(function (e) {
// remove this key from the keys array
delete keys[e.which];
});