6

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.

3 Answers 3

5
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

Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

provide any link for working example. I tried same way it's not working
Inside snippetCompletionProvider triggerCharacters is missing but also insertText is a string and insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet should be added
Not working probably this is an old syntax. What worked for me is @n.Drake answer.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.