Databyte
Databyte

Reputation: 1481

Arguments for Commands in VS Code

So obviously there are arguments for commands and registering a command like

vscode.commands.registerCommand("bla", (arg1: any, arg2: any) => {});

brings arg1 with a strange object containing only one key and that's context; an object holding some information about - you guessed it - the context.

There is also no way for the user to specify arguments. Not through the command palette and not for keybindings.

So are those arguments only for internal stuff or are they supposed to be used by an extension developer?

Upvotes: 14

Views: 12383

Answers (3)

silverbullet069
silverbullet069

Reputation: 1

A little late to this problem, but I've solved this using the fact that function is first-class citizen in TypeScript

You can write a function that return a function, it's that returned function will be called by registerCommand:

// extension.ts
import { test } from "./test"

...

context.subscriptions.push(
    commands.registerCommand(
      `<your extension id>.test`,
      test(arg1, arg2, ...)
    )
  )
// test.ts

// double arrow expression
const test = (arg1, arg2, ...) => () => {
   // do anything you want with extensionPath
}

Upvotes: -1

Max Kessler
Max Kessler

Reputation: 57

Dirty hack: If you don't mind how the command shows up in the editor, you can pass arguments, like ${file}, as the "name" in your launch.json. Then you just grab it from the context like so:

vscode.commands.registerCommand('extensiontest.helloWorld', (context) => { 
   
    type ObjectKey = keyof typeof context;
    const argsKey = 'name' as ObjectKey;
    console.log(context[argsKey]);
    ...

As a side effect, the name of the launch configuration in the drop down list will be {file}, or whatever your arguments are.

I want to stress that this is awful, but I believe it does answer the question.

Upvotes: 1

Michael Liquori
Michael Liquori

Reputation: 629

In keybindings.json you can specify arguments as such:

{
    "command": "workbench.action.tasks.runTask",
    "key": "alt+d",
    "args": "docker"
}

To access keybindings.json open View > Command Palette and type/choose Preferences: Open Keyboard Shortcuts (JSON). You may also want to assign a keyboard shortcut to this command.

Upvotes: 7

Related Questions