Skip to content

Instantly share code, notes, and snippets.

@rniemeyer
Last active August 14, 2018 15:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rniemeyer/47a66d098b173c741bfff8c70544b366 to your computer and use it in GitHub Desktop.
Save rniemeyer/47a66d098b173c741bfff8c70544b366 to your computer and use it in GitHub Desktop.

Visual Studio Code

The Do-It-All Tool For Your Web Development Backpack

Ryan Niemeyer - ryan@knockmeout.net - @rpniemeyer - leankit.com

Start here for all things VS Code: https://code.visualstudio.com/

Github project here: https://github.com/Microsoft/vscode

Presentation notes:

General Capabilities

1. Command Palette

Shift + Cmd + P - Access to almost anything that you can do in the editor (and you can see keyboard shortcuts)

2. Explorer

Cmd + P - Open/find files in your project. Type a ? to see other modes that you use for searching.

3. Toggle Sidebar

Cmd + B - Toggle open/closed the sidebar. On a smaller screen, you can save space by closing it and using Cmd + P to open files.

4. Zen Mode

Cmd + K, Z - Opens zen mode which makes the editor full screen and gets rid of the buttons/menus. Good for focused work.

5. Zooming In/Out

Cmd + +/- - Zooms the entire editor in or out (not just code editor). Using the Command Palette, search for "font" and you can zoom just the editor (can map to keyboard shortcuts, if that is a common need for you).

6. Minimap

The minimap is a small overview of your file in the gutter. Use the Command Palette (search for "minimap") to toggle this on/off.

7. Terminal

Ctrl + ~ - Open a terminal in the root directory of the project that you are editing. Can split the terminal and move it between being docked on the bottom or side.

8. Calling code from command-line

code --help - From a terminal, you can run the code command-line tool. The most common use of this would be to open the current directory that your terminal is in (perhaps after cloning a repo or creating a new project).

Customizing VS Code

9. File Icons

Icons that appear next to files in the file explorer. I like the extension vscode-icons for some colorful and interesting icons.

10. Theme

Cmd + K, Cmd + T - Change themes for VS Code. VS Code allows for theming a most elements of the editor. Material Theme is nice, as well as Cobalt2.

11. Settings

Cmd + , - Access all of the settings. Override at a user (all instances of VS Code for your user) or workspace level (this instance of VS Code). Workspace settings are saved either in the .vscode folder when you are editing a single directory or when using Workspaces they are saved in the single workspace file.

12. Font With Ligature

A popular choice is Fira Code. After installing, you will want to update your VS Code settings "editor.fontFamily": "Fira Code", "editor.fontLigatures": true.

13. Key Bindings

Cmd + K, Cmd + S - edit keybindings. Hover over the keybinding itself, if you forget the symbols (alt, ctrl, shift, cmd, etc.). The Source column indicates whether it is a default binding or one that your user defined. The When column indicates the context for when the binding is active (could have the same binding that applies in the terminal vs. editor).

Navigation

14. Basic Navigation in a File

Cmd + Up - Top of file Cmd + Down - Bottom of file Cmd + Left - Beginning of line Cmd + Right - End of line Alt + Left - Move word by word to the left on a line Alt + Right - Move word by word to the right on a line

Add Shift modifier to any of the above to select while moving

Ctrl + G - Go to a specific line in the file

15. Splitting / Moving Windows

Cmd + \ to split the window

Can find other splits like splitting down (and bind to keys as necessary) in the Command Palette.

16. Navigating Between Windows

Cmd + 1 to go to first set of tabs. Cmd + 2, 3, 4, 5, etc. to move to additional sets of tabs. Ctrl + Tab navigate between files in a group.

17. Navigating Symbols

Shift + Cmd + O - navigate between symbols (methods, properties, variables, etc.) in a file. Cmd + T navigate between symbols for your entire project. Much faster than searching or scrolling and provides good context (variable vs. method).

18. Find in File / Global

Cmd + F - find in a file Shift + Cmd + F - find globally Can add choose whether match is case sensitive, matches partial words, or to use a regular expression. You can include specific folders (maybe only sometimes search ./node_modules) or you can unclick the blue box on the gear for files to exclude and it will search all files.

19. Find All References / Peek + GoTo Definition

Shift + F12 - Find all references - find all the places where a function is called (traces dependencies through your files). F12 - Go To Definition - jump to where a function is defined Alt + F12 - Peek Definition - show an inline view of the function definition

