Thursday, June 7, 2018

Using the VS Code Integrated Terminal with Remote Hosts

I am in the process of writing some server-side scripts on a remote server. There are three things that would make it easier:

1. If I could write the code directly to the server from VS Code
2. If the integrated terminal in VS Code would automatically log me into that server
3. If I could easily toggle between the code window and the terminal window

I am going to describe how to do all of those things.

Writing Code Directly to the Server in VS Code

To write code directly to the server, I am using an SFTP extension I found in the VS Code Marketplace. The extension I am using is simply called sftp.

To configure it, you open the command palette (Cmd+Shift+P) and select SFTP: Config. This will generate a file called sftp.json within the .vscode directory of your workspace. You can check out the full config options, but basically you just need to specify the host, username, and remote path. So that my code is automatically saved to the server, I set the uploadOnSave option to true in the sftp.json file.

And so that I don't have to log in every time, I am using the privateKeyPath option as well. I won't go into the details here of how to set up SSH for auto login without a password but it is definitely a time saver.


Automatically Logging into the Remote Server

The next thing I wanted to accomplish was automatically logging into the remote server in the integrated terminal. To do that I need to update my workspace settings.

To start I select Code ▶ Preferences ▶ Settings to open the Workspace Settings. Then within the settings, I add some JSON to tell it to call the ssh command with an argument of the server name.


Also, because I like to color code my terminal windows, I found the workbench.colorCustomizations setting which allows me to set a value for terminal.background.

For this change to take effect, I have to restart VS Code. A security feature prompts me to make sure this is what I really want to do. This only happens the first time.


I have to restart VS Code one more time. This time when I open the terminal, it automatically logs me into the remote server so that I can test my scripts.

Toggling Between the Code Window and the Terminal Window

While I like having the terminal window integrated into my IDE, I don't like having to use the mouse to click back and forth between the two windows. Fortunately, someone on Stack Overflow had already solved that problem.

This time I go to Code ▶ Preferences ▶ Keyboard Shortcuts. To make the change, I first have to click on the keybindings.json link:


Then I can paste in the code for my settings.


Now after I save my code, I simply press Ctrl+` to switch to the terminal window, test my code, and then press Ctrl+` again to return back to my code.

0 comments:

Post a Comment

 
Blogger Templates