Does codemirror provide Cut, Copy and Paste API?

白昼怎懂夜的黑 提交于 2020-01-03 08:52:42

问题


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!


回答1:


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.




回答2:


There are no CodeMirror APIs for cut/copy/paste because browser security restrictions forbid JavaScript from accessing the clipboard programmatically. Paste could be used to steal private data and Cut/Copy can be used as a more elaborate attack vector.

The browser's own native code handles user gestures that access the clipboard (keyboard shortcuts and context menu items), based solely on the currently selected text or focused text field.

This SO thread has a good summary of attempts to work around these restrictions. CodeMirror's approach is the first bullet: it uses a hidden textarea to ensure that user clipboard gestures work, but that still doesn't support programmatic APIs.

But there is a partial workaround: use a small Flash widget (this is the 2nd bullet in the thread above). Flash relaxes the restrictions on Copy/Cut (but not Paste) a bit. It still has to be triggered by some user event, but it could be something like clicking a button in your HTML UI. Wrappers like ZeroClipboard and Clippy make it simple to access to these capabilities without needing to know Flash. You'd need to write a little glue code to pull the appropriate string from CodeMirror when copying, but it shouldn't be too bad.




回答3:


Add a hidden contenteditable div to your textarea editor wrapper. Contenteditable divs respect new lines and tabs, which we need when copying code.

Here is my CodePen demo

var content = $('.content');
var toCopy = content.find('.copy-this');
// initialize the editor
var editorOptions = {
  autoRefresh: true,
  firstLineNumber: 1,
  lineNumbers: true,
  smartIndent: true,
  lineWrapping: true,
  indentWithTabs: true,
  refresh: true,
  mode: 'javascript'
};
var editor = CodeMirror.fromTextArea(content.find(".editor")[0], editorOptions);
content[0].editor = editor;
editor.save();

// set editors value from the textarea
var text = content.find('.editor').text();
editor.setValue(text);

// setting with editor.getValue() so that it respects \n and \t
toCopy.text(editor.getValue());

$(document).on('click', '.copy-code', function() {
  var content = $(this).closest('.content');
  var editor = content[0].editor;
  var toCopy = content.find('.copy-this')[0];

  var innerText = toCopy.innerText  // using innerText here because it preserves newlines

  // write the text to the clipboard
  navigator.clipboard.writeText(innerText);

});
.content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.CodeMirror {
  height: fit-content !important;
}
.copy-code {
  background: #339af0;
  width: fit-content;
  cursor: pointer;
}
<!-- resources -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.35.0/codemirror.css" />
<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>
<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="content">
  <!-- button to copy the editor -->
  <div class="copy-code" title="copy code">copy</div>
  <!-- add contenteditable div as it respects new lines when copying unlike textarea -->
  <div class="copy-this" contenteditable style="display: none"></div>
  <textarea class="editor" style="display: none;">// here is a comment
// here is another comment 
  </textarea>
</div>


来源:https://stackoverflow.com/questions/9492842/does-codemirror-provide-cut-copy-and-paste-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!