How to add Editor Action in monaco-editor?
I have learned a lot while working on my Tinkerwell alternative project. One of them was the Monaco Editor. This time, the problem I want to tackle is having custom commands for the Monaco Editor.
I want to be able to listen when the Cmd + Enter
key is pressed. I also want to show the command when the user right-clicks on the editor. This is how it looks:
Editor Action
After some research I found that we can add custom action to monaco editor. So here's my action I created to achieve that runner code.
const executeAction: monaco.editor.IActionDescriptor = {
id: "run-code",
label: "Run Code",
contextMenuOrder: 2,
contextMenuGroupId: "1_modification",
keybindings: [
KeyMod.CtrlCmd | KeyCode.Enter,
],
run: runTinker,
}
Here is a brief description for this code.
id
: A unique identifier for the action.label
: The label of the action, this will be displayed in the context menu.contextMenuOrder
: The order in which the action should be displayed in the context menu, if you want to show this at the top set it to 0.contextMenuGroupId
: The group id of the action, set to1_modification
there are three options for this group id.navigation
- The navigation group comes first in all cases.1_modification
- This group comes next and contains commands that modify your code.9_cutcopypaste
- The last default group with the basic editing commands.
keybindings
: The keybindings to trigger the action, set to [CtrlCmd + Enter].run
: A function to be called when the action is triggered.
Don't forget to register the command to the editor.
monaco.editor.addEditorAction(executeAction)
And I think that's all. I hope you find this useful. Let me know if you have any questions.