Change the VS Code terminal directory with a keyboard shortcut

#VSCode #PowerShell #Windows

I love VS Code. It's got all of the features and tools that I need for coding and testing.

When I'm working on a file in the Editor pane and I want to run it or test a command in the Integrated Terminal, I have to manually navigate to the folder where the with a series of cd commands and Tab autocompletes.

If I exit or restart the Terminal, the working directory switches back to the root of my workspace and I have to repeat the process over again.

I have to deal with this annoying quirk dozens of times during the day and it gets very repetitive to keep typing cd.

To make my life easier, I added the keyboard shortcut Ctrl+Alt+c on my Windows machine to change the Integrated Terminal's working directory to the folder of the file I'm currently editing. This shortcut basically sends the command cd 'directory of the current file' so I don't have to keep typing it.

Run this script in the VS Code Integrated Terminal with PowerShell:

$json = @'
// Place your key bindings in this file to override the defaults
[
    {
        "key": "ctrl+alt+c",
        "command": "workbench.action.terminal.sendSequence",
        "args": {
            "text": "cd \"${fileDirname}\"\u000D"
        },
        "when": "editorTextFocus"
    }
]
'@

Set-Content -Path "$env:APPDATA\Code\User\keybindings.json" -Value $json -Encoding UTF8

After running this code in the Integrated Terminal, open the Command Palette (Ctrl+Shift+p), type and run “Developer: Reload Window”. This will reload Code and apply the new shortcuts.

Now, you can use the keyboard shortcut Ctrl+Alt+c to quickly change the Integrated Terminal's working directory to the folder of the file you're currently editing.

Footer image

Discuss...