Dynamic snippet evaluation in VSCode

前端 未结 2 1524
余生分开走
余生分开走 2021-01-11 23:32

Is it possible for a snippet to insert a dynamically computed completion or snippet in Visual Studio Code?

I would like a snippet for inserting date and time strings

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 00:10

    Although, it's possible to achieve simple date-time stuff without extensions:

    "⌚ Date Time SNIPPET": {
        "prefix": "datetime",
        "body": [
            "${CURRENT_YEAR}-${CURRENT_MONTH}-${CURRENT_DATE}T${CURRENT_HOUR}:${CURRENT_MINUTE}:${CURRENT_SECOND}",
        ]
    }
    

    The question is about dynamic snippets. And here's an example of using CompletionItemProvider:

    const datetimeProvider = vscode.languages.registerCompletionItemProvider(
        {
            scheme: 'file',
            // language: 'typescript',
        },
        {
            provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) {
                const completionItem = new vscode.CompletionItem('datetime ⌚', vscode.CompletionItemKind.Snippet);
                completionItem.insertText = new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().split('.')[0];
                return [completionItem];
            }
        },
        // ''// trigger character
    );
    

提交回复
热议问题