How to filter monaco-editor sugggestions dynamically depending on text before?

1.1k Views Asked by At

I have a list of suggestions and I want the editor to filter the displayed ones depending on the words typed before, For example if my list of suggestions is ['car', 'dog', 'pet'], if I type "wash." I only want 'car' to be shown as suggestion and if I type "get." I want 'pet' and 'dog' as suggestions.

Here is a sample of my code if it helps:

monaco.languages.registerCompletionItemProvider('typescript', {
            triggerCharacters: ["."],
            provideCompletionItems: () => ({ suggestions: createSuggestions(items) })
});

const createSuggestions = (list) => list.map(suggestion => ({
            label: suggestion,
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: suggestion
        })
);
1

There are 1 best solutions below

0
On

That happens automatically, when you provide a range in the completion item:

                            const offset = model.getOffsetAt(localPosition);
                            const promise = service.getCompletionsAtPosition(model.uri.toString(), offset);

                            void promise.then((completions: CompletionInfo | undefined) => {
                                if (completions) {
                                    const info = model.getWordUntilPosition(localPosition);
                                    const replaceRange: IRange = {
                                        startLineNumber: position.lineNumber,
                                        startColumn: info.startColumn,
                                        endLineNumber: position.lineNumber,
                                        endColumn: info.endColumn,
                                    };

                                    resolve({
                                        incomplete: false,
                                        suggestions: completions.entries.map((entry) => ({
                                            label: entry.name,
                                            kind: this.convertKind(entry.kind),
                                            range: replaceRange,
                                            insertText: entry.insertText || entry.name,
                                        } as CompletionItem)),
                                    });
                                } else {
                                    resolve({ incomplete: false, suggestions: [] });
                                }
                            });