3

I'm using the monaco editor as a search field. I want to be able to listen to the event when a user selects a suggestion item. If a user selects the suggestion item using tab, or clicks on the suggestion, is there a contextKey or action that gets triggered?

mfa
  • 61
  • 4

1 Answers1

2

[UPD]: added arguments to command to get completion name in the trigger function.

Yes, there is a command field in CompletionItem (I didn't find anything like that in CompletionItemProvider). This means, that you have to add a trigger to each of your completion items. These triggers might differ, just create another one with editor.addCommand.

Here is the code example (and here is a link to the same code in monaco-editor):

var editor = monaco.editor.create(document.getElementById("container"), {
    value: '', language: "json",
});

var commandId = editor.addCommand(
    0,
    function (_, ...args) {
        // here is your trigger function
        alert(`your command ${args} is executing!`);
    },
    ""
);

function createDependencyProposals(range) {
    return [
        {
            label: '"completion"',
            insertText: 'my completion',
            range: range,
            command: {
                id: commandId,
                title: "commandTitle",
                arguments: ['my first completion']
            }
        },
        {
            label: '"completion2"',
            insertText: 'my second completion',
            range: range,
            command: {
                id: commandId,
                title: "commandTitle",
                arguments: ['my second completion']
            }
        },
    ];
}

monaco.languages.registerCompletionItemProvider("json", {
    provideCompletionItems: function (model, position) {
        var word = model.getWordUntilPosition(position);
        var range = {
            startLineNumber: position.lineNumber,
            endLineNumber: position.lineNumber,
            startColumn: word.startColumn,
            endColumn: word.endColumn,
        };
        return { suggestions: createDependencyProposals(range) };
    },
});

Start writing completion to get completion items.

llesha
  • 423
  • 1
  • 15
  • Thank you for the example. In the trigger function, how can I find out which completion item the user has selected? – justadeveloper May 22 '23 at 14:28
  • @justadeveloper that's a good question that I couldn't find an answer to. I looked into source code for CompletionItemProvider. It seems that it is impossible – llesha May 22 '23 at 14:49
  • @ilesha, for what it is worth, I found this answer that might help with my question. https://stackoverflow.com/questions/74809562/how-can-we-get-which-completion-item-is-selected-by-the-user/75442654#75442654 – justadeveloper May 23 '23 at 09:35
  • 1
    @justadeveloper thanks you! I updated the answer with arguments in trigger function – llesha May 23 '23 at 09:50