Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set language of a text document in a VSCode extension

I have a Visual Studio Code extension where I try to open a virtual editor:

vscode.workspace.openTextDocument(vscode.Uri.parse(previewSchema + ":" + path))

context.subscriptions.push(extractHibernateLogCommand, vscode.Disposable.from(
    vscode.workspace.registerTextDocumentContentProvider(previewSchema, hibernateExtractorProvider)
));

Those documents are always language:plain-text. Is it possible to change this programmatically to "SQL" to have the correct highlighting?

Full code

like image 966
GreenRover Avatar asked Aug 16 '17 06:08

GreenRover


1 Answers

Since VSCode 1.28 (September 2018), it's also possible to set the language mode for a document after it has been created using languages.setTextDocumentLanguage():

Set (and change) the language that is associated with the given document.

Note that calling this function will trigger the onDidCloseTextDocument event followed by the onDidOpenTextDocument event.

Here's a simple example that opens a document containing {} and sets the language to JSON:

vscode.workspace.openTextDocument({content: "{}"}).then(document => {
    vscode.window.showTextDocument(document);
    vscode.languages.setTextDocumentLanguage(document, "json");
});
like image 171
Gama11 Avatar answered Oct 18 '22 05:10

Gama11