Also, you can hold down Cmd and hover over a function and see a small peek into the definition above and Cmd + Click to navigate to the definition.

Editing

20. Creating Files / Deep Path

When creating a new file from the file explorer, you can type a deep path (/src/app/data/index.js) and it will create necessary directories along the way.

21. Language Mode

In the lower right-corner, you can click on the file type and change the language that VS Code uses for a file. You can also find this in the Command Palette (search "Language"). Sometimes you have files with an extension that doesn't match the actual type of file (maybe for a good reason).

22. Refactoring

Ctrl + Shift + R - VS Code supports a number of refactoring options. One that I use often is to select a string, and choose to turn it into a constant. You can also select blocks of code and refactor into a method along with a number of other options.

F2 - Rename symbol. When you select a symbol name (argument, properties, variable, function, etc.) and choose to Rename symbol it will allow you to rename all instances of it in the current scope (so much better than a find/replace).

23. Control Characters + Whitespace

From the Command Palette search for "Whitespace" and you can toggle whitespace characters on and off. From the Command Palette search for "Control" and you can toggle control characters on and off.

24. Multi-cursor

Allows you to have multiple active cursors that all respond to your keystrokes. Each cursor can also copy/paste its own buffer.

Alt + Click - will add an additional cursor Cmd + D will select the next instance of the text that you have selected with an additional cursor Shift + Cmd + L will select all instances of the text that you have selected with cursors for each From the Command Palette you can also select a block of lines and choose to "Add Cursors to Line Ends"

Moving around with Alt + Left or Alt + Right and selecting with the Shift modifier is useful in scenarios where you want each cursor to copy a separate piece of text.

25. Move line up/down

Alt + Up or Alt + Down - move a line up or down (without having to cut and paste it).

26. Folding / Unfolding

Cmd + K + 1, 2, 3, 4 - Fold all of the code at a certain level. Sometimes useful in files to collapse the low-level details, while you get an overview and then dig into the specific area that you need to change. I like to use this in test files. Cmd + K, Cmd + J - Unfold all of the code

27. Undo Cursor Position

Cmd + U - brings you back to the last place that you edited Ctrl + - - cycles through recent places that you were editing

28. Problems

Extensions (like ESLint) can contribute to a list of problems in a file. When problems are found, the file turns red in the file explorer and you can see red in the gutter of the file where the problems exist.

Shift + Cmd + M - opens the problem list to see all problems in a file F8 - cycles through the problems

Source Control

VS Code comes with Git support built-in and has extensions for any other source control systems that you might be using.

29. Comparing Two Files

Cmd + Click on two files in the file explorer and right-click on either to choose "Compare Selected". This allows you to diff any two files in your project.

30. Source Control - GIT

The Source Control tab of the sidebar allows you to see changed or staged files and commit files or access other commands. The status bar in the bottom allows access to switching or creating branches.

In the editor, changes have a blue indicator in the gutter, new lines have a green indicator, and deleted lines have a red indicator. You can click on the indicator in the gutter to see a diff of changes, revert the changes, or even stage individual changes in a file.

Snippets

31. Creating Snippets

Go to Code > Preferences > User Snippets to edit your snippets. You can define snippets at a global level or per language (most common).

Some sample snippets:

	"Print var to console": {
		"prefix": "logv",
		"body": [
			"console.log( \"$1\", $1 );",
			"$2"
		],
		"description": "Log a variable to console"
	}

This snippet is accessed when typing logv and then tabbing. The first tab stop will create two cursors with one in the quotes and one in the second argument. This allows you to type a variable name and hit tab again to move to the next line of code.

Here is one that I use in testing:

"calledOnce.and.calledWith": {
		"prefix": "shc",
		"body": [
			"$1.should.be.called${2|Once,Twice,Thrice|}",
			"	.and.calledWith( $3 );",
			"$4"
		]
	}

In this one, I can type a variable name and then choose between Once, Twice, or Thrice before moving to assert the arguments that it was called with.

For testing (mocha), I often use simple snippets as well:

"describe": {
		"prefix": "des",
		"body": [
			"describe( \"$1\", () => {",
			"	$2",
			"} );",
			""
		]
	},
	"it": {
		"prefix": "itt",
		"body": [
			"it( \"$1\", () => {",
			"	$2",
			"} );",
			""
		]
	},
	"beforeEach": {
		"prefix": "bef",
		"body": [
			"beforeEach( () => {",
			"	$1",
			"} );",
			""
		]
	}

