|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | + * Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | + *--------------------------------------------------------------------------------------------*/ |
| 5 | + |
| 6 | +import * as vscode from 'vscode'; |
| 7 | +import { ensureEmojis } from '../common/emoji'; |
| 8 | +import { Schemes } from '../common/uri'; |
| 9 | + |
| 10 | +export class EmojiCompletionProvider implements vscode.CompletionItemProvider { |
| 11 | + private _emojiCompletions: vscode.CompletionItem[] = []; |
| 12 | + |
| 13 | + constructor(private _context: vscode.ExtensionContext) { |
| 14 | + void this.buildEmojiCompletions(); |
| 15 | + } |
| 16 | + |
| 17 | + private async buildEmojiCompletions(): Promise<void> { |
| 18 | + const emojis = await ensureEmojis(this._context); |
| 19 | + |
| 20 | + for (const [name, emoji] of Object.entries(emojis)) { |
| 21 | + const completionItem = new vscode.CompletionItem({ label: emoji, description: `:${name}:` }, vscode.CompletionItemKind.Text); |
| 22 | + completionItem.filterText = `:${name}:`; |
| 23 | + completionItem.sortText = name; |
| 24 | + this._emojiCompletions.push(completionItem); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + provideCompletionItems( |
| 29 | + document: vscode.TextDocument, |
| 30 | + position: vscode.Position, |
| 31 | + _token: vscode.CancellationToken, |
| 32 | + context: vscode.CompletionContext |
| 33 | + ): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { |
| 34 | + // Only provide completions for comment documents |
| 35 | + if (document.uri.scheme !== Schemes.Comment) { |
| 36 | + return []; |
| 37 | + } |
| 38 | + |
| 39 | + const word = document.getWordRangeAtPosition(position, /:([-+_a-z0-9]+:?)?/i); |
| 40 | + if (!word) { |
| 41 | + return []; |
| 42 | + } |
| 43 | + |
| 44 | + // If invoked by trigger charcter, ignore if this is the start of an emoji (single ':') and there is no preceding space |
| 45 | + if (context.triggerKind === vscode.CompletionTriggerKind.TriggerCharacter) { |
| 46 | + if (word.end.character - word.start.character === 1 && word.start.character > 0) { |
| 47 | + const charBefore = document.getText(new vscode.Range(word.start.translate(0, -1), word.start)); |
| 48 | + if (!/\s/.test(charBefore)) { |
| 49 | + return []; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // Update the range on cached items directly |
| 55 | + for (const item of this._emojiCompletions) { |
| 56 | + item.range = word; |
| 57 | + } |
| 58 | + |
| 59 | + return new vscode.CompletionList(this._emojiCompletions, false); |
| 60 | + } |
| 61 | +} |
0 commit comments