[See my edit below - this is now much easier to do.]
I figured out a way to do what you want but it is a bit of a hack. As you probably know it is easy to bind a task if you can create the task in .vscode/tasks.json and use something like the following:
{
"key": "shift+escape",
"command": "workbench.action.tasks.runTask",
"args": "Start server and process files"
},
It is much trickier to run a script via a keybinding without a pre-existing task. However, you can try the following which takes advantage of the "workbench.action.terminal.runSelectedText",
command. But we need to get the script into a selection first so:
Use the macros extension (which is a little rough) so that we can tie together multiple commands. In your user settings:
"runCommandInTerminal": [
{
"command": "type",
"args": {
"text": "node -v"
}
},
{
"command": "cursorMove",
"args": {
"to": "wrappedLineStart",
"by": "wrappedLine",
"value": 1,
"select": true
}
},
"workbench.action.terminal.runSelectedText",
"editor.action.clipboardCutAction",
// "workbench.action.terminal.focus"
],
This is a general example of a setting "runCommandInTerminal"
that you can then bind to any key chord you wish in keybindings.json, like
{
"key": "ctrl+shift+e",
"command": "macros.runCommandInTerminal"
},
Your example is a little harder because you want to access something like ${file}
which you cannot do in the settings, only tasks.json and launch.json. Fortunately, there is a command which will get the current file: "copyFilePath"
. So try
"runCommandInTerminal": [
"copyFilePath",
{
"command": "type",
"args": {
"text": "touch "
}
},
"editor.action.clipboardPasteAction",
{
"command": "cursorMove",
"args": {
"to": "wrappedLineStart",
"by": "wrappedLine",
"value": 1,
"select": true
}
},
"workbench.action.terminal.runSelectedText",
"editor.action.clipboardCutAction",
// "workbench.action.terminal.focus"
],
First get the file path, then output the first part of your script command "touch
".
Next append the filepath to the end of the command.
Move the cursor to select the preceding.
Run the selection in the terminal.
Cut the selection from the editor.
This can be run with your keybinding. You will see the flash of the script being typed and cut but your editor code will be unaffected. It is best to run it from a blank line in the editor but you can run it from the beginning of a line of unrelated code if you wish (but indentation may be lost for now).
It is hacky but seems to work. I would love to know if there is an extension or another way to do this cleaner.
EDIT May, 2019:
Since my original answer (as @Jeff indicated) vscode has added the sendSequence
command. And the ability to use variables with that command. So now the OP's question is much easier to accomplish:
{
"key": "alt+x",
"command": "workbench.action.terminal.sendSequence",
"args": {"text": "touch ${file}"}
}
in your keybindings.json file. See variables with a sendSequnce command.