empire29
empire29

Reputation: 3890

how to force order in vscode extension CompletionItems

I am writing a custom VSCode Extension that helps me add relative (from the workspace) links to files in my project; I have two use cases:

1) search for files by keyword (searches anywhere in the workspace) 2) list files by folder

Since "list files by folder" is more specific, and thus more likely to contain the desired, I want them to show up first in the CompletionItem suggestions.

So when I search for "pictures", i get a list of CompletionItems

../../../../animals/pictures/cat.png (by keyword)
../../../../animals/pictures/dog.png (by keyword)
../../../pets/pictures/dog.png (by keyword)
./pictures/dog.png (by files in folder)

I can add the CompletionItems to the return array in any order I like, and it still lists alphabetically.

Is there any way I can control the order the results list?

Upvotes: 2

Views: 1393

Answers (2)

Mark
Mark

Reputation: 180835

I find this sort of thing handy for sorting the text (which I call 'priority' and set to the sortText property:

    const priority = {
        "title": "01",
        "find": "011",
        "replace": "02",
        "restrictFind": "03",
        "cursorMove": "031",           // added later
        "triggerSearch": "04",
        "triggerReplaceAll": "041",    // added later
        "isRegex": "05",
        "filesToInclude": "06",
        "preserveCase": "07",
        "useExcludeSettingsAndIgnoreFiles": "08",
        "isCaseSensitive": "09",
        "matchWholeWord": "091",
        "filesToExclude": "092"
    };

This way you can go back and insert something new where it belongs logically in the priority list and sort it between prior entries easily.

Upvotes: 0

Matt Bierner
Matt Bierner

Reputation: 65223

Try setting the sortText property on the items you return:

 firstCompletionItem.sortText = 'a';
 secondCompletionItem.sortText = 'b';
 ...

sortText is an arbitrary string used for sorting the order in which completions are shown.

Keep in mind that sortText is only used when completion items match equally well. If you just trigger intellisense on a new line for example, all completion items will match equally well against the empty line, so sortText will be used order them. If however you trigger intellisense after typing the letter a, completions that start with a will be shown before those that do not, regardless of their sortText (after which all the completion items starting with a will be ordered using their sortText)

Upvotes: 3

Related Questions