Reputation: 4227
I'm using monaco editor for my project and I can be able to emit editor events for undo/redo actions like so:
editor.getModel().redo();
editor.getModel().undo();
This is a very common editor, so I think there should be cut/copy/pase actions also, but unfortunately, I don't see similar actions like editor.getModel().cut.. e.t.c.
What have I missed?
Upvotes: 4
Views: 7133
Reputation: 331
If you want to use modern APIs, then you can use the Clipboard API as follows
For cut:
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,
}]);
}
}
And likewise for paste
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,
}]);
}
Upvotes: 1
Reputation: 501
You can trigger editor actions to copy/paste:
editorInstance.trigger('source','editor.action.clipboardCopyAction');
editorInstance.trigger('source','editor.action.clipboardPasteAction');
Actions available can be listed with: editorInstance.getActions().map(a => a.id)
I still haven't figured out what effect the first argument to trigger has, so I have simply provided a string that suggests what triggered the action.
Upvotes: 5
Reputation: 342
You can use native browser events along with your editor and make sure your editor has 'focus' for those actions:
editor.focus();
document.execCommand('cut'); // copy paste, e.t.c
Upvotes: 4