Hassam Ullah
Hassam Ullah

Reputation: 99

How to make a VS Code command be executed by default when extension enabled?

How to make a command be executed by default when extension enabled in VS Code?

I am creating my first VS Code extension and I have created a command but it is only executable from the command palette.

How do I make it execute as soon as it is enabled in VS Code?

let myStatusBarItem: vscode.StatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left,0);

export function activate(context: vscode.ExtensionContext) {
    let countLines = vscode.commands.registerCommand('line-counter.countLines', () => {
        vscode.window.showInformationMessage('Hello from line-counter');
    });

    context.subscriptions.push(countLines);
    context.subscriptions.push(myStatusBarItem);
    updateStatusBarItem();
}

function updateStatusBarItem(): void {
    const n = getNumberOfSelectedLines(vscode.window.activeTextEditor);
    if (n > 0) {
        myStatusBarItem.text = `$(megaphone) ${n} line(s) selected`;
        myStatusBarItem.show();
    } else {
        myStatusBarItem.hide();
    }
}

function getNumberOfSelectedLines(editor: vscode.TextEditor | undefined): number {
    let lines = 0;
    if (editor) {
        lines = editor.selections.reduce((prev, curr) => prev + (curr.end.line - curr.start.line), 0);
    }
    return lines;
}

Upvotes: 0

Views: 76

Answers (1)

Esteban Dalel R
Esteban Dalel R

Reputation: 43

Anything on the top level of the activation function will be called on activation.

We do this at watermelon for our activity bar object.

Upvotes: 1

Related Questions