摩纳哥编辑 copy/cut/paste 行动

Monaco editor copy/cut/paste action

我正在为我的项目使用 monaco editor,我可以为 undo/redo 操作发出编辑器事件,如下所示:

editor.getModel().redo();
editor.getModel().undo();

这是一个非常常见的编辑器,所以我认为也应该有 cut/copy/pase 操作,但不幸的是,我没有看到类似的操作,例如 editor.getModel().cut.. e.t.c.

我错过了什么?

您可以将本机浏览器事件与您的编辑器一起使用,并确保您的编辑器具有 'focus' 这些操作:

editor.focus();
document.execCommand('cut'); // copy paste, e.t.c

您可以触发编辑器操作 copy/paste:

editorInstance.trigger('source','editor.action.clipboardCopyAction');
editorInstance.trigger('source','editor.action.clipboardPasteAction');

可以列出可用的操作:editorInstance.getActions().map(a => a.id)

我仍然没有弄清楚触发的第一个参数有什么影响,所以我只是提供了一个字符串来表明触发操作的原因。

如果你想使用现代APIs,那么你可以使用剪贴板API如下

剪裁:

function cutOrCopy(editor:monaco.editor.IStandaloneEditor, isCut:boolean) {
  editor.focus();
  // Get the current selection in the editor.
  const selection = editor.getSelection();
  if (!selection || selection.isEmpty()) {
    navigator.clipboard.writeText("");
    return;
  }

  // Get the text from that selection.
  const data = editor.getModel()?.getValueInRange(selection);

  // Set the clipboard contents.
  navigator.clipboard.writeText(data || "");

  if (isCut) {
    // This is a cut operation, so replace the selection with an empty string.
    editor.executeEdits("clipboard", [{
      range: selection,
      text: "",
      forceMoveMarkers: true,
    }]);
  }
}

粘贴也一样

async function paste(editor:monaco.editor.IStandaloneEditor) {
  editor.focus();
  // Get the current clipboard contents
  const text = await navigator.clipboard.readText();

  // Get the current selection in the editor.
  const selection = editor.getSelection();
  if (!selection) {
    return;
  }

  // Replace the current contents with the text from the clipboard.
  editor.executeEdits("clipboard", [{
    range: selection,
    text: text,
    forceMoveMarkers: true,
  }]);
}