Dynamic snippet evaluation in VSCode
It's definitely not possible to execute a script or something similar within a snippet.
You can write an extension for Visual Studio Code instead. The extension must implement a CompletionItemProvider
.
Its provideCompletionItems
method would return a list of CompletionItems
. Their filterText
properties would be set to the texts displayed in the suggestion box (for example "date" or "time") and their insertText
properties would be set to the dynamically computed values.
Finally you would need to register the completion provider using registerCompletionItemProvider
.
You should absolutely take a look on how to create an extension before you start: https://code.visualstudio.com/docs/extensions/example-hello-world
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
);