Alvain
Alvain

Reputation: 61

VSCode: How to programmatically set a handler on editor's language change event in my extension?

I make an extension for VS Code. My task is to add an element to the status bar when working with a specific language, for example, SQL. For other languages, the element does not need to be displayed. I have created a command:

    envStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 80);
    envStatusBarItem.command = aseChangeEnvironmentCommand;
    context.subscriptions.push(envStatusBarItem);

and set the listener:

context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(updateEnvStatusBarItemFn));

In addition, in package.json added the condition "onLanguage: sql" to activationEvents.

I show and hide the status bar element as follows:

    const updateEnvStatusBarItemFn = () => {
        const editor = vscode.window.activeTextEditor;
        if (editor) {
            if (editor.document.languageId === 'sql') {
                let aseCurrentServer = context.globalState.get('aseCurrentServer', '');
                envStatusBarItem.text = `ASE[${aseCurrentServer}]`;
                envStatusBarItem.show();
            }
            else {
                envStatusBarItem.hide();
            }
        }
        else {
            envStatusBarItem.hide();
        }
    };

The problem is that the extension is activated when you change the language in the editor to SQL or open the * .sql file (as per the condition in package.json). The status bar element is shown, but then the extension is considered active and the function of displaying / hiding the status bar element only works on the software-installed onDidChangeActiveTextEditor handler when switching tabs. I could not find a listener related to changing the language in which I could hang my handler. Is there such a way, or should I write feature-request?

Upvotes: 2

Views: 2601

Answers (1)

Alvain
Alvain

Reputation: 61

I received the answer from VSCode team on github:

When the language of a document changes the onDidCloseTextDocument and onDidOpenTextDocument events are fired:

github comment

Description is in VSCode sourcecode.

Upvotes: 3

Related Questions