Joshua's Docs - VS Code Settings, Power User Tips, and Misc Notes
Light

Resources

What & Link Type
Official VS Code Docs
   - Tips and Tricks
   - Updates
   - Default Settings Reference
Official MS Docs on VS Code (very good!)
Python with VS Code My guide for using VS Code with Python
VSCodeTips Community / Forum for sharing VS Code Tips

Opening VS Code Via CLI

Opening VS Code Via CLI - Windows

VSCode is exposed, via the system PATH, as code. This allows you to do the following, in a standard command prompt:

  • Open a directory: code {dir}
    • You can use code . for opening the current directory
  • Open a specific file code {filePath}

If you notice that every time you open a file with this method, it also opens a file called cli.js, there is likely a permission mismatch; e.g. you set Code.exe to always open as an Administrator, but the console you called code from was not launched as an administrator.

  • The fix here is to simply use an elevated command prompt, or remove the setting that code.exe always run with Administrator privileges.
  • Relevant issues: #72521, #91613

Opening VS Code Via CLI - macOS

It takes an extra installation step to add Code to your $PATH.

After you have done that, you can call it from your terminal just as you can in Windows, with code . to open current directory, or code {PATH} to open a path.

If this stops working, check this answer for details.

Piping Data from CLI into VS Code

# Anonymous, inline
# blocks terminal until closed
echo "foo" | code -

VS Code Pro Tips - Use VSCode Faster and More Efficiently

VSCode has a large surface area, but if your goal is to work faster and more efficiently, these are some of the things I would focus on getting familiar with:

  • The Command Palette!
    • A quick command selector / executor, brought up with CTRL + SHIFT + P (CMD + SHIFT + P on macOS), or via View -> Command Palette
    • You can do most tasks in VS Code through this prompt
  • Snippets
    • Kind of like macros, but even more powerful
  • Go to symbols
    • Quickly navigate to symbols within a document
    • I use CTRL + P (go to file) and then type @, instead of the CTRL + SHIFT + O shortcut, because it is one less thing to remember
  • VS Code's many navigation options in general (go-to-definition, go-to-implementation, etc.)
  • Vim extension, if that is already your thing.
  • Making use of advanced settings:
    • Customizing colors in scrollbar (workbench.colorCustomizations { editorOverviewRuler.* })
    • Maximum number of open tabs:
      {
      	"workbench.editor.limit.enabled": true,
      	"workbench.editor.limit.value": 10,
      	"workbench.editor.limit.perEditorGroup": true
      }
    • Turn off annoying autocomplete for words: "editor.wordBasedSuggestions": false
    • And many more! Make sure to keep up with / skim VS Code release notes for new improvements to take advantage of!
  • My post: 5 Underrated Built-in VSCode Features 😊
  • "Tasks"

Troubleshooting

  • Stale path / environment variables in terminal
    • Try completely restarting VSCode - close all windows and relaunch
    • Try running VSCode as an administrator; this can often fix path expansion issues
    • Check which shell you are using as the integrated terminal
      • You can override with settings.json -> terminal.integrated.shell.{OS}
  • TypeScript import autocomplete keeps using absolute or incorrect relative paths
    • Try setting settings.json -> "typescript.preferences.importModuleSpecifier": "relative"
  • Markdown preview is flashing / jumping all over the place / scrolling randomly
    • This happens intermittently to me, and I haven't yet found the exact culprit. However, some settings that seems to minimize this are:
    {
    	"markdown.preview.markEditorSelection": false,
    	"markdown.preview.scrollEditorWithPreview": false
    }
  • VSCode refuses to stop inserting spaces, even with "editor.insertSpaces": false and "editor.detectIndentation": false
    • Make sure that tab control mode is not set to tab moves focus
    • Make sure there is not a conflicting extension installed
      • If this is only happening with indenting in lists in Markdown, and you have the Markdown All in One extension installed, try changing the markdown.extension.list.indentationSize to inherit instead of adaptive (details here and here)
  • Files keep opening in the wrong tab / wrong tab group (non-active group)
    • If every time you try to open a file, it keeps opening in a different tab group than your current active tab group, check to see if your tab group is locked. Turn off the tab group lock if you want additional files to be able to open in it.
  • VSCode keeps changing my file when I save, but editor.formatOnSave is set to false / off!
    • Check for settings like files.trimTrailingWhitespace, which alter the current file on save, regardless of editor.formatOnSave.
    • Some extensions might also run actions on save, but not respect this setting.

🔗 - Resource: VSCode - Common Error Cases

Troubleshooting - General Checklist

  • Check the relevant logs, under the output view
    • Command Palette -> Output: Focus on Output View
    • There is a dropdown to switch between different output channels
  • Check applied settings (check your project-specific settings.json as well as your global settings)
  • Reload VS Code
    • Command Palette -> Developer: Reload Window
  • Use extension bisection to find which extension is breaking things
    • Command Palette -> Help: Start Extension Bisect
  • Make sure setting key-values make sense
    • If targeting multiple languages, make sure you are using "[alpha][bravo]": {} (e.g. "[javascript][typescript]": {}) and not "[alpha, bravo]": {}

