Dynamic fragment estimation in VSCode

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

I need a snippet to insert date and time strings from different formats. For example, if you type date , the current date in ISO format will be automatically expanded.

example of expanding a dynamic fragment with dates

Sublime Text has a tool for this in the python API using the on_query_completions method in the EventListener class. There the implementation will be very simple:

 def on_query_completions(self, view, prefix, locations): if prefix == 'date': val = datetime.now().strftime('%Y-%m-%d') return [(prefix, prefix, val)] if val else [] 

I read the User Defined Snippets documentation , but it seems that you can only insert predefined text with tabs and variables that the user fills.

If this is not possible with the functionality open by the API, can I implement something similar using the API with a higher level of extension / extension?

I understand that there is an existing extension called Insert Date and Time , but this works through a command pallet instead of a dynamic extension.

+5
source share
1 answer

It is definitely not possible to execute a script or something similar in a fragment.

Instead, you can write an extension for Visual Studio code. The extension should implement CompletionItemProvider .

Its provideCompletionItems method returns a list of CompletionItems . Their filterText properties will be set to the texts displayed in the sentence window (for example, "date" or "time"), and their insertText properties will be set to dynamically calculated values.

Finally, you will need to register the completion provider with registerCompletionItemProvider .

You should absolutely take a look at how to create an extension before launch: https://code.visualstudio.com/docs/extensions/example-hello-world

+3
source

All Articles