Home > Blockchain >  How to get the language of the file according to its extension?
How to get the language of the file according to its extension?

Time:06-24

I am having problem on this one, How to find the language of the file according to its extension using the vscode API? i tried vscode.languages.getLanguages but I don't think that's the right one.

CodePudding user response:

Do you mean get the targeted opened-file's language?For that you can use window.activeTextEditor?.document.languageId .The docs are here.

vscode.languages.getLanguages is the API that get the vscode's registered language,in other words,get the language list that vscode can recognize.If you want to know the opened file's language,you should use window.activeTextEditor?.document.languageId.

Also,you can use the event vscode.window.onDidChangeActiveTextEditor with it to keep you always get the opened-file's language.

For instance,in my extension,I code like this:

//When the texteditor change,it will be called
private initialListener(){
  vscode.window.onDidChangeActiveTextEditor(this.theScheduler["changeLanguage"])
}             

theScheduler is a object like this:

{
 changeLanguage:function(){
    let text = window.activeTextEditor?.document.languageId; //Get the targeted file's language
//do something
}

My extension's source code are here,you can view it as a reference. I'm sorry that the code's annotation is chinese friendly,do hope it can help you some.

  • Related