Further info: https://code.visualstudio.com/docs/editor/userdefinedsnippets

Debugging

32. Debug a Node Program

VS Code is known for how well it can debug problems like those running in Node. When going to the debug tab of the sidebar, you can define a run configuration by clicking the gear icon.

Common choices for debugging node would be to: Launch Program - launch and debug your program directly from VS Code Attach by Process ID - allows you to pick a process running on your machine to attach to (run program like node --inspect index.js to allow attaching or node --inspect-brk index.js to force the program to wait until the debugger attaches Attach to Remote Program - allows you to specific an address and post to attach to a program running remotely (perhaps in a docker container on your machine).

The launch configurations support a variety of properties to configure your debugging experience that are futher described in the documentation:

Basic debugging info: https://code.visualstudio.com/docs/editor/debugging Node.js specific info: https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_attaching-to-nodejs

33. Debug Chrome

Install this extension. This will allow you to create Chrome launch configurations for either launching a web application in Chrome or attaching to an existing Chrome instance. With this extension you can set breakpoints in VS Code and hit them while using your web application in Chrome.

Additional documentation for the extension: https://github.com/Microsoft/vscode-chrome-debug

Extensions

34. Some that I like:

  • GitLens. Adds a ton of useful tools to VS Code related to Git. This includes nice blame information on each line as well as a sidebar tab for exploring a branch of file history to see diffs of individual changes.

  • ESLint - Adds eslint support to VS Code for evaluating your code for problems. Set eslint.autoFixOnSave : true in your settings, so eslint can address and fixable problems automatically. You will need to ensure that your files.autoSave option is set to off, onFocusChange or onWindowChange for this to work.

  • EditorConfig - Extension for working with https://www.npmjs.com/package/editorconfig which is useful in an environment where you have people using a variety of editors.

  • Prettier - Extension for working with Prettier for automatic code formatting. Useful to ensure that all code in a project is formatted the exact same way.

  • SQL Server - Create connections to SQL Server instances and run scripts against your server and get intellisense when editing SQL files.

  • Docker - Adds intellisense for various docker files and access to running common docker commands.

Extensibility

35. Writing Your Own Extension

Documentation for building extensions: https://code.visualstudio.com/docs/extensions/overview Examples: https://code.visualstudio.com/docs/extensions/samples

Installing the yeoman generator:

npm install -g yo generator-code
yo code

Activation code for my sample word-shortener extension:

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require("vscode");

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log(
		'Congratulations, your extension "word-shortener" is now active!'
	);

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	const disposable = vscode.commands.registerCommand(
		"extension.shortenWord",
		function() {
			const editor = vscode.window.activeTextEditor;
			if (!editor) {
				return;
			}

			const { document: doc, selections } = editor;

			editor.edit(function(edit) {
				// Loop through all selections (multi-cursor)
				for (const selection of selections) {
					// Get the text
					let text = doc.getText(
						new vscode.Range(selection.start, selection.end)
					);

					// Shorten the text like: testing -> t5g
					if (text && text.length > 3) {
						const shortText =
							text.substr(0, 1) +
							(text.length - 2) +
							text.substr(text.length - 1, 1);
						edit.replace(selection, shortText);
					}
				}
			});
		}
	);

	context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {}
exports.deactivate = deactivate;

Honorable Mentions

  • Tasks - run npm, grunt, gulp scripts or integrate your own external calls into vs code.

  • Multi-root Workspaces - include multiple directories in a single instance of vs code.

  • Insider edition - Install a build that has the latest release each day

  • VS Live Share - allows real-time collaboration.

    • Sign-in with Github or Microsoft credentials
    • Start a collaboration session and send the link to another user
    • User can join your session and navigate your files and make edits (with permissions)
    • Can also share your terminal (read-only or read/write)
    • Can share a port (like if you are running a web application on port 8080, you can share port and user can run in their machine).
  • Keyboard Shortcut Sheets (PDF)

Thanks!

Ryan Niemeyer ryan@knockmeout.net

@JamesSkemp
Copy link

Belatedly, would love to see a short video of you doing what you did at THAT Conference with adding wrappers around a SQL statement. I'm already a big fan of VS Code, but that demo was a big kick in the seat to learn how to use multi-cursors properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment