Jan Rygh
Jan Rygh

Reputation: 61

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.

Upvotes: 6

Views: 7651

Answers (3)

n.Drake
n.Drake

Reputation: 2635

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

Upvotes: 5

joverall22
joverall22

Reputation: 350

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"});
      }
});

Upvotes: 2

AndersMad
AndersMad

Reputation: 338

No, not in the current version - hopefully there will come an updated version soon :) But you can however register your own snippet in code the will be available in autocomplete / CTRL + SPACE and then later in the command palette.

Upvotes: 0

Related Questions