Does codemirror provide Cut, Copy and Paste API?

HelloCW picture HelloCW · Feb 29, 2012 · Viewed 8.3k times · Source

From http://codemirror.net/doc/manual.html, I only find getRange(), undo(), redo() etc, and I can't find cut(), copy() and paste API, and more when I try to run editor.execCommand("cut"), I get the error. Could you help me? Thanks!

Answer

Mr. Polywhirl picture Mr. Polywhirl · Oct 17, 2015

Using clipboard.js, you can define the text() function to grab the value of the CodeMirror's inner document.

Store a reference to the (<textarea>) editor's selector for convenience.

var editorSelector = '#editor' // or '#editor + .CodeMirror';

Instantiate a new ClipBoard object with reference to your button.

new Clipboard('.clip-btn-native', {
    text: function(trigger) {
        return getCodeMirrorNative(editorSelector).getDoc().getValue();
    }
});

Retrieve a CodeMirror Instance via native JavaScript.

function getCodeMirrorNative(target) {
    var _target = target;
    if (typeof _target === 'string') {
        _target = document.querySelector(_target);
    }
    if (_target === null || !_target.tagName === undefined) {
        throw new Error('Element does not reference a CodeMirror instance.');
    }

    if (_target.className.indexOf('CodeMirror') > -1) {
        return _target.CodeMirror;
    }

    if (_target.tagName === 'TEXTAREA') {
        return _target.nextSibling.CodeMirror;
    }

    return null;
};

Demo

Please see complete; in-depth demo over at JSFiddle.