Debugging / Launching

Debugging Resources

Launch.json Tips

  • For Yarn, set runtimeExecutable to "yarn", and runtimeArgs should just be an array of the commands you would normally type after yarn run. E.g:
    {
    	"runtimeExecutable": "yarn",
    	"runtimeArgs": ["debug-build"],
    }
  • If you have breakpoints for all "Uncaught Exceptions" on, you might want to exclude node_modules, or any other third-party directory, from that rule (if you are seeing a bunch of exceptions you don't care about).
    • You can do this with the skipFiles feature.
    • Example: "skipFiles": ["<node_internals>/**", "${workspaceFolder}/node_modules/**/*.js"]
  • Viewing the results in the integrated console
    • Use "console": "integratedTerminal"

Strange Issue with Auto-Attach

I've noticed a strange issue with auto-attach in VSCode. Even if I have it turned on, it (the VSCode debugger) often will not work if Chrome is open, although the auto-attacher in Chrome works just fine. It's almost like Chrome is hijacking the debugger port or something.

The fix for me was to manually create a launch.json entry, rather than relying on only the --inspect-brk or --inspect flag for Node. In addition, make sure the entry has type: "node", not type: "chrome".

If you don't have a launch.json file, you can also try toggling autoattach on & off via the command palette (or look at the bottom left of the window for the toggle status)

Manual Attachment

If auto-attach is not working for you, another option is to manually attach to a running node process; open the Command Palette and then run the Attach to Node Process command. Details here

Disable annoying word autocomplete

{
	"editor.wordBasedSuggestions": false,
	"javascript.suggest.names": false
}

Setup basic code formatting rules

{
	"editor.tabSize": 4
}

Disable CRLF (\r\n) endings on Windows

{
	"files.eol": "\n"
}

Force indent style

If you really want to ensure a specific indent style in a shared repo, this is a forceful way to do so, in your .vscode/settings.json:

{
	"editor.insertSpaces": true,
	"editor.tabSize": 4,
	"editor.detectIndentation": false,
	"editor.formatOnSave": true,
	"editor.autoIndent": "full"
}

Change Linting / Error Styling

The main way that VSCode tracks if something is a "problem" is by having it flagged as either a warning or an error. Linters plug into this system, instead of defining their own types of problems, so unfortunately customization is often limited.

The first way to customize warnings and errors is in our VSCode settings.json to use workbench.colorCustomizations and the nested sub-properties for editorError.__, editorWarning.__, etc. For example, if we wanted to change the error red squiggly to appear lighter, with some opacity, we could use:

"workbench.colorCustomizations": {
	"editorError.foreground": "#ff00006e"
}

The second way is to have your linter actually emit different problem types to VSCode. For example, you can tell your linter to report all lint violations as warning instead of error:

🚨 -- WARNING -- 🚨: In general, having your linter emit warnings instead of errors is not a great idea, especially for large codebases that rely on automated lint checks to enforce clean PRs; this could allow lint tests to pass that should really fail.

Extensions:

Exporting Plugins as a List

For your personal dotfiles or sharing with others, you might want to export your list of installed extensions to a file. You can do this with code --list-extensions.

⚠ Warning: --list-extensions exports all installed extensions, regardless of whether they are enabled or disabled.

A full list of available CLI options are available in the VSCode docs.

VSCode-Icons - Customization

For customizing the icons, checkout "Fine Tuning" in the Wiki.

Here is an example of how you can get VSCode-Icons to apply an existing icon its library to a file extension it doesn't normally recognize. In this example, I'm having it use the makefile icon for justfile config files:

"vsicons.associations.files": [
	{
		"icon": "makefile",
		"extensions": ["justfile"],
		"filename": true,
		"format": "svg"
	}
]

Settings

Per directory settings

You can control settings per root directory (workspace/project) through {WORKSPACE_ROOT}/.vscode/settings.json.

  • This file will be automatically created if you touch a workspace level setting (through the GUI), but you can also manually create it:
    • mkdir .vscode && touch .vscode/settings.json

You can add a file (extensions.json) to your workspace .vscode folder, so that when other devs checkout your code, VSCode will recommend for them to install the extensions that will help them the most. Read more here.

Settings Tricks

Selectively Applying Settings

Sometimes you want certain VSCode settings to apply to only a subset of all the files present in your working directory. There are a few different ways this can be accomplished:

Workspaces

Workspaces - Configuration File

  • Adding specific files instead of folders
    • Not supported (yet) 😢. Please go upvote / thumbs-up Issue #45177

Javascript Type Safety

There are are a bunch of options for getting some type-safety with JS in VScode, and better intellisense. Of course, you are free to also use linters, like ESLint (see my JS DevOps Cheatsheet), but that is not the only option. There is actually built-in type checking options!

To get the full power of this feature, you really should use JSDoc comments to provide additional type annotations, control inferred types, and so on. This is a hefty topic, so I've moved all my notes on it to a dedicated JSDoc cheatsheet page, under this section.

More resources on internals:


Recovering Work or Files

I won't lecture you on proper file backups and version control systems, but will just say this should only be used as a last resort if you accidentally deleted files and are looking to recover them.

VSCode does actually maintain some backups and revision history. This S/O should steer you in the right direction for finding the main backups folder. You can also try the Command Palette - Developer: Open Logs Folder - and then go up from that directory until you find the parent folder with the Backup folder inside it.

There is probably also some sort of internal database / repository for managing local edit operations, so that undo and redo can work, but I'm not sure how to easily access that.

Coming from Notepad++ / "where is X?"

If you are coming from using Notepad++, or a vastly different IDE, you might be looking for certain things. For example:

  • "Show all characters"
    • In Notepad++, this shows whitespace characters (\t, \s, etc.), as well as EOL (end of line) characters (\r or \n). I have not a single method to do both on VSCode, but you can do them separately.
      • Whitespace: Menu -> View -> Render Whitespace
      • EOL: There is an extension that shows them
  • How do I view the file summary, with word-count, etc.?
    • There is no one "summary" view, but character count can be tabulated by selecting text (displays in bottom bar by default), and word count can be displayed by installing an extension, such as Microsoft's aptly named "Word Count"

Searching

  • You can use regex
  • You can filter your search by specific files and by directory
    • See guide here
    • Uses glob syntax
    • Use , to separate multiple patterns
    • Use ! to negate a pattern
  • You can exclude files and directories
    • Inherits settings from .gitignore and global settings

💡 If you want files to stop showing up in the command-palette / file picker, you need to remove them from your history. You can do this quickly, for all files, with the command File: Clear Recently Opened.

Showing the Currently Active File in the Explorer Sidebar

To scroll to and show the active file in the explorer sidebar, use the File: Reveal Active File in Explorer View command.

This should happen by default with most files, except if they are excluded.

Hidden Files Not Showing up in the Sidebar File Explorer

Wondering why you can't see .git/ in the file explorer side pane? It, among a few other presets, is excluded by default thanks to the files.exclude default value.

To override, set your own value for files.exclude in your VSCode settings.


Linting / Formatting Controls

VSCode - Built-in Formatting Options

First, I want to point out that you can customize settings per language in VSCode, no extension required. Just put the language specifier as the JSON key, and then the settings as the object value. Like so:

{
	"editor.tabSize": 4,
	"[php]": {
		"editor.tabSize": 2
	}
}

You can even specify certain actions to be ran after certain file types are saved, by using editor.codeActionsOnSave under a language specifier!

If you are have multiple language formatting extensions installed, and want to tell VSCode which one to use per language, that is another thing you can do with settings:

{
	"[php]": {
		"editor.defaultFormatter": "vscode.php-language-features"
	}
}

If you run into issues with the format on save feature, where it doesn't seem to respect a global setting, you might find success by moving the setting under the specific language:

{
	// Global
	"editor.formatOnSave": true,
	// Override at the language level
	"[yml][yaml]": {
		"editor.formatOnSave": false
	}
}

Also, if VSCode seems to be auto-formatting on save despite the setting set to false, check for extensions or settings like files.trimTrailingWhitespace, which always execute regardless of editor.formatOnSave.

JS Linting

Check out my notes here.


Building an extension


Using VS Code for Markdown Editing

VS Code can actually be pretty powerful as a Markdown editor; I have used it to create and edit blog posts, technical documentation pages, and more.

📘 Official Resource: Markdown Editing with Visual Studio Code

Here are some quick tips for using VSCode as a Markdown editor:

  • It has a live markdown preview pane
  • There are many extension which enhance the markdown editing experience
  • You can link between documents, and VS Code will let you click through in either the editor or preview pane
  • You can customize the font of the editor just for Markdown, so your regular coding experience stays the same
    • For example:
      {
      	"[markdown]": {
      		// This changes the appearance of Markdown *source* styling, not the live preview
      		"editor.fontFamily": "'Hack', 'Times New Roman', monospace",
      		"editor.fontSize": 14,
      		"editor.letterSpacing": 0.8,
      		"editor.wrappingStrategy": "advanced",
      		// With a non-mono-space font, tabs tend to get shrunk
      		"editor.tabSize": 6
      	}
      }

Automating Visual Studio Code

Tasks

📄 Main Doc Tasks

Snippets

Main doc: User Defined Snippets

There is a lot in this doc, so make sure to read carefully!

Snippets - Advanced Transforms

  • Examples:
    • Official docs: here
  • Escaping: It's complicated!
  • Combining tab-stops with variables
    • You can combine tab-stops (where the cursor tabs between) and variable / macros, by nesting:
    • Example: "src=\"${1:${CLIPBOARD:IMAGE_SOURCE}}\"

Wishlist: Things I Would Like To See Fixed or Added In VSCode

Markdown Source Last Updated:
Mon Dec 04 2023 04:05:55 GMT+0000 (Coordinated Universal Time)
Markdown Source Created:
Sun Sep 15 2019 09:21:24 GMT+0000 (Coordinated Universal Time)
© 2024 Joshua Tzucker, Built with Gatsby
Feedback