Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert snippet in Monaco Editor?

I am using Monaco Editor v 0.10.1 in a webpage, and wonder if anybody knows if it is possible to add a set of Snippets that will pop up in Command Palette -> Insert Snippet like for the Visual Code editor.

like image 255
Jan Rygh Avatar asked Jan 11 '18 16:01

Jan Rygh


2 Answers

You can use the AddAction method to do this...

//Register a custom snippet
monaco.languages.registerCompletionItemProvider('javascript', {
      provideCompletionItems: () => {
        return [
          {
            label: 'for: Array',
            kind: monaco.languages.CompletionItemKind.Snippet,
            documentation: 'Iterate over an Array',
            insertText: [
              'for(let i=0; i < arr.length; i++){',
              '\tlet elem = arr[i];',
              '',
              '}'].join('\n')
          }
        ]
      }
    });

//Add custom action
this.editor = window.monaco.editor.create(this.$el, options);
window.activeEditor = this.editor
this.editor.addAction({
      id: 'insert-text-at-cusor-command',
      label: 'Command Snippet',
      keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F10],
      contextMenuGroupId: 'snippets',
      contextMenuOrder: 1.5,
      run: function (ed) {
        activeEditor.focus()
        activeEditor.trigger('keyboard', 'type', {text: "for"});
      }
});
like image 32
joverall22 Avatar answered Oct 23 '22 10:10

joverall22


monaco.languages.registerCompletionItemProvider('javascript', {
  provideCompletionItems: () => {
    return {
      suggestions: [
        {
          label: 'Async Block',
          kind: monaco.languages.CompletionItemKind.Snippet,
          documentation: 'Add an async block',
          insertText: [
            '(async () => {',
            '\t',
            '})()'].join('\n')
        }
      ]
    };
  }
});

Reference: https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-completion-provider-example

like image 74
n.Drake Avatar answered Oct 23 '22 09:10

n.Drake